Legal Information

Information in this document is subject to change without notice and does not represent a commitment on the part of Microsoft Corporation. Companies, names, and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents or pending patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. The furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property rights.

This is a preliminary release of the documentation. It may be changed substantially prior to final commercial release. This document is provided for informational purposes only and Microsoft Corporation makes no warranties, either expressed or implied, in this prerelease document.

Information in this document is Microsoft Confidential.

©1996 by Microsoft Corporation. All rights reserved.

ActiveMovie, ActiveX, DirectDraw, DirectX, Microsoft, MS-DOS, Visual C++, Visual Basic, Win32, Windows, and Windows NT are either registered trademarks or trademarks of Microsoft in the United States and/or other countries.

Apple and QuickTime are registered trademarks of Apple Computer, Inc.

Asymetrix and ToolBook are registered trademarks of Asymetrix Corporation.

Unicode is a trademark of Unicode, Inc.


About Filter Graph Architecture

This article describes the building blocks of the filter graph architecture of Microsoft® ActiveMovie™ application programming interface. It describes the role of the objects in the system (such as the filter graph manager, filters, and pins) and introduces the programming models for both application and component development . It also introduces the model that controls and manages the streaming of multimedia data.

What Is ActiveMovie?

ActiveMovie is an architecture that controls and processes streams of multimedia data; it is also a runtime that uses this architecture to allow users to play digital movies and sound encoded in various formats, including MPEG-1.

The playback capability makes use of video and audio hardware cards that support Microsoft DirectX™ set of application programming interfaces (APIs). ActiveMovie also plays movie files in audio-video interleaved (.avi) or Apple® QuickTime® (.mov) format.

The ActiveMovie architecture defines how to control and process streams of time-stamped multimedia data by using modular components called filters connected in a configuration called a filter graph. An object called the filter graph manager is accessed by applications and controls how the filter graph is assembled and how data is moved through the filter graph.

The filter graph manager provides a set of Component Object Model (COM) interfaces to allow communication between the filter graph and the application. Applications can directly call the filter graph manager interfaces to control the media stream or retrieve filter events. Or they can use the ActiveMovie ActiveX™ (.ocx) control for higher-level programming. A subset of Media Control Interface (MCI) commands is also available for backward compatibility with Microsoft Video for Windows® 1.x and compliance with the OM-1 MPEG MCI specification.

ActiveMovie is the architecture to use for most new multimedia applications for Windows 95 or Windows NT®. With a few exceptions, it replaces multimedia playback services, APIs, and architectures provided by Microsoft in earlier versions of the Windows Software Development Kit (SDK). However, libraries will continue to be available and supported for applications that use the earlier Microsoft multimedia playback services, such as Microsoft Video for Windows. The first release of ActiveMovie does not provide a corresponding replacement for every solution found in the previous multimedia technology. For example, there is no video capture capability built into the runtime. In these cases, you may find an opportunity to use the ActiveMovie architecture to provide your own solutions with the help of the many samples provided in this SDK.

You can access ActiveMovie through the COM interface, the ActiveMovie ActiveX control, or MCI, as shown in the following illustration:

Because of the flexible, modular design of ActiveMovie architecture, there are many potential uses and applications for filter graphs. Some examples include filter graphs that implement video capture, control of remote devices such as VCRs, animation sequencing, and MIDI recording and editing.

Choosing the Right Programming Model

ActiveMovie is accessible at many levels, and the approach you use depends on your requirements and the investment you plan to make in development. You might plan to rewrite an existing multimedia program, write a new multimedia program, or perhaps add multimedia capabilities to an existing program. Typically, existing applications that use the MCI command set are easily ported, whereas applications that access lower-level multimedia services will require more time to rewrite. For new applications, ActiveMovie playback services can be quickly added by using the ActiveMovie ActiveX control, or with a few direct functions, calling the COM interfaces. For C or C++ programmers, you can write filters that add specific processing capabilities to multimedia data already managed by existing filter graphs.

Rewriting Existing Applications

If you are adapting an application that currently plays AVI-encoded movies and sounds to use ActiveMovie, you have several choices. These choices depend on the services the application uses and your goal. If your application uses MCI commands, you can use the MCI subset provided by ActiveMovie. In the majority of cases, this will be a straightforward upgrade that maintains AVI playback and adds MPEG and QuickTime playback capabilities to your application. If your existing C-based application uses Video for Windows API, you can replace most of these with calls to the filter graph manager COM interfaces.

Writing New Applications

When writing a new application, you have some options. For example, if you only want to add MPEG playback to your application, you can incorporate the ActiveMovie ActiveX control in your application or directly access the COM interfaces on the filter graph manager. Both Microsoft Visual Basic® version 4.0 and Microsoft Visual C++® allow access to the ActiveX control or the COM interfaces. Filters within a filter graph are typically written in C++ using the ActiveMovie class library.

If your application must process the media stream in some way, you can incorporate both the filter graph manager and a custom filter into your application. The instantiated filter graph manager generates and manages the filter graph; the custom filter could be inserted into a preconfigured filter graph (created and saved using the Filter Graph Editor tool in the ActiveMovie SDK). Or the filter could be inserted at runtime into an existing filter graph.

Using an Object-Oriented Model

All components of the ActiveMovie filter graph architecture are implemented as COM objects. This includes the filters through which data is passed, and filter components that serve as a connection between filters or allocate memory. Each object implements one or more interfaces, each of which contains a predefined set of functions, called methods. An application calls a method, or other component objects, to communicate with the object exposing the interface. For example, the application calls methods on the IMediaControl interface on the object of the filter graph manager, such as the Run method, which starts a media stream. The filter graph manager, in turn, calls the Run method on the IFilter interface exposed by each of the filters.

Filter graph architecture uses COM interfaces because they have the following properties:

•	COM interfaces are publicly defined. This means thatany filter that implements the correct predefined interfaces will work in a filter graph without any knowledge about the other filters, because all filters are built with the same interface specifications.

•	COM interfaces do not change after definition. A base set of interfaces are guaranteed to work; additional interfaces may be introduced to cover additional services. This definition prevents version problems.

•	COM interfaces must have all methods implemented by any object that exposes them (even if the implemented method simply returns E_NOTIMPL). This assures that calling a method on the interface of an object will not generate an error.

•	COM interfaces are discoverable. All COM objects support a method called QueryInterface that allows an external component to discover if an interface is present and retrieve a pointer to it.

•	COM interfaces are implemented by the object that exposes the interface (they do not contain an implementation themselves). The interface is essentially a contract for the functionality. Objects like the filter graph manager, or Microsoft filters, have implemented interfaces that can be accessed. When you write a filter, you implement the interfaces.

The ActiveMovie model of calling COM interfaces to perform multimedia services is also more efficient than the Video for Windows model, which uses a driver entry point. The latter requires the overhead of a lengthy switch statement to decode a message identifier, whereas calls to COM methods are direct.

To make filter development easier, ActiveMovie provides a set of C++ classes that help you implement the interfaces required by the objects you create.

The Filter Graph Manager and Filter Graphs

To use the filter graph manager from an application, it is not necessary to know much about the underlying filter graphs. However, it is useful to understand at least the basic principals of filter graphs if you ever want to configure your own filter graph rather than letting the filter graph manager configure them for you.

A filter graph is composed of a collection of filters of different types. Most filters can be categorized into one of the following three types:

•	A source filter, which takes the data from some source, such as a file on disk, a satellite feed, an Internet server, or a VCR, and introduces it into the filter graph.

•	A transform filter, which takes the data, processes it, and then passes it along.

•	A rendering filter, which renders the data; typically this is rendered to a hardware device, but could be rendered to any location that accepts media input (such as memory or a disk file).

For example, a filter graph whose purpose is to play back an MPEG-compressed video from a file would use the following filters:

•	A source filter to read the data off the disk.

•	An MPEG filter to parse the stream and split the MPEG audio and video data streams.

•	A transform filter to decompress the video data.

•	A transform filter to decompress the audio data.

•	A video renderer filter to display the video data on the screen.

•	An audio renderer filter to send the audio to the sound card.

The following illustration shows such a filter graph:

It is possible for some filters to represent a combination of types. For example, a filter might be an audio renderer that also acts as a transform filter by passing through the video data. But typically, filters fit only one of these three types.

Filter graphs stream multimedia data through filters. In the media stream, one filter passes the media downstream to the next filter. An upstream filter describes the filter that passes data to the filter; a downstream filter describes the next filter in line for the data. This distinction is important because media flows downstream, but other information can go upstream.

To make a filter graph work, filters must be connected in the proper order, and the data stream must be started and stopped in the proper order. The filter graph manager connects filters and controls the media stream. It also has the ability to search for a configuration of filters that will render a particular media type and build that filter graph. Filter graphs can also be preconfigured, in which case the filter graph manager does not need to search for a configuration.

When searching for a rendering configuration, the filter graph manager uses the filter mapper, which first reads the registry and determines the types of filters available. The filter graph manager then attempts to link filters that accept that data type until it reaches a rendering filter. A merit value is registered with each filter and, of the filters that might be capable of handling the data, the filters with the highest merit are tried first.

Controlling the media stream means starting, pausing, or stopping the media stream. It can also mean playing for a particular duration or seeking to a particular point in the stream. The filter graph manager allows the application or ActiveX control to specify these activities and then calls the appropriate methods on the filters to invoke them. It also allows filters to post events that the application can retrieve. Therefore an application can, for example, retrieve status about some special filter it has installed.

ActiveMovie and the Internet

The ActiveMovie ActiveX control is being incorporated into Microsoft Internet Explorer so that the control can be placed on a web page and programmed using Visual Basic Script commands. The underlying implementation of filters to accomplish this demonstrates the flexibility of the ActiveMovie architecture. To the ActiveMovie ActiveX programmer, this is another ActiveX control, which can play video or audio files over the Internet while the file is downloading, rather than requiring the user to wait. (Enabling this capability will depend on hardware and connection conditions which Internet Explorer will determine.)

Because of the flexibility of ActiveMovie architecture, the same filter graphs constructed to play back media from files can play back media from the Internet by simply changing the source filter. Take, for example, the previous example of a filter graph to play MPEG movies from a disk file. The first filter in that graph is a file reader filter. By simply replacing this filter with a filter capable of reading from an Internet URL address, MPEG movies can be played from the Internet. Both file and URL reader source filters do nothing but deliver an unparsed stream of data. A parser filter is responsible for pulling the data from the reader, parsing it, and pushing it downstream. In the case of the MPEG filter graph, the parser is also the MPEG stream splitter, which divides audio and video streams.

The source filter that reads from an Internet server is called the URL moniker filter. It knows how to read, but not parse, data from a URL address. The next filter in the filter graph is a media parser. For the MPEG filter graph, this parser is built into the MPEG splitter filter. Other media types have their own separate parser filters (for example, a QuickTime parser). There is also a file source filter that does no parsing on its own but just reads data off the disk for playing back media files called the asychronous reader filter. It is the source file filter used for most ActiveMovie filter graphs.

The modularity of this architecture allows most of the same components to be reused between file and Internet playback. It also means that if you want to render a new type of data, you may only need to write a parser (and probably a renderer), and use the existing asynchronous file or URL moniker filter.

Stream Architecture

Stream architecture defines objects and interfaces that exchange streams of time-based data. In particular, it defines interfaces for the following requirements:

•	Connecting filters to other filters

•	Negotiating data types

•	Transporting data between filters

•	Synchronizing presentation of data

•	Graceful degradation of rendering in cases of insufficient resources (that is, quality-control management)

Filters and Pins

The two basic components used in the stream architecture are filters and pins. A filter is a COM object that performs a specific task, such as reading data from a disk. For each stream it handles, it exposes at least one pin. A pin is a COM object created by the filter, that represents a point of connection for a unidirectional data stream on the filter, as shown in the following illustration:

Input pins accept data into the filter, and output pins provide data to other filters. A source filter provides one output pin for each stream of data in the file. A typical transform filter, such as a compression/decompression (codec) filter, provides one input pin and one output pin, while an audio output filter typically exposes only one input pin. More complex arrangements are also possible.

At a minimum, a filter exposes the IFilter interface. This interface provides methods that allow the enumeration of the pins on the filter and return filter information. It also provides the inherited methods from IMediaFilter; these methods allow control of state processing (for example running, pausing, and stopping) and synchronization and are is called primarily by the filter graph manager:

In addition, a filter might expose several other interfaces, depending on the media types supported and tasks performed. For example, a filter can expose the ISpecifyPropertyPage interface to support a property page.

Pins are responsible for providing interfaces to connect with other pins and for transporting the data. The pin interfaces support the following:

•	The transfer of time-stamped data using shared memory or other resource.

•	Negotiation of data formats at each pin-to-pin connection.

•	Buffer management and buffer allocation negotiation designed to minimize data copying and maximize throughput.

Pin interfaces differ slightly, depending on whether they are output pins or input pins.

An output pin typically exposes the following interfaces:

•	IPin methods are called to allow the pin to be queried for pin, connection, and data type information, and to send flush notifications downstream when the filter graph stops.

•	IMediaPosition allows information about the stream's duration, start time, and stop time to be relayed from the renderer. The renderer passes the media position information upstream to the filter (typically the source filter) responsible for queuing the stream to the appropriate position.

•	IQualityControl passes quality-control messages upstream from the renderer to the filter that is responsible for increasing or decreasing the media supply.

An input pin typically exposes the following interfaces:

•	IPin allows the pin to connect to an output pin and provides information about the pin and its internal connections.

•	IMemInputPin allows the pin to propose its own transport memory allocator, to be notified of the allocator that an output pin is supplying, to receive media samples through the established allocator, and to flush the buffer. This interface can create a shared memory allocator object if the connected pin does not supply a transport memory allocator.

The standard transport interface, IMemInputPin, provides data transfer through shared memory buffers, although other transport interfaces can be used. For example, where two components are connected directly in hardware, they may connect to each other by using the IPin interface, and then seek a private interface that can manage the transfer of data directly between the two components. For more information about the model for connecting pins by using their IPin methods, see The Connection Model.

Synchronization

Reference clock synchronization is accomplished by implementing the IReferenceClock interface on any filter that has a reference clock. For example, because sound cards are predominantly used for reference clocks, the audio renderer filter implements this interface, which essentially allows any caller to register for the receipt of time notifications.

Quality-Control Management

The ActiveMovie stream architecture provides for graceful adaptation of media rendering to overloaded or underloaded media streams. The IQualityControl interface is used to send quality-control notifications from a renderer filter either upstream, eventually to be acted on by some filter in the graph, or directly to a designated quality control manager. The base classes implement the passing of quality control notifications upstream by providing the IQualityControl interface on the output pins of filters. Quality control notification uses a Quality structure, which indicates whether the renderer is overloaded or underloaded. A filter capable of, say, discarding samples to relieve and overloaded condition, can then act on this notification. This is typically done by a source filter but could be done by other filters. For example, the ActiveMovie AVI Decoder filter skips samples until the next key frame when it receives a quality control notification.

Stream Control Architecture

The stream architecture allows applications to communicate with the filter graph manager; it also allows the filter graph manager to communicate with individual filters to control the movement of the data through the filter graph. Using the stream architecture, filters can post events that the application can retrieve, so an application can, for example, retrieve status information about a special filter it has installed.

The filter graph manager exposes media control and media positioning interfaces to the application. The media control interface, IMediaControl, allows the application to issue commands to run, pause, and stop the stream. The positioning interface,IMediaPosition, lets the application specify what section of the stream to play. Additionally, the filter graph manager has interfaces that let the application queue commands, IDeferredCommand and IQueueCommand, to be played at a future time.

Individual filters expose a media control interface so that the filter graph manager can issue the run, pause, and stop control commands. The filter graph manager is responsible for calling these methods in the correct order on all of the filters in the filter graph. (The application should not do this directly.)

The position commands are handled less directly. The filter graph manager gets called by the application to, for example, play a specified length of media stream starting at some specified stream time. However, unlike the media control interface, only the renderer filter exposes a media position interface. Therefore, the filter graph manager calls only the renderer filter with positioning information. The renderer then passes this position control information upstream through media position interfaces exposed on the pins, which simply pass it on. The positioning of the media stream is actually handled by the output pin on the filter that is able to seek to a particular position (for example, a file source filter) because pins are responsible for the data transport mechanism.

Position information is passed serially upstream because there may be filters between the renderer and the source filter that require position information. Consider a transform filter that is written to perform some video or audio modification only during the first 10 seconds of a video clip (for example, increasing the volume or fading in the video). This filter probably needs to have information about where the stream is starting so that it can determine its correct behavior. For example, it should not perform if the start time is after the first 10 seconds, or it should adjust accordingly if the start time is within this duration.


ActiveMovie COM Interfaces

The ActiveMovie™ COM interfaces comprise the schematic of an architecture for streaming time-stamped media. The filter graph, through which media flows, is composed of objects, such as filters, pins, media samples, allocators, and enumerators, that work together. COM interfaces are implemented on these objects and are called by other objects with which they interact. The filter is the only filter graph COM object that has a CLSID; all other objects in the filter graph support COM interfaces and are created as needed by the filter. Filters and their supporting object must implement their COM interfaces and a class library is available for help in that task. The filter graph manager, on the other hand, has a CLSID and supports several fully implemented interfaces, as do plug-in distributors, which are aggregated by the filter graph manager. (Microsoft-provided plug-in distributors are referred to as the filter graph manager in this article.)

This article explains which object implements each interface and who is likely to call the interface methods implemented on each type of object.

Introducing the ActiveMovie COM Interfaces

The ActiveMovie COM interfaces can be categorized as follows:

•	Filter graph manager interfaces, which are fully implemented and used by applications to create, connect, and control filter graphs and by filters within the filter graph to post event notifications and to force reconnections when needed.

•	Filter and pin interfaces, which must be implemented by the filter. They comprise the methods exposed by filters for communicating with the filter graph manager, connecting with other filters, passing data downstream (from source filter to renderer filter) and passing quality control and media positioning information upstream (from renderer to source).

•	Enumerator and media sample interfaces, which are interfaces on objects created temporarily for passing information.

•	Control interfaces, which are exposed by filters and the filter graph manager to enable the starting, stopping, and positioning of media in the stream. The control interfaces on the filters must be implemented when writing a filter, whereas they are already implemented on the filter graph manager.

Filter Graph Manager Interfaces

Most filter graph manager interfaces fall in the category of control interfaces, also listed separately in this article; however, some are unique to the filter graph manager.

Interface	Who calls methods	What methods do	Comments
IFilterGraph	Not normally called directly.	Add, connect and reconnect filters in a filter graph.	Use IGraphBuilder instead, since it inherits from this interface.
IGraphBuilder	Application.	Create filter graphs dynamically from stream media type or recreates stored filter graph.	Inherits from IFilterGraph. Also uses a filter mapper object to look up filters in the registry.
IGraphVersion	Application and plug-in distributors in the filter graph manager.	Return the current filter graph version.	Determine when a filter graph has had filters added, deleted, or reconnected.
IEnumFilters	Application or possibly a filter that wants to know what other filters are in the graph.	Return filters, skip filters, or clone the enumerator.	Implemented in the filter graph manager.
IEnumRegFilters	Filter mapper.	Return filters, skip items, or clone the enumerator.	Implemented by the filter graph manager.
IMediaControl	Application.	Run, pause, and stop the filter graph, and return the state.	Has many of the same methods as the IMediaFilter interface, which is implemented on filters.
IMediaEvent	Applications that need to retrieve events passed to the filter graph manager from filters.	Get events, get event handles, block until completion, and block or unblock default handling of events by the filter graph manager.	Implemented by the filter graph manager.
IMediaEventSink	Filters that need to pass events to the application.	Receive event notifications from filters.	Implemented by the filter graph manager.
IMediaPosition	Applications.	Get duration and position properties, and get and set start time, stop time, pre-roll time, and rate properties.	Implemented on the filter graph manager and also on filters.
IMediaSelection	Applications.	Set and retrieve current position and stop position in units other than time (such as sample or field).	Implemented on the filter graph manager and also on filters.
IQueueCommand	Application wishing to send a deferred command.	Cue commands to run at stream time (offset from start) or presentation time.	Implemented by the filter graph manager and used by applications. Filters can implement this.
IDeferredCommand	The application that sent a deferred command using IQueueCommand.	Return confidence information, postpones, or cancels a deferred command, and returns HRESULT values from an invoked command.	Implemented by the filter graph manager and returned to any application that calls IQueueCommand methods.
IAMCollection	An OLE Automation client such as Microsoft® Visual Basic®.	Retrieve the number of items in the collection and retrieve an indexed item.	Implemented by the filter graph manager. Not used by C or C++ applications.
IRegFilterInfo	An OLE Automation client such as Microsoft Visual Basic.	Return a filter name and add it to the filter graph.	Implemented by the filter graph manager. Not used by C or C++ applications.
IFilterInfo	An OLE Automation client such as Microsoft Visual Basic.	Return name, vendor information, IFilter interface, filename (for source filters), specified pin object, or collection of associated pin objects.	Implemented by the filter graph manager. Not used by C or C++ applications.
IPinInfo	An OLE Automation client such as Microsoft Visual Basic.	Return pin information such as name, direction, connections, and collection of associated media type objects. Also methods to connect and disconnect pins.	Implemented by the filter graph manager. Not used by C or C++ applications.
IMediaTypeInfo	An OLE Automation client such as Microsoft Visual Basic.	Return the major and minor media types.	Implemented by the filter graph manager. Not used by C or C++ applications.
Filter and Pin Interfaces

Filters are composed of one filter object and one or more pin objects. Although only the IUnknown and IFilter interfaces are strictly required on a filter, filters can support other filter and pin interfaces, as discussed below.

Filter Interfaces

The following interfaces are exposed by filter objects in order to be integrated with the filter graph manager. The filter is the main COM object and has a class ID (CLSID) and name registered in the registry. Filters must provide access to their pins and otherwise communicate with the filter graph. They must also allow the filter graph manager to manage the data flow by accepting state change messages.

Interface	Who calls methods	What methods do	Comments
IUnknown	Filter graph manager.	Return a pointer to the interface, add and delete references to the interface.	Implemented by the CUnknown base class.
IPersist	Filter graph manager.	Return the class identifier (CLSID) of the filter for saving the filter as part of a stored filter graph.	Implemented by the CBaseFilter base class.
IMediaFilter	Nothing directly.	Put the filter in run, stop, or pause state, gets and sets the reference clock and retrieves the filter state.	Inherited by the IFilter interface, which should be used instead of referencing this directly.
IFilter	Filter graph manager.	Same as IMediaFilter plus enumerates pins, retrieves filter and vendor information, and locates pins when rebuilding a persistent filter graph.	Inherits methods from the IMediaFilter interface. Implemented by the CBaseFilter class.
IPersist	Filter graph manager when loading preconfigured filter graph files.	Has one method that is used to retrieve the class identifier of the filter.	Inherited by IFilter along with IMediaFilter.
IAMovieSetup	Entry-point routines in dllentry.cpp.	Two methods which register and unregister the object.	This is implemented by the base classes for most of what is required to make a filter self-registerable. Need to override one base member function to provide setup structures.
The following additional filter interfaces may be exposed by filters such as source filters, and by video and audio renderers. Source filters are notified via a quality control mechanism so that they can adjust the amount of data introduced to the stream according to the performance of the renderer. Audio renderers are usually called upon to provide a reference clock, since audio hardware generates this. The video renderer filter supplied by Microsoft exposes interfaces to handle both the video window and the transferring of video frames into video buffers.

Interface	Who calls methods	What methods do	Comments
IAsyncReader	Downstream parser filter.	Perform synchronized reads, request data, request allocator, begin and end flushing and retrieve total length of the file.	Implemented on the Asynchronous Reader Filter, which reads media types with a major type of MEDIATYPE_Stream.
IFileSourceFilter	Any application that needs to set the name of the file into which the file sink filter will write.	Set or retrieve the filename.	Implemented on any source filter that needs a file name from the user.
IFileSinkFilter	Any application that needs to set the name of the file from which the file source filter will read.	Set or retrieve the filename.	Implemented on a file writer filter, as used in a video capture filter graph.
IQualityControl	Filter graph manager, upstream filter, or pin.	Receive a quality message and receive the quality sink location.	Normally implemented on filters that can affect the quality when they receive the message.
IReferenceClock	Filters that need to be synchronous with a reference clock.	Register for time notifications from the filter, convert real to reference time, and return the current time.	Implemented on a filter that can generate a reference clock, typically an audio renderer. Provides services similar to the timeBeginPeriod and timeSetEvent Win32® functions.
IBasicAudio	Applications and OLE Automation clients such as Visual Basic.	Get and set the properties of the audio renderer filter.	Can be implemented on an audio renderer filter.  Supports OLE Automation.
IBasicVideo	Applications and OLE Automation clients such as Visual Basic.	Get and set the source video rectangle, and retrieve video size and palette values as well as the current image.	Normally implemented on a video renderer filter.  Supports OLE Automation.
IVideoWindow	Applications and OLE Automation clients such as Visual Basic.	Control the window aspects of a video renderer.	Normally implemented on a video renderer filter.
IDirectDrawVideo	C or C++ applications.	Set and retrieve DirectDraw™ hardware and emulated capabilities and surface types.	Normally implemented on a video renderer filter.
IFullScreenVideo	C or C++ applications.	Set and retrieve fullscreen modes, message drain, icon caption and other information.	Normally implemented on a video renderer filter.
IOverlay	Filters upstream from the renderer that want to be notified of window changes.	Set and retrieve palette and color key information; get window handle, clip list, window position; setup advise link with upstream filter.	Normally implemented on a video renderer filter.
IQualProp	Property page objects.	Retrieve rendering quality properties of the video renderer such as the number of frames drawn, jitter, and so on.	Supports OLE Automation.
Pin Interfaces

These interfaces are exposed by pin objects. Pins do not normally have registered class identifiers and are usually created by the filter object on which they reside. They are exposed externally by the filter, which includes a method (IFilter::EnumPins) to hand out pointers to the IPin interfaces of its pins, normally to the filter graph manager. The filter graph manager is responsible for connecting pins by calling an IPin method on one of the pins with a pointer to the other pin. Once pins are connected, each pin holds a pointer to the pin to which it is connected.

Interface	Who calls methods	What methods do	Comments
IUnknown	Filter graph manager, other pins, the owning filter.	Return a pointer to the interface, add and delete references to the interface.	Implemented on all pins by the CUnknown base class.
IPin	Filter graph manager, other pins, the owning filter.	Connect and disconnect the pin, return information on external and internal pin connections, return preferred media types enumerator, negotiate preferred media types, receive flush and end-of-stream notifications.	Implemented on all pins by the CBasePin base class.
IMemInputPin	Filter graph manager, output pin of a connected filter.	Return a preferred allocator, receive the allocator provided by output pin, receive media samples, and tell whether the pin will block on receive.	Normally only on input pins. Implemented by the CBaseInputPin base class.
IMemAllocator	Owning filter and output pin of connected filter.	Allocate one or more buffers based on required size, retrieve a buffer for a media sample, commit memory when in use, and release it (decommit) when not in use.	Appears on allocator object normally created by IMemInputPin. Implemented by CMemAllocator class.
IQualityControl	Downstream filter or pin on downstream filter.	Receive a quality message and receive the quality sink to send quality messages to.	Implemented on output pins by the CBaseOutputPin base class, where it is used to pass the message upstream.
IMediaPosition	Filter graph manager or downstream filter.	Get duration and position properties, and get and set start time, stop time, pre-roll time, and rate properties.	Downstream filters call methods on output pins supporting this to pass a requested media position upstream. Implemented in CPosPassThru on pins.
IMediaSelection	Applications.	Set and retrieve current position and stop position in units other than time (such as sample or field).	Downstream filters call methods on output pins supporting this to pass a requested media position upstream. Implemented in CPosPassThru on pins.
In addition, the Microsoft video renderer's input pin supports the IOverlay interface, which allows the connected upstream pin to effectively register its IOverlayNotify interface in order to receive notifications of video window changes. Replacement video renderers may also implement this if they are intended to connect to the same filters as the video renderer provided with ActiveMovie.

Media Sample and Enumerator Interfaces

Media sample and enumerator interfaces are temporary objects created to pass information or data between objects. They do not have class identifiers.

Media Sample Interface

The media sample interface is created from the memory allocator, which uses the media sample object as its unit of exchange. It has no class identifier. It is the unit of media data that is passed from one filter to the next via the memory allocator shared by two connected pins.

Interface	Who calls methods	What methods do	Comments
IUnknown	Pin or filter.	Return pointer to the interface, add and delete references to the interface.	Implemented on media samples by the CUnknown base class.
IMediaSample	Pins or filters that need to manipulate the media sample data or examine its properties.	Return a pointer to data, and get and set properties on the media sample such as buffer size, time stamp, data length, type, synchronization point, pre-roll, and end-of-stream properties.	Implemented on media samples by the CMediaSample base class.
Enumerator Interfaces

Enumerators in ActiveMovie are based on the OLE EnumXXX interfaces. They include the Next and Prev methods, which tell the enumerator what item or items to return; the Skip method, which skips one or more items; and the Clone method, which makes a copy of the enumerator. Enumerators are used to present lists of items such as filters in a filter graph, pins on a filter, or media types that are preferred by a pin.

Interface	Who calls methods	What methods do	Comments
IEnumPins	Filter graph manager.	Return pins, skip pins, or clone the enumerator.	Implemented by the CEnumPins class.
IEnumMediaTypes	Filter graph manager or connected pin negotiating a media type.	Return media types, skip media types, or clone the enumerator.	Implemented by the CEnumMediaTypes class.
IEnumFilters	Application or possibly a filter that wants to know what other filters are in the graph.	Return filters, skip filters, or clone the enumerator.	Implemented in the filter graph manager.
IEnumRegFilters	Filter mapper.	Return filters, skip items, or clone the enumerator.	Implemented by the filter graph manager.
Control Interfaces

Control interfaces allow the filter graph manager to coordinate the activities of the data stream with filters. Interfaces described previously in both Filter Graph Manager Interfaces and Filter and Pin Interfaces sections are repeated here so that all control interfaces can be viewed together.

Interface	Who calls methods	What methods do	Comments
IMediaControl	Application.	Run, pause, and stop the filter graph, and return the state.	Implemented by the filter graph manager.
IMediaPosition	Application, when exposed on the filter graph manager; filter graph manager or downstream filter, when exposed on a filter.	Get duration and position properties, and get and set start time, stop time, pre-roll time, and rate properties.	Implemented on the filter graph manager and also on filters.
IMediaSelection	Applications.	Set and retrieve current position and stop position in units other than time (such as sample or field).	Implemented on the filter graph manager and also on filters.
IMediaFilter	Nothing directly.	Put the filter in run, stop, or pause state, gets and sets the reference clock and retrieves the filter state.	Inherited by IFilter, which should be used instead of referencing this directly.
IFilter	Filter graph manager.	Same as IMediaFilter plus enumerates pins, retrieves filter and vendor information and locates pins when rebuilding a persistent filter graph.	Inherits methods from the IMediaFilter interface. Implemented by the CBaseFilter class.
Because ActiveMovie objects are COM-based objects, it is a natural extension to use other COM interfaces published in the OLE specifications to perform functions such as listing property pages or accessing files. Following are some of the OLE interfaces that are commonly used in ActiveMovie filter:

•	IPersistFile

•	ISpecifyPropertyPages

The Interfaces on a Typical Filter Graph

Perhaps the best way to put the ActiveMovie interfaces into perspective is to look at the interfaces exposed in a simple filter graph. The example chosen here is a filter graph that plays back audio data stored on a disk. It is composed of a source filter and an audio renderer filter (no transforms are done, so this is a very simple graph).

The basic source filter consists of an IFilter interface, and one output pin that can be found via the EnumPins method on the IFilter interface. The OLE IPersist interface might also be present on the filter (not shown here) in order to enable the filter to be stored as part of a persistent filter graph.

The output pin supports IPin and IMediaPosition, since the source filter is a seekable filter (that is, it can be told to move to a particular position in the media stream). The following illustration shows the interfaces on the source filter and its output pin.

Note that qualtiy management is not implemented in this example, but could be by including the IQualityControl interface on the output pin as well.

The basic renderer filter consists of a COM driver supporting the IFilter (and, again, IMediaFilter by inheritance) and IMediaPosition interfaces, as well as having one input pin through the EnumPins method of the IFilter interface. The OLE IPersistFile interface might also be present on the filter (not shown here) in order load the file. The renderer may support additional interfaces, such as IReferenceClock (as a master for synchronization) or IBasicAudio, for an audio renderer as shown here.

The input pin supports the IPin and IMemInputPin interfaces. Methods of the IMediaPosition interface on the renderer filter may call the IMediaPosition interface methods of the output pin that is connected to the renderer's input pin.

A basic representation of the connection of a source filter to a renderer filter is shown below.

Once the pins are enumerated and connected, it is the implementation of the output and input pins that defines the interactions of the two pins.

Once the filters are connected, the control available to the user (filter graph manager) is indicated through the bold interfaces. This continues with the example of connecting an audio source to an audio renderer.

The following interfaces are those that would likely be used during a transport:

•	IMediaPosition supports the ability to seek to a position and change the rate.

•	IBasicAudio supports the ability to set the volume.

•	IFilter supports such methods as Run and Pause (methods on the filter graph manager's IMediaControl interface).

Special (custom) interfaces that the filters would support must be obtained directly from the filters. Usage of these interfaces implies that the user is aware of their identifiers.


ActiveMovie C++ Class Library

This article provides a general description the Microsoft® ActiveMovie™ class library, the relationship of the base classes with the ActiveMovie Component Object Model (COM) interfaces that they implement, and 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 ActiveMovie 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.

Base Classes

Most of the base classes in the ActiveMovie class library implement ActiveMovie COM interfaces. These classes produce C++ objects that provide an IUnknown interface so that the interfaces they support can be accessed by external components.

CBaseObject and CUnknown Classes

The CBaseObject class is at the root of all base classes. It exists primarily to provide debugging assistance by keeping a count of all active ActiveMovie objects. All base class constructors in derived base classes provide a debugging object name as the first parameter and call the CBaseObject constructor. The debugging object name sent to this base class can then be viewed on a debugging monitor.

All ActiveMovie classes that implement interfaces derive from a base class called CUnknown, which is derived from CBaseObject. CUnknown implements the INonDelegatingUnknown interface, which is essentially the same as the IUnknown interface because it provides methods to request an interface, and to add or release references to that interface.

There are two two IUnknown because of aggregation, the combining of more than one object into a single larger object. Although objects in the filter graph, such as filters and pins. are rarely aggregated, the design is available extensibility. 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 object, 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. Rather, it is reserved for communicating through the outer object. An object, such as the pin from another filter, typically communicates privately with other objects in the filter graph, such as another pin. If the other object is part of an aggregation, it must provide a private access.

The INonDelegatingUnknown interface provides direct, private access to interfaces, regardless of whether the object is aggregated. Direct access is important in most of the communication between the ActiveMovie objects such as pins, allocators, and filters, and is therefore the default method of communication. The IUnknown interface is therefore reserved for aggregation. In fact, the base classes implement the IUnknown interface on nonaggregated objects (which includes almost every object in current filter graphs) to call the nondelegating interface directly.

Base Classes that Implement Interfaces

The majority of classes in the ActiveMovie class library implement COM interfaces and can be categorized as follows:

•	Filter base classes implement the IFilter 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.

•	Memory classes include CMediaSample, CBaseAllocator, CMemAllocator, and their derived classes.

•	Control and position classes include CBaseFilter, CMediaPosition, CMediaControl, and CBaseMediaFilter.

Filter Base Classes

The ActiveMovie 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.

CBaseFilter is the base class for all filter classes. It implements the IFilter interface, which specifies methods to allow the filter graph manager to create pins, enumerate the 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 IFilter 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 provide 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 inplace 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 and 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 in the ActiveMovie runtime.

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 ActiveMovie 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, its base classes CBaseVideoWindow, and CBaseWindow

•	CAggDirectDraw

•	CAggDrawSurface

The following illustration shows all of the classes that support renderers that are not derived from either CBaseFilter or CBasePin:

Pin Base Classes

Pins have a greater responsibility 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:

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. These are tasks that pins must perform. 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.

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 CThread class as shown in the following illustration:

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 performs the same routines as if it were handed a sample on an IMemInputPin::Receive method from a pushing source filter.

Enumerator Base Classes

An enumerator is an interface that provides methods for traversing a list of elements. They are used in OLE programming, and the ActiveMovie model follows the OLE model. Two enumerator classes are provided in the class library: CEnumPins, which implements the IEnumPins interfaces, and CEnumMediaTypes, which implements the IEnumMediaTypes interface. Two other ActiveMovie enumerator interfaces, IEnumFilters and IEnumRegFilters, are not represented by base classes because they are only implemented by the filter graph manager.

The CEnumPins class creates an enumerator when the IFilter::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 OLE 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 Classes

Transport classes share memory between pins and pass media samples using that memory. ActiveMovie provides four classes to help implement shared memory transports:

•	CBaseAllocator

•	CMemAllocator

•	CMediaSample

•	CImageSample

CBaseAllocator is a class that provides member functions to implement the IMemAllocator interface, as shown in the following illustration:

The IMemAllocator interface 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 most frequently calls the IMemAllocator methods. CBaseAllocator provides the member functions Alloc and Free that are called from the Commit and Decommit methods. Derived classes override functions Alloc and Free to provide their own allocation and freeing of memory.

Because CBaseAllocator performs very little implementation by itself, most pins use the CMemAllocator class, which is derived from CBaseAllocator. CMemAllocator overrides Free 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 of the CMediaSample interfaces 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:

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 three other classes: CPosPassThru, CMultiPinPosPassThru, 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 IMediaSelection interface on output pins of filters and does nothing but call the corresponding interface on the output pin of the next upstream filter, thereby passing through the positioning data. IMediaSelection 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 times on individual samples, so that samples can be queried at any time for this information. This is helpful when dealing with seeking using IMediaSelection, because this type of seeking does seek-to-time values and so does not keep track of the samples 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 IMediaSelection interface directly?

The CMultiPinPosPassThru class implements a special case of IMediaPosition passthrough. The video mixer takes many input pins and produces one output pin, so the CMultiPinPosPassThru class passes the IMediaPosition information from the output pin of the mixer to the output pins connected to each of its input pins.

Finally, CSourcePosition is the class that helps the source filter implement its IMediaPosition interface.

Utility Classes

The ActiveMovie 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 are briefly described in this section.

Win32 Classes

Several classes have been implemented to handle Win32 threads, events, and critical sections. These include the following classes:

CAMEvent 	Handles a Win32 event as a C++ object. Methods allow events to be put into the signaled state or reset to a non-signaled 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.

CTimeoutEvent 	This class derives from CAMEvent and adds the ability to specify a timeout period when waiting for an event to become signaled.

CCritSec 	Handles a Win32 critical section as a C++ object to provide intra-process 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.

CThread 	An abstract worker thread class providing 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.

Lists and Queue Classes

The following classes are available for handling lists and queues:

CBaseList 	Represents a linked list data structure of typeless pointers to objects derived from CBaseObject.

CGenericList 	Template class derived from CBaseList that calls CBaseList member functions and adds type checking for the type specified in the template.

CNode 	A subclass of CBaseList representing a single node in the list.

CNodeCache 	A subclass of CBaseList representing a cache of nodes. This class facilitates rapid access to adding or removing CNode class nodes to or from a CBaseList list.

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 on without blocking, while the COutputQueue class handles the passing of the media samples downstream.

Multimedia Data Type Classes

The following multimedia data type classes are provided in the ActiveMovie SDK:

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.

COARefTime 	Converts the CRefTime values between LONGLONG, used by filters, and double, used by OLE Automation interfaces.

FOURCCMap 	Provides conversion between the older-style FOURCC media tags used to identify and register media types and the GUID media subtypes used by ActiveMovie.


ActiveMovie and COM

Microsoft® ActiveMovie™ provides a framework that simplifies the creation of Component Object Model (COM) objects. Familiarity with C++ is assumed. An appreciation of COM would be helpful, but not essential. For more information about writing a filter, see Creating a Transform Filter.

ActiveMovie filters, the filter graph manager, plug-in distributors, and enumerators are all COM objects. A general design has been adopted for the way in which ActiveMovie implements COM objects. This design is available to help you implement your own filters and plug-in distributors (or any COM object).

ActiveMovie components are supplied as inprocess servers (that is, servers that run in the same address space as your application). They are packaged in a single dynamic-link library (DLL), quartz.dll. Use the COM framework of ActiveMovie to build your own inprocess COM servers which you can package in your own DLL(s).

Typically, a single C++ class implements a single COM class. The ActiveMovie COM framework requires that C++ classes that implement COM objects conform to a few simple rules, and that the developer provides a class factory template for each such class. The class factory template contains information about the class that is vital to the framework. Class factory templates are defined in the DLL using two global variables (g_Templates and g_cTemplates) as shown in the following example.

CFactoryTemplate g_Templates[]=

{   {L"My class name", &CLSID_MyClass,   CMyClass::CreateInstance,  CMyClass::Init},

{L"My class name2", &CLSID_MyClass2,   CMyClass2::CreateInstance}

};

int g_cTemplates = sizeof(g_Templates)/sizeof(g_Templates[0]);

The names and types of these variables must be as they appear in the previous example. Because any DLL may contain several COM classes, each of which will require a class factory template, the factory templates are defined in an array and the number of elements in the array is recorded in another variable. Each element of the array contains the following fields:

•	A textual description of the class (using wide characters, therefore the "L" prefix).

•	A pointer to the class identifier of the class (CLSID).

•	A pointer to a static method of the class that can create instances of the class.

•	A pointer to a static method of the class. This method is called when the DLL is loading or unloading and can perform one-time initialization and termination. If this method is not required, this final termination may be omitted, will default to null, and will be ignored.

The framework uses the information in these class factory templates to create instances of the specific class, and to register and unregister the COM classes.

The following example demonstrates a simple C++ class implementing a COM class using the ActiveMovie framework.

class CMyClass : public IMyInterface, public CUnknown

{

private:

/* private attributes */

protected:

~CMyClass()

{ /* release private attributes */ }

CMyClass(TCHAR *pName, LPUNKNOWN pUnk, HRESULT *phr)

: CUnknown( pName, pUnk, phr )

{ /* set up private attributes */ }

public:

DECLARE_IUNKNOWN

static CUnknown *CreateInstance(LPUNKNOWN pUnk, HRESULT *phr)

{

CUnknown * result = 0;

result = new CMyClass( NAME("CMyClass"), pUnk, phr );

if ( !result ) *phr = E_OUTOFMEMORY;

return result;

}

STDMETHODIMP NonDelegatingQueryInterface(REFIID iid, void ** ppv)

{

if ( iid == IID_IMyInterface )

{

return GetInterface(static_cast<IMyInterface *>(this), ppv );

}

   else

{

return CUnknown::NonDelegatingQueryInterface(iid, ppv);

}

}

/* My interface methods */

};

This is not a typical filter example because filters will normally derive from more specialized base classes than CUnknown. However, because all base filter classes eventually derive from CUnknown, this example demonstrates what is essential in a more generic manner. The more specialized filter base classes that derive from CUnknown are responsible for implementing NonDelegatingQueryInterface for the required interfaces, so this is not typically necessary in the derived filter class, unless it adds some interfaces that are not in the base classes.

The example is probably more typical for an ActiveMovie plug-in distributor (PID), which extends the functionality of the filter graph manager, or for a framework for implementing an arbitrary COM object.

INonDelegatingUnknown::NonDelegatingQueryInterface is a method that allows other objects to gain access to interfaces on the COM object. All COM objects support IUnknown::QueryInterface to do this and the ActiveMovie class library supplies the DECLARE_IUNKNOWN macro to enable the IUnknown interface. The ActiveMovie framework goes one step further and makes it easy to aggregate objects (make them part of a larger COM object) by implementing an INonDelegatingUnknown interface. Even if your object is not aggregated, it uses the INonDelegatingUnknown interface, which is mapped to the IUnknown interface by the base classes.

Although aggregation is handled for all objects by the ActiveMovie class framework, it is typically not used by filters in current ActiveMovie filter graphs. Plug-in distributers do, however, require aggregation (as is described at the end of this article), and future filter graphs may incorporate filter objects that are composed of collections of aggregated filters.

With this in mind, it may be helpful to explore more of the details of the previous example. First, a brief review of some COM basics may help to set the stage. COM objects are created by their class factories, are reference counted during their lifetimes, and self-destruct when their reference count drops to zero. COM objects may be created in isolation, or may be aggregated with an already existing COM object. In this second case, the existing object (referred to as the outer object) maintains the reference count. The created object (referred to as the inner object) is not reference counted, but will be destroyed by the outer object during the destruction of the outer object. (The application cannot directly manipulate COM objects; an application can only invoke the methods that the object chooses to expose through its interfaces. Typically, COM objects make several interfaces available. All COM objects must support the IUnknown interface.

All classes using the ActiveMovie framework must inherit from CUnknown either directly (as in the previous example) or indirectly, through one of the other supplied base classes. CUnknown, with the DECLARE_IUNKNOWN macro and the NonDelegatingQueryInterface method, provide the IUnknown interface with the required reference counting and support for COM aggregation.

NonDelegatingQueryInterface is a method on INonDelegatingUnknown, which is supported by CUnknown. NonDelegatingQueryInterface is overridden in derived classes that wish to support new interfaces, such as IMyInterface in the example. The method should check for all the interfaces known to be implemented on the object and return appropriate pointers to these interfaces. Requests for unrecognized interfaces should be passed to the NonDelegatingQueryInterface of CUnknown. The call to the GetInterface method (of CUnknown) copies the interface into the ppv parameter and ensures that the correct reference count is incremented.

The methods in INonDelegatingUnknown mirror those in IUnknown. For more information about CUnknown, the INonDelegatingUnknown interface, and the NonDelegatingQueryInterface method, see the CUnknown section in the reference material. INonDelegatingUnknown is defined in combase.h; CUnknown is implemented in combase.cpp.

When an instance of the class is required, the framework, using the information in the class factory template, calls the CreateInstance method of the class. The framework passes a pointer to an outer unknown (if the object is to be part of an aggregate object), and the phr parameter, a pointer to an HRESULT value. The constructor or the constructor of an inherited class can set this value if an error occurs. The phr parameter should not be initialized; this is the responsibility of the calling application. CreateInstance constructs an instance of the class. The name passed to the constructor is wrapped with the NAME macro supplied by ActiveMovie. When building debugging versions, NAME passes the textual name on to the constructor. When building nondebugging versions, NAME results in a null pointer, thus saving space in versions that are not for debugging purposes.

The class constructor and destructor are declared protected. This prohibits the creation of the object using C++ language constructs. Instances of this class can only be created by calling the CreateInstance method.

The class constructor needs to construct the inherited CUnknown. The pName parameter points to a string that is available for debugging purposes. It is vital that the string referenced by pName is in static storage, because the constructor for CUnknown will not copy it.

Reviewing the Instantiation Process

It may be helpful at this point to consider the normal process of instantiating a COM object and examine how the ActiveMovie COM framework supports this process.

1	Inprocess server DLLs must export certain standard functions so that COM can interact with them. The ActiveMovie framework provides these functions for you. The module definition file for the DLL must list these functions in its EXPORTS section, and link to strmbase.lib. The functions are: DllGetClassObject, and DllCanUnloadNow. (The source code for these functions is supplied in DllEntry.cpp.)

2	DLL entry points which facilitate the automatic registration of COM classes may be defined. These entry points are DllRegisterServer and DllUnregisterServer. Although the framework does not directly provide these entry points, it does provide a pair of functions, called AMovieDllRegisterServer and AMovieDllUnregisterServer (defined in dllentry.cpp), that can implement these entry point functions. These functions take care of registering and unregistering all COM objects for which you have provided class factory templates in the g_Template array. You can add a DllRegisterServer function to your module that simply calls AMovieDllRegisterServer, or you could do the same for DllUnregisterServer.

3	Registry entries are required to link the class identifier (CLSID) of the COM object to the DLL in which the class is implemented. The framework provides entry points in the DLL that support the automatic registration of class identifiers in the registry, using the information provided in the class factory templates.

4	When the DLL is loaded, the DllMain entry point is called to perform any initialization. The framework provides this function. During its execution, any initialization routines referenced in the class factory templates will be called.

5	When an application calls CoCreateInstance or CoGetClassObject, COM calls the DllGetClassObject function in the appropriate DLL to obtain a pointer to a class factory that can instantiate objects of the CLSID requested by the application. The framework supplies this function. Using the information in the class factory template, the framework creates a class factory. (If the requested CLSID cannot be found in the array of class factory templates, an error is returned to the application.)

6	The class factory is called to instantiate an object that supports the interface identifier (IID) requested by the application. At this point, the class factory will call the static method referenced in the class factory template.

7	By deriving the class from CUnknown, overriding NonDelegatingQueryInterface, and using the DEFINE_IUNKNOWN macro to declare the IUnknown interface, both COM aggregation and reference counting are addressed.

8	During the life of the DLL, DllCanUnloadNow may be called to see if it is safe to unload the DLL. Typically, this returns S_FALSE if any class factory is locked, or if any of the objects that have been created still exist. The framework implements DllCanUnloadNow.

Creating Filters

When creating filters, you can take advantage of one of the richer classes that ActiveMovie provides, such as CTransformFilter or CBaseRenderer, instead of deriving from CUnknown. These supplied classes are derived from CUnknown, but provide additional functionality specific to various types of filters. However, building filters also requires an understanding of the ActiveMovie Connection Model and the pin classes. For more information about creating filters, see Creating a Transform Filter.

Creating Plug-In Distributors

The filter graph manager can perform operations at a high level, treating the filter graph as a single entity. These operations may be distributed across an entire filter graph, or perhaps to just a single filter in the filter graph. The filter graph manager, of itself, only exposes a few interfaces. A feature called a plug-in distributor allows the filter graph manager to be extended with additional interfaces. When the filter graph manager receives a request for an interface which it does not support, it tries to find a plug-in distributer (PID) that does support it. If it succeeds in finding such a PID, then that PID is instantiated as an aggregate object within the filter graph manager. By doing so, the filter graph manager appears to support many more interfaces.

Plug-in distributors are aggregated with the filter graph manager, but all of the aggregation logic is provided by CUnknown, allowing you to concentrate on the PID logic.

A PID is designed to be aggregated into a filter graph manager; it will call on the services of its owning filter graph manager. Because the PID is unlikely to function correctly without an owning filter graph, it checks for an outer unknown in the constructor of the PID. To make this determination, add the following line to the body of the constructor illustrated in the previous example:

if (!pUnk) *phr = VFW_E_NEED_OWNER;

To be even more defensive, the PID could also request an IFilterGraph or IGraphBuilder interface from the outer unknown during construction, because these interfaces are known to be only on the filter graph manager.

Recall that if the PID obtains any interface pointers from the filter graph manager, the pointers should be released immediately. Because the PID is an aggregate object, its lifetime is within the lifetime of its containing object, the filter graph manager, so there is no need to maintain a lock on it. Furthermore, maintaining a lock introduces a circular reference count that would not allow the destruction of the filter graph manager.

The Class Factory

The concept of a class factory is not specific to ActiveMovie; it is a common design that appears when the underlying type of the object being created is not known to the client that requests its creation. With COM objects, clients request interface pointers but know little about the underlying objects that implement that interface.

In C++, there are two means of implementing a class factory. One is to implement it as a genuine class, the other is to implement it as a static method on the class that the class factory will manage. The first method provides better separation of responsibilities and data hiding, and is the approach adopted by COM. The second method allows for a simpler implementation.

The ActiveMovie COM framework provides the best of both worlds. It exposes a genuine COM factory class to its clients while allowing the developer to implement the body of the class factory as a static method of your class. The bridge between these two approaches are the two global variables, g_Templates and g_cTemplates.

The ActiveMovie framework defines classes called CFactoryTemplate and CClassFactory. A CFactoryTemplate object holds information regarding a specific class, including a pointer to the static factory method of the class. When CClassFactory is instantiated, it must be given reference to a CFactoryTemplate instance. The CClassFactory instance will then act as a class factory for the class described in its associated CFactoryTemplate instance. The following illustration demonstrates the relationship between these classes, their instances, and the objects they create.

The ActiveMovie SDK includes a module, and DllEntry.cpp, which provides the function DllGetClassObject. This function uses the illustrated process to create a class factory that can produce instances of a class.


Control Interfaces and Plug-in Distributors

The filter graph manager exports control interfaces; it also distributes the actions of interface methods to the appropriate filters. For example, the IMediaControl::Run method on the filter graph manager is called by an application to run the filter graph; this is distributed to the IMediaFilter::Run method of each filter method by the filter graph manager. This distribution allows applications to have a single point of control to perform the basic operations.

Plug-in Distributors and Extensibility

To allow the filter graph manager to be extensible, a mechanism known as a plug-in distributor (PID) is used. This is a Component Object Model (COM) object that exposes a particular control interface and implements it by calling the enumerator of the filter graph manager, finding which filters expose the control interface and talking directly to those filters. PIDs are supplied for the standard control interfaces; these can be replaced by Independent Software Vendors (ISV) and other interface distributors can also be added.

When the filter graph manager is asked for an interface that it does not recognize, it searches the registry for a PID. This is an unnamed value under the following key:

HKEY_CLASSES_ROOT\Interface\<IID>\Distributor

This value provides the class identifier (CLSID) of an object that can distribute the interface identifier (IID). The filter graph manager then instantiates that object as an aggregated object, specifying the IUnknown implementation of the filter graph manager as the outer IUnknown, and asking for the IID. The object will then be able to use its outer IUnknown pointer to obtain an IFilterGraph interface. With this interface, it can enumerate the filters in order to implement its control interface methods and properties; it will also be able to use the IMediaControl implementation of the filter graph manager for correctly ordered and synchronized state changes (run, pause, stop, and so on).

Control Distributors

The standard control distributors that are supplied will directly implement their distribution. These distributors make the following assumptions:

•	Applications that connect filters directly without informing the filter graph manager will get unexpected results if they also use the distributors of the filter graph manager. For example, a deadlock might occur if an calls the IMediaFilter::Run method of a filter directly, because the filter graph manager contains a distributor that implements IMediaControl::Run and passes calls on to the IMediaFilter::Run method of each filter.

•	Filters do not change the interfaces they support during the existence of a graph. If the enumerator of the filter graph manager is synchronized, the set of filters that support a specified control interface has not changed.

•	Properties that can be aggregated directly can be read and written to through the control interface even when exposed by multiple filters. For example, duration can be reported as the longest of all individual durations, with all streams treated as running in parallel.

•	Where a property is exposed by several different filters, applications will either use the filter graph manager to set and get the property or will communicate with the individual filters, but will not mix the two methods. An application that communicates with two audio renderers to reset the volume and then queries the IBasicAudio implementation of the filter graph manager for the volume, will get undefined results. (In practice, it will probably retrieve the volume property of the first audio renderer with no attempt to combine this with the other stream.) If the application sets the property through the interface of the filter graph manager, the same value will be set to all the individual filters that expose it.

•	The filter graph manager will expose the IMediaControl interface (through a replaceable distributor) as the main application method for starting and stopping graphs. This is a slightly higher-level, simplified interface than IMediaFilter and is suitable for OLE Automation (OA) clients and simple applications. It will be implemented by calls to the IMediaFilter interface implemented by the filter graph manager and by individual filters. Individual filters will expose IMediaControl; the same applies to the event notification scheme implemented by IMediaEvent. Other control interfaces may be exposed by both the filter graph manager and some individual filters.

PIDs are required to keep track of the filters in the filter graph. This is done by implementing the IDistributorNotify interface on the distributor. IDistributorNotify has the same Run, Pause, and Stop methods as IMediaFilter, all of which are called before the calling the filter. It also has a IDistributorNotify::NotifyGraphChange method, which notifies the distributor when any filters are added or removed from the filter graph, or connections change.


The Flow of Data in a Filter Graph

This article examines the types of data that move in a filter graph, where the data originates and how it is routed, and the protocols that must be followed for data to flow correctly. Data flow in the filter graph occurs in the following ways:

•	Media sample data flows from one filter to the next—originating at a source filter and terminating, eventually, at a renderer filter.

•	Control information, such as end-of-stream and flushing notifications, travels with the media data stream from filter to filter.

•	Notification events flow from the filters to the filter graph manager and, optionally, to the application.

•	Filter graph control data flows from the application to the filter graph manager and finally to the filters themselves.

•	Quality control data originates in the renderer and flows upstream through the filters until it finds a filter capable of cutting back or increasing the media data flow. It may also flow directly to a quality control manager if one is registered.

Media Sample Data

ActiveMovie™ filters pass media data downstream, that is, from the output pin of one filter to the input pin of the next filter. The flow and control of the data is effected by the interfaces on those pins and the filters themselves. Data streaming activity is serialized by the filters; all data streaming calls for a given pin are explicitly serialized and usually originate from a single thread.

Data is passed from the output pin of one filter to the input pin of the next. The two connected pins agree upon a common method of exchanging data, called a transport. The most common transport is the local memory transport. This transport is implemented if the input pin supports the IMemInputPin interface. The ActiveMovie class library base classes assume this transport.

Filters must follow protocols in order to pass and receive media samples. The connected pins must agree upon the allocator to be used, must have a means of passing the data, and must follow the correct procedure for holding onto a sample or releasing it back to the sender. Media samples are data objects that support the IMediaSample interface. They are obtained from an allocator, most likely represented by an object supporting the IMemAllocator interface.

For the local memory transport, an output pin passes a media sample to the input pin it is connected to by calling the input pin's IMemInputPin::Receive or IMemInputPin::ReceiveMultiple methods, depending on whether it is passing single or multiple samples. Before it can pass this data, however, the output pin must obtain a media sample. The IMemInputPin interface on the input pin provides an IMemAllocator object when requested to provide an allocator. If the output pin is not using its own allocator, or one provided to it from further upstream, it can call the IMemAllocator::GetBuffer method on the input pin to retrieve one.

The input pin can either process the data right away or it can save it for later processing. In the latter case it must call the IUnknown::AddRef method on the media sample to prevent the sample from being returned to the allocator. When the output pin has called the input pin's IMemInputPin::Receive method, it must call the IUnknown::Release method to free the sample. If the input pin did not save the sample by calling IUnknown::AddRef, the sample is then immediately returned to the allocator.

The output pin may decide not to pass the media sample on to the input, in which case it can just call the sample's IUnknown::Release method without calling the input pin's IMemInputPin::Receive method.

Control Information

There are two types of control information, both of which flow with the media samples from filter to filter:

•	End-of-stream notifications

•	Flushing operations

End-Of-Stream Notifications

It is important for filters to indicate when there is going to be no more data in the current set of data. A filter does this by sending an end-of-stream notification to the next filter, which is accomplished by the output pin calling the IPin::EndOfStream method on the downstream filter's input pin.

When a source filter (an originator of data) reaches the end of its data, it calls the IPin::EndOfStream method on all pins connected to its output pins. This mechanism is propagated down the filter graph so that each filter that processes its EndOfStream method in turn calls EndOfStream on the pins connected to its output pins. When the notification reaches the end of the line in the filter graph, the renderer passes an EC_COMPLETE notification to the filter graph manager. The filter graph manager counts the EC_COMPLETE notifications it receives and when all renderer filters have completed, it passes the notification to the application.

Although source filters usually originate the end-of-stream notification, it is also possible for other filters to detect this condition and generate the notification downstream. Most notably, this applies to parser filters that connect. For example, the MPEG parser (in the MPEG splitter filter) can detect the end of the stream and when it does, return S_FALSE from the Receive method, which signals the upstream filter to stop sending data until a seek occurs or the filter graph is stopped.

Flushing Operations

In the ActiveMovie filter graph architecture, flushing is a two-stage process. Flushing is not usually initiated as part of normal data flow, but rather as a result of a control action from the filter graph manager. As such, it is an asynchronous event which requires graceful flushing of old data followed by a resynchronization and pushing of new data.

In a flushing operation, first IPin::BeginFlush is called by the source filter on all input pins connected to its output pins. This call is propagated down the graph by all filters to the rendering filter or filters. After BeginFlush has been called, an input pin should reject all data until its IPin::EndFlush method has been called. It should also free any connected pins waiting for any of its resources. In the case of the local memory transport, this means that every renderer filter should free any filter waiting for a sample from its allocator.

After a filter has called BeginFlush on the pins connected to its output pins it should call IPin::EndFlush when it can guarantee that all processing of samples by its pins is complete and no more samples will be processed. For source filters this means shutting down data generation, then calling EndFlush on the pins connected to its output pins. For other filters it means waiting for an EndFlush call (which guarantees that no more samples will be sent) and then waiting for any queues it maintains itself to empty. Because calls can block on downstream filters for the local memory transport model, it is important to wait for queues to empty when EndFlush is called, rather than trying to do so when BeginFlush is called.

Event Notifications

Notification data goes from filters to the filter graph manager and can be passed on to the application. The EC_COMPLETE notification, which occurs at the end of a data stream, has already been mentioned. There are also many other event notifications, many of which are sent by specialized filters, such as the renderer to communicate with a host application. Another class of notifications are error notifications, which are also sent from filters to the filter graph manager.

The convention for ActiveMovie filters is that a filter that detects an error report, it passes a notification to the filter graph manager by calling the IMediaEventSink::Notify method. Errors in processing data can generate several errors, including the following:

•	EC_STREAM_ERROR_STOPPED, if no more data can be processed.

•	EC_STREAM_ERROR_STILLPLAYING, if data can still be processed.

If processing can no longer continue, the filter graph manager should be notified with EC_STREAM_ERROR_STOPPED and the appropriate convention for the particular transport should be used to notify the upstream output pin. In the case of the local memory transport, this involves returning an error value from IMemInputPin::Receive.

Errors of this type can be caused by events such as being out of memory or encountering other resource problems. Or they may be caused by other events such as a failure to obtain a buffer when trying to pass data downstream.

On the other hand, when an error occurs but processing can still continue, the EC_STREAM_ERROR_STILLPLAYING error should be sent to the filter graph manager. In this case, the upstream output pin should not be notified. Specifically, for the local memory transport, the input pin's IMemInputPin::Receive method should return NOERROR when this type of error occurs.

Filter Graph Control Data

Control data originates at the application and is passed to the filter graph manager. At the COM level, this is handled by filter graph manager interfaces in the control.odl type definition library. Examples of control data are calls to the IMediaControl interfaces, such as IMediaControl::Run, IMediaControl::Pause, and IMediaControl::Stop. The IMediaPosition and IMediaSelection interfaces provide access to moving forward or backward in a media stream.

The most important thing to understand about the flow of control data is that it should always pass through the filter graph manager first. This is because there is usually an order that must be followed in controlling the filters in the filter graph to avoid deadlocks and other problems. The filter graph manager is dedicated to handling these conditions.

Quality Control Data

The ActiveMovie stream architecture provides for graceful adaptation of media rendering to overloaded or underloaded media streams. The IQualityControl interface is used to send quality-control notification messages from a renderer filter either upstream, to be acted on eventually by some filter in the graph, or directly to a designated location. For example, a renderer that is getting too many frames to process can try to get an upstream filter to cut down on the number of frames it is sending. This is usually more efficient than simply dropping frames at the renderer, which may not do any good at all in some cases. (A video decompressor filter takes many CPU cycles decompressing frames, so it is better to discard samples before processing them rather than after processing them.) Likewise, when the renderer filter can handle more data, it sends notifications to increase the number of samples.

Quality-control messages are passed upstream by default; if a filter has no registered quality sink, the default action passes the message to the IQualityControl interface of the connected output pin. Internally, the output pin passes the quality-control message to its input pin, if it has one, and the message travels upstream until it reaches a filter that can affect the data stream quality in the requested manner. ActiveMovie handles this mechanism automatically in the transform base classes.

If a filter can handle the situation and if it is not appropriate for filters further upstream to take any action, that filter will consume the notification, act on it and not pass it on. A filter can both act on the message and pass it on, or take no action and pass it on. Silently accepting the messages and taking no action is considered bad behavior and may damage the performance of the filter graph as a whole.

A quality sink is a feature implemented by the IQualityControl::SetSink method. When this method is called, the filter is instructed not to send messages upstream, but rather to send them to the object passed to the SetSink method. Typically, this object would be a component called a quality-control manager. Such a component would set itself as the sink for all the filters to send the quality-control messages rather than anywhere else. It would then decide whether to route the messages upstream or to take some other action, such as cutting back the video stream to avoid breaking the audio. A quality-control manager is not provided in the initial version of ActiveMovie but can be implemented using the existing IQualityControl interface and should be anticipated when writing filters.


Getting Started with ActiveMovie Tools

This article describes some of the tools and practices required to develop a filter using the Microsoft® ActiveMovie™ Software Development Kit (SDK). It includes a brief overview of the Filter Graph Editor (GraphEdit), an explanation of the globally unique identifier (GUID), and an overview of how to register an ActiveMovie filter.

The Filter Graph Editor

The Microsoft ActiveMovie SDK includes a tool called the Filter Graph Editor (graphedt.exe) that provides a graphical representation of filters, pins, and a filter graph. Use the Insert menu in the editor to insert a filter graph.

For example, if you insert the Bouncing Ball source filter, a box labeled Bouncing Ball appears.

To construct the filter graph, right-click the output pin located on the right side of the box. Then click Render, and the filter graph required to render the bouncing ball source is automatically generated by the filter graph manager. Notice that the Video Renderer filter is displayed, and its input pin is connected to the output pin of the Bouncing Ball box. The connected filters represent a filter graph. To view the current format of a pin, right-click the pin, and then click Properties.

Click the Play, Stop, or Pause button to control the filter graph. You can create a new graph by deleting or adding filters. You can connect the filters in the graph either by automatically rendering it (using Render) or by dragging from the output pin of one filter to the input pin of another filter. Only certain pins, and therefore certain filters, can be connected, because they have to support a common format.

Globally Unique Identifiers (GUIDs)

A globally unique identifier (GUID) is a 128-bit (16-byte) integer that an algorithm creates. The algorithm uses several criteria, including the current date, time, and a machine identifier, to ensure that it will be unique. GUIDs are used extensively in the OLE Component Object Model (COM) and have an important role in ActiveMovie.

GUIDs identify filters, pins, and major and minor media types. In developing a filter, you must generate your own GUIDs. Use a utility, such as guidgen.exe or uuidgen.exe. Both of these utilities provide options for the output format. Uuidgen is a console application; you must carry out the "UUIDGEN -?" command to obtain information about how to use the utility. Guidgen is a graphical application; you can copy its output to the clipboard and paste it into source code.

Guidgen generated the following example, using the DEFINE_GUID option. The commented line demonstrates how the GUID will appear in the registry. Fill in "name" with the name you want to give this GUID.

   // {8A96EC30-239C-11cf-B58D-524153480000}

     DEFINE_GUID(<<name>>,

   0x8a96ec30, 0x239c, 0x11cf, 0xb5, 0x8d, 0x52, 0x41, 0x53, 0x48, 0x0, 0x0);

Typically, the GUID of a filter is generated once during development, with separate filters requiring separate GUIDs. It is important to generate your own GUID for your filter rather than using one, for example, from a sample application you may be using as a template. If filters have duplicate GUIDs, only one will be available for use.

ActiveMovie and the Registry

The following section describes how to install your filter and how the ActiveMovie filter mapper utilizes the registry to construct filter graphs. Examine the registry with tools such as RegEdit from Microsoft® Windows® 95 and RegEdt32 from Microsoft® Windows NT®.

Installing Filters

Currently, filter information is added to the registry through registry (.reg) files. Use the registry files provided with the ActiveMovie samples as a starting point for your own registry file. Copy your own GUIDs into that registry file. Note, however, that standard GUIDs are used for the input and output pin types, so you will not generate those unless you support your own format. Copy your filter to a directory in your path, and run the registry file to install it. Ultimately, the location of the filter in the registry should include the full path to the filter, so it will not need to reside in a directory in your path. In the future, registry files will no longer be necessary for installation.

ActiveMovie and the Component Object Model (COM)

Components of the ActiveMovie filter graph architecture are implemented as OLE COM objects, including filters, multimedia data, and pins. Every component object is characterized by one or more interfaces. An interface contains a predefined set of implemented functions, called methods. Applications or other component objects call methods to communicate with the object that is exposing the interface. To facilitate filter development, the ActiveMovie SDK provides C++ classes that help implement the interfaces you choose to have your objects support.

ActiveMovie Additions to the Registry

During installation, ActiveMovie creates the Filter section of the HKEY_CLASSES_ROOT hive and fills it with the GUIDs of filters included with the ActiveMovie SDK, as shown below.

Filter information, including the interfaces and pins exposed, is placed in the CLSID section of HKEY_CLASSES_ROOT using the GUID of the filter. The CLSID entry for a filter can look like the following:

Filter Mapper and Filter Graph Construction

During construction of a filter graph, the filter mapper consults the registry extensively. Starting in the HKEY_CLASSES_ROOT\Filter section (as shown in the previous example), the mapper obtains a list of all installed filters by enumerating all subkeys. Given a GUID of a filter as the cross-reference key, the filter mapper retrieves the filter's information, including input and output pin format, from the HKEY_CLASSES_ROOT\CLSID section. The filter is added to the graph if the filter mapper determines that, ultimately, the filter assists in reaching the appropriate renderer. Disconnected filters within the graph are queried before any registry access to improve performance.


The Connection Model

This article provides an overview of the basic filter connection architecture in a Microsoft® ActiveMovie™ filter graph by examining the behavior of the base classes in the class library that implement connection. Because filters connect to other filters using pins, the architecture describes pin connection. Consequently, the CBasePin, CBaseOutputPin, and CBaseInputPin base classes and the IPin interface are discussed. This article describes the connection process and the default functionality built into these classes.

The Connection Process

When building a filter graph, the filter graph manager connects pins between filters. It also selects filters based on the media type in the file it has been given to render or selects a predetermined configuration for the filter graph it is assembling. The filter graph manager can be asked specifically to add a filter by using the IFilterGraph::AddFilter method. The filter graph manager calls the IFilter::JoinFilterGraph method on the filter to notify it that it has joined the filter graph. The added filter can then be connected like any other filter. When connecting filters, the filter graph manager requests the filters to enumerate their pins and then, for each connection required, requests that an output pin connect to an input pin.

The base classes handle much of the connection mechanism. However, it is important to understand the connection process when writing a filter so that you can identify what to override and what is expected of your filter. Before two connected filters are prepared to pass media between them, the following connection and negotiation processes must occur in this order:

1	The initial pin connection occurs.

2	The output pin of one filter retrieves interfaces from the connected input pin.

3	Both pins negotiate for a common media type.

4	Both pins negotiate for an appropriate transport to pass the media.

In the first step, the filter graph manager informs the output pin of one filter to connect to a specified input pin of another filter. This results in an exchange of IPin interface pointers. Filters should never connect to other filters by themselves. The filter graph manager must always be the agent that initiates a connection, because deadlocks can occur otherwise. A filter or an application can instruct the filter graph manager to connect two pins (through the IGraphBuilder::Connect or IFilterGraph::ConnectDirect method), or the filter graph manager can determine to connect filters when rendering a filter by using the IGraphBuilder::Render or IGraphBuilder::RenderFile method.

In the second step, the output pin may request the IMemInputPin interface from the connected input pin. This is in preparation for the fourth step, where the output pin will use IMemInputPin to retrieve a memory allocator from the input pin. If the output pin already has a memory allocator (or some other transport in the case of hardware filters), it can skip this step or can request some other interface in a proprietary design.

In the third step, media types are tried until one is found that is acceptable to both pins or the pins run out of types to try (in which case the connection fails). First, the output pin asks the connected input pin to propose its list of media types. If none of these are acceptable to the output pin, the output pin proposes its own types.

In the fourth step, the output pin asks the connected input pin for an allocator interface. The output pin then either accepts the allocator, or proposes its own allocator and notifies the input pin of the selection. The output pin makes the final determination.

How the Base Classes Implement Connection

The CBasePin class and its derived base classes, CBaseOutputPin and CBaseInputPin, implement most of the mechanism for the most common connection scenarios, much of which can be overridden by the derived filter class for more control of the process.

The connection procedure relies on the implementation of four interfaces:

1	IPin, which is implemented by the CBasePin class and inherited by the CBaseInputPin and CBaseOutputPin classes.

2	IEnumMediaTypes, which is implemented by the CEnumMediaTypes class and passed out by the IPin::EnumMediaTypes method.

3	IMemInputPin, which is implemented by the CBaseInputPin class.

4	IMemAllocator, which is implemented by the CBaseAllocator class and passed out by the IMemInputPin::GetAllocator method.

The IMemInputPin and IMemAllocator interfaces are only necessary if the filter belonging to the connecting input pin (called the downstream filter) is expected to provide a shared memory allocator for transporting samples between the pins. However, the base class implementation in CBaseInputPin assumes this condition and implements IMemInputPin to provide an allocator object to a connected output pin that requests it.

In the connection scenario of the default base class, the pin classes derived from CBaseInputPin and CBaseOutputPin need only to override and implement a few member functions and can let the base classes do the remaining work. Base classes derived from these classes, such as CTransformInputPin and CTransformOutputPin, do much of the required implementation to provide a default connection scheme.

Pin classes derived from CBaseInputPin and CBaseOutputPin need only to override the following member functions to enable pin connection:

•	CBasePin::CheckMediaType, which is called for every media type proposed by the media type enumerator. The overriding member function must accept or reject the media type proposed.

•	CBasePin::GetMediaType, which is called by the media type of the output pin enumerator to suggest media types already agreed upon by the input pin for transform filters. This member function also presents the type of media a source filter will produce.

Additionally, the output pin derived from the CBaseOutputPin class must override the CBaseOutputPin::DecideBufferSize member function. This is called by the base classes to let the output pin inform any acquired allocator of the size and type of media samples that the output pin will be providing. This is done by the output pin of the filter because the derived filter class should know the type and size of the data it is going to send to the input pin of the connected filter.

To see the context of these overriding functions, it is helpful to step through the execution of the connection code in the class library. All connection takes place in the scope of one CBasePin::Connect member function.

The Filter Graph Manager Starts the Connection

The connection starts when the filter graph manager calls the IPin::Connect method on the output pin, passing it a pointer to the input pin to which it is connecting. The filter graph manager has previously retrieved pointers to the IPin interfaces of both filters, for example, by calling the IFilter::EnumPins method on each connecting filter. The EnumPins method creates a CEnumPins object to enumerate the pins, which the enumerator does by repeatedly calling the CBaseFilter::GetPin member function of the derived filter, which the derived filter must implement.

The CBasePin::Connect implementation of IPin::Connect does much of the work in this case. It calls the following functions:

•	CheckConnect, which is overridden by CBaseOutputPin.

•	AgreeMediaType, which is implemented by CBasePin.

The CBasePin::CheckConnect implementation simply determines that the pin directions are different. The overriding CBaseOutputPin::CheckConnect member function calls the IUnknown::QueryInterface method of the connected input pin to retrieve a pointer to the IMemInputPin interface of that pin. This will be used later in the connection process to request an allocator from the connected input pin. (Your derived class can override CBaseOutputPin::CheckConnect and omit retrieving the IMemInputPin interface if the output pin already has an allocator; for example, it might want to use the allocator from an upstream filter to eliminate copying.)

Negotiating Media Types with CBasePin::AgreeMediaType

The CBasePin::AgreeMediaType member function is called next and attempts to negotiate a media type that both pins agree upon. It does this by trying to find a media type that is presented by the connected input pin with which the output pin agrees. If that fails, it tries to find a media type preferred by the output pin that the connected input pin agrees with.

CBasePin::AgreeMediaType calls the following member functions and methods:

•	IPin::EnumMediaTypes on the connected pin.

•	CBasePin::TryMediaTypes in the derived output pin class.

The IPin::EnumMediaTypes method of the connected input pin is called to return a media type enumerator (IEnumMediaTypes). This allows the output pin to examine the list of preferred media types belonging to the input pin.

The IEnumMediaTypes::Next method of the enumerator calls the GetMediaType member function of the derived input pin to retrieve each media type. If GetMediaType is not implemented, the base class implementation returns an error but this does not necessarily break the connection. (Pins are not required to have a preferred media type if one pin or the other can propose a type that they both accept. If neither pin can propose types, the connection will fail.)

Determining a Media Type with CBasePin::TryMediaTypes

CBasePin::AgreeMediaType calls CBasePin::TryMediaTypes next. The TryMediaTypes member function cycles through the preferred media types of the connected input pin and calls the CBasePin::CheckMediaType member function of the derived output pin class for each one it finds. CheckMediaType must be implemented by your derived output pin class. If CheckMediaType accepts the media type, the IPin::ReceiveConnection method of the connected input pin is called with the media type to determine if the connected input pin accepts this media type. If so, TryMediaTypes calls the CBaseOutputPin::CompleteConnect member function to finish the connection to the input pin.

If the input pin has no media types that the output type can use, CBasePin::AgreeMediaType repeats the entire process, using the enumerator for the media types of the output pin. (That is, it gets its own enumerator and calls TryMediaTypes with each of its preferred media types.) Again, the enumerator calls GetMediaType for each media type in the list. In this case, GetMediaType should be implemented to provide a media type. If the filter is a source filter, it will have a definite media type to export. If the filter is a transform filter, the media type will be established between the input pin of the filter and its connected pin; the transform filter should query for that media type or simply use the enumerator of the upstream filter (unless the transform filter changes the media type from input pin to output pin).

CheckMediaType is called by CBasePin::TryMediaTypes even when TryMediaTypes enumerates the list of the preferred media types of the output pin. This is because the owning filter may be an inplace-transform filter that is simply using the media type (and enumerator) of an upstream filter; this is the point at which the filter determines if the media type is compatible. The input pin of this transform filter might defer selecting a media type when it is connected, in which case it would be up to the output pin of the transform filter to make sure the media type is compatible with its transform.

If a media type can be established, TryMediaTypes eventually calls the CBaseOutputPin::CompleteConnect member function to negotiate a memory allocator.

First, the CBaseOutputPin::CompleteConnect member function calls the CBaseOutputPin::DecideAllocator member function. This member function negotiates a shared memory allocator with the input pin. It does this by first calling the IMemInputPin::GetAllocator method of the connected input pin, which retrieves a pointer to an IMemAllocator interface provided by the input pin.

Then, CompleteConnect calls the pure virtual CBaseOutputPin::DecideBufferSize member function, which your derived output pin class must override and implement because only the derived class can determine the required buffer size for its media type.

Finally, CompleteConnect calls the IMemInputPin::NotifyAllocator method of the connected pin to inform the input pin of the allocator to use and to provide a pointer to it. The input pin can reject this allocator, in which case the output pin can retry with a different allocator or fail the connection. If your derived class is not using the allocator of the connected input pin, override CBaseOutputPin::DecideAllocator in your derived class to call the NotifyAllocator member function with an allocator.

When a Reconnection Should Occur

Reconnection is always performed through the IFilterGraph interface on the filter graph manager. Reconnection is performed by calling the IFilterGraph::Reconnect method which passes the IPin interfaces of the two pins to be reconnected.

Filters are connected with the upstream filter first and the downstream filter second. That means that the filter negotiates the connection on its input pin before information is available about the filter being connected to its output pin. When the output pin of the filter connects, it may become clear that the media type or allocator that was established for the input pin of the filter are not appropriate. In this case, the input connection can be broken and reconnected.

For example, consider the following connection scenario. An audio effects filter (for example, a reverberation effect) is inserted between an MPEG-audio decompressor filter and another audio effects filter. During the upstream connection to the decompressor filter, a media type is chosen— for example, 22.05Khz, 16-bit mono. However, in this scenario, when the reverberation filter connects its output pin, the downstream filter will only accept an 11.025Khz, 16-bit mono media type. Therefore, after connecting with the downstream filter, the reverberation effects filter must then reconnect with the upstream filter and negotiate for an 11.025Khz media type.

But media types are not the only reason for reconnection. In many cases, the filter is an in-place transform filter; that is, a filter that does not require that it either alters the media type or copies the data. Such a filter can be designed to use an allocator of some other filter (upstream or downstream) and likewise use the media type of another filter. That is, the filter is doing its transform "in place" in the buffer of another filter (for example, in the file buffer of the source filter or the video buffer of the rendering filter).

The general rule is that filters of this type should offer the allocator of the downstream filter to the upstream filter, once the allocator has been established for the output pin. This requires a reconnection of the input pin so that, when the input pin is asked for an allocator (in IMemInputPin::GetAllocator) by the upstream output pin, it can offer the allocator retrieved from the downstream filter by the output pin of the transform filter. Therefore, in-place transforms always reconnect.

There are a couple of important rules to follow when requesting a reconnection.

First, a filter must never request a reconnection unless it is certain that the reconnection will succeed. If the reconnection fails, it causes an asynchronous error in the filter graph for which there is no obvious cleanup. Any error that occurs (for example, from incompatible media types) should occur when the pins are connected the first time, when there are ample retry options available at more than one level (by the filter graph manager or the application at least).

Second, a filter should request a reconnection on the same thread as the call to IPin::Connect. For example, the following scenario will cause problems:

1	The filter graph manager calls Connect on a pin.

2	The filter pin carries out the Connect method and creates a thread, which starts to determine whether everything is OK for the connection.

3	Connect returns to the filter graph manager.

4	The filter graph manager returns to the application.

5	The application calls the IMediaControl::Run method of the filter graph manager to start the filter graph and the filters start running.

6	The thread from the initial connection calls the IFilterGraph::Reconnect method and the filter graph manager attempts to carry out Reconnect.

7	Failure occurs because the filters cannot reconnect while in the running state.

The filter graph has code to prevent this failure as long as the IFilterGraph::Reconnect method takes effect while the filter graph is still processing the IGraphBuilder::Connect method. Calling the filter graph to reconnect before returning from the IPin::Connect method is the best way to ensure this problem does not occur. The best way to achieve this is to perform all of this on the same thread.


Creating a Transform Filter

This article steps through the process of creating a transform filter for a Microsoft® ActiveMovie™ filter graph using Microsoft® Visual C++® and the ActiveMovie C++ class library. The article covers the initialization code requirements for all filters and uses a transform filter as the model for a basic filter.

Developers who wish to write a source or renderer filter may want to read this article to understand how transform filters work with these other types of filters.

How to Write a Transform Filter: A Tutorial

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 inplace.

The fewer number of 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 and augment the IUnknown::QueryInterface code for any unique interfaces in your filter.

This step addresses the Component Object Model (COM) aspects of implementing a filter.

4	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.

Because several of the base class member functions that require overriding involve the connection process, media type, and allocator negotiation, you may want to read some background information on these topics. You can start by reading the section The Connection Model for Transform Filters at the end of this article. For more information about connection, see The Connection Model.

Writing the Filter

This section describes the four basic steps for creating a transform filter.

Step 1: 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 inplace 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 an inplace transform 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 an inplace transform include the following:

•	If the transformation generates more data upon output than space provided in the allocator of the input (for example, a decompressor filter), it will require a copy. If the transformation generates less data upon output and needs to consolidate memory, it will require a copy.

•	If the original media data must be preserved, a copy must be made; 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, a separate copy must be made, primarily because the decompressor cannot allow another filter to have access to the original data to modify it.

•	Any filter that 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.

Step 2: Derive the Classes for Your Filter

At this point, you must decide which base class or classes to use and which member functions you need to override and implement. You can then create the header files to define your derived classes.

Some member functions in the base classes must be overridden in your derived class because they are either declared pure virtual in the base classes (they have no implementation) or have default implementations that do nothing but return some error value. This section demonstrates which member functions are typically overridden and for what purpose.

You either derive your filter class from the transform base classes (CTransformFilter or CTransInPlaceFilter) 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 some assumptions about the workings of transform filters that make the process of creating a transform filter easier.

Using the Transform Base 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 in nature with the transform-inplace classes at the bottom of the hierarchy tree. CTransInPlaceFilter is derived from CTransformFilter, which is in turn derived from CBaseFilter as shown in the following illustration:

The CTransInPlaceInputPin class is derived from CTransformInputPin class. The CTransformInputPin class is derived from the CBaseInputPin class, as shown in the following illustration:

The CTransInPlaceOutputPin class is derived from the CTransformOutputPin class. The CTransformOutputPin class is derived from the CBaseOutputPin class, as shown in the following illustration:

Copy transform and transform-inplace classes share many features, because the inplace transform 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 only need to derive a main filter class (from CTransInPlaceFilter or CTransformFilter).

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 CreateInstance function. For more information about instantiating the filter, see Instantiate the Filter and Add IUnknown Methods. Beyond this, your classes must override a few member functions in the transform base classes.

If your derived filter class is based on the CTransformFilter class, you must override the following member functions.

Base class	Member function	Must override to
CTransformFilter	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.
CTransformInputPin	none
CTransformOutputPin	none
If your derived filter class is based on the CTransInPlaceFilter class, override the following member functions.

Base class	Member function	Must override to
CTransInPlaceFilter	Transform	Implement transform.
	CheckInputType	Verify support of media type.
CTransInPlaceInputPin	none
CTransInPlaceOutputPin	none
Beyond the default implementation in the transform classes, which other member functions you must override depend on what you want your filter to do. First, the GetPin and GetPinCount member functions must be overridden 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 on the pins only. 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 that you are most likely to 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 identified in the following table.

Base class	Member function	Reason to override
CTransInPlaceFilter or CTransformFilter	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.
	BreakConnect	To release extra interfaces when connection is broken.
	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  StopStreaming	To be notified when entering or exiting the streaming state.
	AlterQuality	To do anything with quality-control messages other than passing them on.
CTransInPlaceInputPin or CTransformInputPin
CTransInPlaceOutputPin or CTransformOutputPin
An example of a filter derived from a transform class is the Gargle sample application. This sample uses the inplace transform classes and derives its filter class from the CTransInPlaceFilter class. It uses multiple inheritance to derive from two interfaces used for property pages: ISpecifyPropertyPages and IGargle. ISpecifyPropertyPages is an OLE interface: IGargle is defined in the sample application. The sample application also derives from CPersistStream, which implementsIPersistStream, to store and recall some filter properties along with a stored filter graph. However, only the CTransInPlaceFilter base class is strictly required for the filter implementation.

Following is the declaration in the gargle.h header file for the derived filter class:

// Gargle filter - derived from CTransInPlaceFilter.

const int MaxGargleRate = 1000;    // 1000Hz maximum rate

const int MinGargleRate = 1;       // 1Hz minimum rate

const int DefaultGargleRate = 10;  // 10Hz default

// CGargle

//

class CGargle

    : public CTransInPlaceFilter       // main ActiveMovie interfaces

    , public ISpecifyPropertyPages     // Needed for properties only

    , public IGargle                   // Needed for properties only.

                                       // Without this the PURE virtual

                                       // functions in IGargle will not

                                       // be implemented.  (If they ever

                                       // got called the entire app would

                                       // silently ExitProcess!!).

    , public CPersistStream            // implements IPersistStream

{

public:

    static CUnknown *CreateInstance(LPUNKNOWN punk, HRESULT *phr);

    DECLARE_IUNKNOWN;

    //

    // --- CTransInPlaceFilter Overrides --

    //

    HRESULT CheckInputType(const CMediaType *mtIn);

    // Basic COM - used here to reveal our property interface.

    STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void ** ppv);

    // CPersistStream overrides

    HRESULT WriteToStream(IStream *pStream);

    HRESULT ReadFromStream(IStream *pStream);

    int SizeMax();

    STDMETHODIMP GetClassID(CLSID *pClsid);

    // --- ISpecifyPropertyPages ---

    // return our property pages

    STDMETHODIMP GetPages(CAUUID * pPages);

    // IGargle - private interface to put/set properties

    STDMETHODIMP get_GargleRate(int *GargleRate);

    STDMETHODIMP put_GargleRate(int GargleRate);

    STDMETHODIMP put_DefaultGargleRate(void);

    STDMETHODIMP put_GargleShape(int iGargleShape);

    STDMETHODIMP get_GargleShape(int *GargleShape);

private:

    // Constructor

    CGargle(TCHAR *tszName, LPUNKNOWN punk, HRESULT *phr);

    // Overrides the PURE virtual Transform of CTransInPlaceFilter base class

    // This is where the "real work" is done.

    HRESULT Transform(IMediaSample *pSample);

    // This is where the real work is really done (called from Transform)

    void MessItAbout(PBYTE pb, int cb);

    // Overrides a CTransformInPlace function.  Called as part of connecting.

    virtual HRESULT SetMediaType(PIN_DIRECTION direction, const CMediaType *pmt);

    // If there are multiple instances of this filter active, it's

    // useful for debug messages, and so on, to know which one this is.

    static m_nInstanceCount;                   // total instances

    int m_nThisInstance;

    const int           m_DefaultGargleRate;   // The default rate (Hz)

    int                 m_GargleRate;          // The current rate (Hz)

    int                 m_Shape;               // 0=triangle, 1==square

    int                 m_SamplesPerSec;       // Current sample format

    int                 m_BytesPerSample;      // Current sample format

    int                 m_Channels;            // Current sample format

    int                 m_Phase;               // See MessItAbout in gargle.cpp

    CCritSec            m_GargleLock;          // To serialize access.

};

As you can see from this header file, CGargle overrides the following CTransInPlaceFilter member functions:

•	Transform, which does the main work of CGargle.

•	CheckInputType, to verify the media type during connection.

•	NonDelegatingQueryInterface, to distribute references to extra interfaces.

•	SetMediaType, to force a reconnection when either the input or output pin is connected so that an established media type can be offered to the other pin connection.

Step 3: Instantiate the Filter and Add IUnknown Methods

All filters must add code to let the base classes instantiate the filter. 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).

Instantiating 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 is the CreateInstance member function from the Gargle sample filter:

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 CreateInstancemember function that creates your filter object. The Gargle sample filter does this as follows:

// 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]);

Finally, link your filter to strmbase.lib and export DllGetClassObject and DllCanUnloadNow using a .def file.

Making Added Interfaces Available

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.

ActiveMovie 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 of 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 illustrates how the Gargle sample 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.

Step 4: Override the Base Class Member Functions

When you instantiated the filter (step 3), you wrote the header and defined which member function to implement. In this section, you actually implement the member functions.

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 in-place transform functions will simply modify the code in one buffer.

The CheckInputType Member Function

During the pin connection, the CheckInputType member function of the input pin is called to determine whether the media type proposed is acceptable. The CTransformInputPin::CheckInputType 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;

    }

CheckTransform

Copy transform filters have the option of transforming the media type from the input pin to output pin. Therefore, when the CTransformInputPin::CheckMediaType member function is called during connection, if the output pin is connected (so its media type is known), 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.

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 does not change in an inplace transform filter, as it might in a copy transform filter.

The DecideBufferSize Member Function

Copy transform filters may be required to set 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 has not passed one from further 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 to have the derived class fill in the requirements for the buffer by calling the IMemAllocator::SetProperties method on the allocator object to which it has a reference.

In the CTransInPlaceFilter class, this member function is never called because the allocator of another filter is always being used. It is implemented in the base class header file to return E_UNEXPECTED.

The GetMediaType Member Function

Pins provide enumerators to allow other objects to determine the media type of the pin. The media type enumerator (IEnumMediaTypes) is provided by a pin and is implemented by the pin base classes to call the GetMediaType member function in the pin class. In the copy transform filter classes, the pin GetMediaType member functions simply call the virtual 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 of the transform filter. If the input pin of the transform filter must perform an enumeration, it obtains an enumerator from the input pin of the downstream filter. If the output pin must perform an enumeration, it obtains an enumerator from the output pin of the upstream filter. One consequence of this is that inplace transforms cannot connect to each other unless at least one of them is connected to something else, because neither of the inplace transforms has the capability to propose any media type for the connection.

Other Overrides

If you have derived your filter class from the transform classes and want more than one input pin and one output pin, you must also override the GetPin member function of CTransformFilter or CTransInPlaceFilter so you can create pin objects from your derived classes. If you only override one of the pin classes, you must duplicate the code in GetPin to create the other pin from the appropriate base pin class (for example, from either CTransformInputPin or CTransformOutputPin ).

The base classes implement CBaseOutputPin::DecideAllocator to let the output pin automatically use the allocator of the downstream pin. 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). For example, in the ActiveMovie model, a source filter pushes media samples onto the next filter and insists on its own allocator. If you write an inplace transform filter to be inserted between a source filter and, say, a decompressor filter, the transform filter would be required to present the allocator of the source filter to the decompressor, and this would require overriding the CBaseOutputPin::DecideAllocator member function.

Connecting the Transform Filters

When writing a transform filter, it helps to understand some of the basic mechanics of filter connection, because many of the base classes and member functions used to write a filter involve connecting the filter with other filters.

Filter connection involves negotiating a common media type for each pair of connected pins and agreeing on an allocator to transport the media samples between them. You might find it helpful to read the following two sections about allocator and media sample negotiation before you start, or if you find yourself unsure of the context of any of the base classes or interfaces involved in writing a filter.

How Allocator Negotiation Works

For information about the connection process, including media type and allocator negotiation, see The Connection Model. When you are determining your transform filter characteristics, it may 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 may 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 means of creating a new allocator from the input pin of any connection.

On the other hand, inplace-transform 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 inplace-transforms do not change the media type, the media type from the downstream filter should be offered to the upstream filter upon reconnection.

Filter Graphs: An Example

To better understand the allocation model for an inplace-transform filter, the following illustration shows a simple and common example of a filter graph:

The simple example demonstrates the model of the inplace transform 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 inplace filter (InPlace E). Because it is an inplace-transform 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 decompresser will be writing directly to the video renderer's buffer, which might be a DirectDraw™ surface.

What if the downstream filter from an inplace-transform filter is a copy transform filter? The copy transform filter will offer to create its own allocator on its input pin (the base classes handle this), and that allocator can then be offered upstream by inplace-transform filter upon reconnection.

But consider InPlace B in the example. Even though CopyDec C can create an allocator from its IMemInputPin::GetAllocator method, the source filter, Source A, uses its own buffer — a file buffer. So when InPlace B connects to CopyDec C, InPlace B will have accepted an 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 of CopyDec C, but this allocator will be refused by the source filter, because it is preferable for the decompressor filter to read directly from the file buffer.

Therefore, any upstream filter can force the use of its allocator downstream but should have good reason to do so (such as the case where 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 may help to highlight how transform filters handle media type negotiations.

The Connection Process: A Summary

When an output pin of one filter 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 implement IEnumMediaTypes to repeatedly call a CBasePin member function called GetMediaType for each media type in the list. You implement this member function in your input and output pins 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 implement CheckMediaType to verify whether this type is acceptable. If no media types are found (for example GetMediaType may not even be implemented on the connected input pin or may 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 input pin of the filter.

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 transforms), a reconnection scheme must be in place for offering the media type of the downstream filter to the upstream filter. To understand this, consider the media type negotiation of the inplace-transform Filter B in the following illustration:

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 decide to 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 all the way through, then the BOutPin to CInPin connection will fail. (It is possible to find that an inplace transform 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.


Alternative Video Renderers

Microsoft® ActiveMovie™ provides a window-based video renderer; it also provides a full-screen renderer in the runtime installation. You can use the C++ classes in the ActiveMovie Software Development Kit (SDK) to write alternative video renderers. For alternative renderers to interact correctly with ActiveMovie-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. Consult the SAMPVID sample in the ActiveMovie SDK for an example of an alternative video renderer that uses these classes.

The following sections describe 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 messages). Because of the ongoing development of ActiveMovie, review your implementation periodically to ensure that the renderers are current with the most recent version of ActiveMovie.

Handling Flushing and End-of-Stream Messages

An upstream filter calls the IPin::EndOfStream method when it detects that it will be able to send no more data to the downstream filter, in this case the renderer. A renderer should note this end-of-stream 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 message to the filter graph manager.

Any calls to the IMemInputPin::Receive or IMemInputPin::ReceiveMultiple methods after an end-of-stream notification is signaled should be rejected. The E_UNEXPECTED error message is the most appropriate error message to return in this case. The EC_COMPLETE message should be sent only once by a renderer each time it reaches the end of a stream. Furthermore, EC_COMPLETE messages are never sent except when the filter graph is running. Therefore, if the filter graph is paused when a source filter sends an end-of-stream message, then EC_COMPLETE should not be sent until the filter graph is finally run.

When a filter graph is stopped, any cached end-of-stream message should be cleared. So, if the filter graph is paused and an end-of-stream message is received, and then the filter graph is stopped, the renderer should not send EC_COMPLETE if it is subsequently paused and run. If no seeks have occurred, then the source filter will send another end-of-stream message to reset the state upon the pause that follows the stop. If, however, a seek has occurred while the filter graph is stopped, then the source filter may have data to send, so it won't send an end-of-stream message.

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 messages 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 message 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 handled through deferred commands.)

Video renderers often depend on end-of-stream messages for more than the sending of EC_COMPLETE messages. For example, if a stream has finished playing (that is, an end-of-stream message is sent) and another window is dragged over a video renderer window, a number of WM_PAINT 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 message 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, it is customary for the renderer to draw the playback area black.

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 exceptions. First, 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 onto this queued data. This is an exception to the ActiveMovie 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 onto the image stops the allocator from being decommitted, which in turn makes any subsequent pause 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 may 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 until there is data queued at the renderers. When a renderer is paused, it should return S_FALSE if there is no data currently 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 renders 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 timeout 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 to run or not. If, while a renderer is waiting for data to arrive, its source filter sends an end-of-stream message, then that should also complete the state change.

Once all filters really have data waiting to be rendered, the filter graph will complete its pause state change.

Handling Termination

If the user closes the video window (for instance by pressing ALT-F4), the typical convention is to hide the window immediately and signal EC_USERABORT to the filter graph manager. This message 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 running, the window will be hidden and all further samples delivered rejected. If the window is shown (perhaps through IVideoWindow::put_Visible), then no EC_REPAINT messages should be generated.

Handling Media Types and Dynamic Format Changes

Video renderers in ActiveMovie only accept video formats that can be drawn efficiently. For example the window-based runtime renderer will accept only the RGB format that matches the current display device mode (for example RGB565 when the display is set to 65536 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.

A source filter wanting to change formats dynamically should always call the IPin::QueryAccept method on the renderer input pin (this is implemented in the base classes as a call to CTransformFilter::CheckInputType). Which formats a renderer will allow a source to change to dynamically is also undefined, although at a very minimum, it should allow the source to change palettes. When a source 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.

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 need to save filter graphs exactly during an editing session and restore them later.

Event Notifications

The following section lists the event notifications (messages) that can be sent by a renderer. This section also includes descriptions of the messages.

EC_COMPLETE

This event notification is sent by renderers after all data has been rendered. No more data should be accepted after the EndOfStream method is called on the input pin of the renderer. Only one EC_COMPLETE message must be sent for each logical stream. Stopping a renderer resets any end-of-stream state currently cached.

EC_USERABORT

This event notification is used by video renderers to signal a closure that the user requested. For example, if the user closes the video window. After this message has been sent, no more samples should be accepted until the renderer has gone through a stop transition. No EC_REPAINT notifications should be sent after an EC_USERABORT notification is sent unless the renderer is stopped and reset.

EC_REPAINT

A renderer should send its input pin as the first parameter to the event. 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 allows output pins to handle repaints before the filter graph has to be touched. This will not be done if the graph is stopped as 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 in order 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 side-steps 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.

The EC_REPAINT notification is sent only when the renderer is either paused or stopped. This message signals to the filter graph manager that the renderer needs data. If the filter graph is stopped when it receives one of these messages, it will pause the filter graph, wait all filters to receive data (by calling GetState), and then stop it again. When stopped, a video renderer should hold onto 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 notify that a repaint can be sent, which is turned off after an EC_REPAINT message 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.

EC_PALETTE_CHANGED

This event notification is sent whenever a video renderer detects a palette change in the stream. The ActiveMovie video renderers detect whether a palette has really changed in dynamic format or not. The renderers do this not only to filter out the number of EC_PALETTE_CHANGED messages sent but also to reduce the amount of palette creation, installation, and deletion required as these changes are expensive to process.

EC_VIDEO_SIZE_CHANGED

This event notification is sent whenever a video renderer detects a change in native video size. An application might use this message to negotiate space in a compound document. The actual video dimensions are available through the IBasicVideo control interface. The ActiveMovie renderers detect whether the video has actually changed size or not prior to sending these events.

EC_ACTIVATE

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 message whenever its window is either activated or deactivated. In other words, an EC_ACTIVATE message should be sent for each WM_ACTIVATEAPP message received by a renderer.

When a renderer is being used in full-screen mode, these messages 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 ActiveMovie full-screen renderer uses as a cue to return to typical rendering mode.

EC_FULLSCREEN_LOST

This event notification is sent to an application. The application might use this message to restore the state of a full-screen button for example. The EC_ACTIVATE messages are used internally by ActiveMovie to manage full-screen switching on cues from the video renderers. When the filter graph manager switches out of full-screen mode (resulting from an EC_ACTIVATE message signaling deactivation), it will send an EC_FULLSCREEN_LOST message to the application.

EC_DISPLAY_CHANGED

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 rebooting the machine a renderer may find itself with a bad image format connection. In these situations a renderer may send an EC_DISPLAY_CHANGED event code to the filter graph manager. The first parameter should be the pin which 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.

EC_WINDOW_DESTROYED

This event notification should be sent by renderers when their window is destroyed. The first parameter must be the renderer's IFilter interface. In fact, sending this when the filter is being destroyed might be too late as the filter graph manager might have already been destroyed. Therefore, it is best to handle this when the renderer's IFilter::JoinFilterGraph method is called with a NULL filter graph (indicating that the renderer is about to be removed from the filter graph). Sending these event codes allows 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).


Understanding ActiveMovie Full-Screen Video Render Support

Full-screen support is implemented by Microsoft® ActiveMovie™ in a number of ways that depend on what hardware resources are available. An application may support full-screen video playback through the IVideoWindow interface provided by the filter graph manager. An application may have its own implementation of full-screen playback, but it stands to make less than optimal use of resources than if it uses 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 chosen option is typically picked the first time the filter graph enters full-screen mode. While in full-screen mode, no functions may be made through IVideoWindow (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 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 plug-in distributor first scans all filters supporting IVideoWindow in the filter graph. It 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 cannot be found then the PID tries to find a filter supporting the IVideoWindow interface that can have its window stretched full-screen without penalty. It 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 the filter indicates that its window may be stretched full-screen at no cost, then that becomes the chosen filter.

If a filter is then chosen for stretching upon a request to render full-screen, the PID resets a number of that 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 so that no change is apparent.

Therefore, when changing to full-screen, the application should be aware that the filter graph may change the properties on an IVideoWindow interface in the filter graph. As previously mentioned, access to IVideoWindow properties is not possible when in full-screen mode, so the application cannot easily determine what changes have been made. (These changes should be transparent to the application.)

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 so no overall change is visible.

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 supporting an IVideoWindow interface and assumes that it is the current video renderer filter.

If none are available, the call to change full-screen mode will return VFW_E_NO_FULLSCREEN. When asked to change into full-screen mode, the PID stops the filter graph, if it is not already stopped, disconnects the current renderer and reconnects the ActiveMovie full-screen renderer in its place. If the connection is successful, then the filter graph is restored to its original state.

When switched 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 DirectDraw™. For example, it may switch display full-screen to 320x240 when it might have been in, for example 1024x768. By switching to lower resolution modes, it can cheaply implement full-screen rendering without having to stretch images.

The full-screen renderer currently implements 320x240x8/16 bits per pixel, 320x240x8/16, 640x400x8/16 and 640x480x8/16 display modes. The full-screen renderer will only be used on machines where DirectDraw is available and offers mode changing capabilities. It also relies on the filter that is upstream from the renderer to be enabled by DirectDraw. If either of these conditions are not true, then the PID drops back into a lower performance means of implementing full-screen playback.

Stretching the Output of a Renderer Full-Screen

After trying the first three options, the final effort 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 exactly 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 varies and depends on the resolution currently displayed. The worst scenario is one in which the user is using a relatively high resolution (for example, 1024x768) and the images have to be stretched by the renderer using GDI. This is likely to provide very low frame throughput. Use this method only if necessary.

Implications of Full-Screen Support for the Application

While the interface on the filter graph exposed to applications is kept simple, the underlying implementation is relatively complex. The full-screen renderer has some special properties that developers of applications should be aware of. In particular, the renderer only changes display mode when activated (either paused or run). Therefore, if full-screen mode is switched to when the filter graph is stopped, no change may be obviously visible until the filter graph is started again. When the filter graph is subsequently run, the display mode will change 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 may also copy the behavior of the full-screen renderer and only switch to full-screen when activated. The filter supporting full-screen playback may have to do this as the resources they require to play full-screen may 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 since, if full-screen 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 (that is, tabbing back to the original application).

All renderers that implement IVideoWindow send event codes to the filter graph manager upon the activation and deactivation of their windows. When in full-screen, mode, the PID watches for these. When it sees a window that it made full-screen being deactivated, it will automatically switch out of full-screen and send an EC_FULLSCREEN_LOST event code to the application event queue. This is the only interference the PID implements; all other user interface is left open to the application as described in the remainder of this article.

The end result of this is that when in full-screen mode, no window may be displayed on top of the full-screen window. In fact, when the full-screen renderer switches display mode, it disables all GDI output for other applications, so this is actually impossible. Any user interactions have to be done through hot keys.

Whatever mechanism the PID ultimately uses to implement full-screen playback, it always makes sure that any 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, so 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.

This means that an application can rely on receiving all mouse and keyboard messages when in full- screen mode regardless of what filter is implementing it. It could use this to implement hotkey support for seeking, for example. However, properties can only be set when not in full-screen mode, so if the only time an application is required to catch messages is when in full screen mode, it must set the message drain before turning full-screen on. Likewise, the message drain can only be reset after setting full-screen mode off.

Finally, 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.


Controlling Filter Graphs Using Visual Basic

This article describes how to use the methods, events, and properties exposed by the Microsoft® ActiveMovie™ dynamic-link library, quartz.dll, to render a stream of time-stamped video data in applications based in Microsoft Visual Basic®. More specifically, these methods, events, and properties let an application:

•	Run, pause, or stop the video stream.

•	Set the position in the video stream (seek).

•	Control the audio volume and balance.

•	Size and position the video window.

•	Retrieve and control filter and pin information.

This article is written for the Microsoft Visual Basic developer who is already familiar with Windows® application programming, Windows multimedia programming, and OLE Automation (OA) features of the Microsoft Visual Basic programming system version 4.0.

Before reading this article, see About Filter Graph Architecture.

ActiveMovie 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 is capable of rendering an audio-video interleaved (.avi) file.

In this illustration, 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, ActiveMovie supports an OLE Automation (OA) 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 ActiveMovie interfaces available in quartz.dll for use with Visual Basic-based applications and describes the purpose of each interface.

Interface 	Meaning

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.

IMediaTypeInfo 	Retrieves the media type and subtype.

IMediaPosition 	Controls and retrieves start time, stop time, rate, and current position.

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.

ActiveMovie Interfaces and Visual Basic

To use the ActiveMovie interfaces in your Microsoft Visual Basic-based application, you must register the ActiveMovie control type library in your Visual Basic project.

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 OA information that Visual Basic requires. The following illustration shows the References dialog box:

Once 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.

Note  The type information in the filter graph manager is organized by interface, rather than object.

The VBDemo Sample Application

This section is based on the VBDemo sample application, which lets the user do the following:

•	Choose an ActiveMovie file (.avi, .mpg, or .mov).

•	Display a simple toolbar that lets the user play, pause, or stop the rendering.

•	Display the length of the video and the elapsed time.

•	Display start position and run rate.

•	Display a volume control and balance control.

•	Position the destination window (a shape control) below all other controls in the main form.

The application, when running a file, appears as follows:

Installing the Files

Before using the ActiveMovie 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 ActiveMovie 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 have been successfully installed, start Visual Basic and choose the Tools/References option from the Visual Basic menu. (At startup, Visual Basic examines the registry database for registered OA controls and adds their names to the list that appears in this dialog box.) To use the filter graph manager, click the box that appears next to the ActiveMovie control type library name.

Once the type information has been registered with Visual Basic, you can begin using the filter graph manager and the accompanying interfaces in your application.

Preparing to Use the ActiveMovie Objects

All of the objects in the VBDemo sample program are initialized using the coclass FilgraphManager, which bundles 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. The objects in the sample application are defined 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

All of the programmable objects are initialized 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

The other interfaces available for use with Visual Basic-based applications are obtained 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, the sample application does not instantiate a filter graph until the user selects a file. The code that handles this selection is embedded in the procedure that opens the file, mnu_FileOpen. This code displays the Show Open common dialog box and stores the selected file name in a g_strFileName variable. After this, the code verifies that the correct file type was chosen. Quartz.dll issues an error message if it is passed a file extension other than .mpg, .avi, or .mov.

Once the g_strFileName variable is set, the application instantiates the filter graph manager and creates the filter graph object. The filter graph manager is instantiated when the Visual Basic keyword New is used to create the OA 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 sample application displays a toolbar from which the user controls video rendering. When the user clicks the command button labeled Run, the Run method is activated and a global Boolean variable (fVideoRun) is set to True. This variable is used in a timer procedure that retrieves the current media position (or elapsed rendering time). If the Pause or Stop button is clicked, this variable is set to False, and the current media position is not retrieved during timer events.

The code that activates the Run, Pause, and Stop methods is found in the Toolbar1_ButtonClick procedure. The toolbar contains buttons that are numbered 1, 3, and 5; the buttons numbered 2 and 4 are separators that provide additional space between the buttons, as shown in the following example:

Private Sub Toolbar1_ButtonClick(ByVal Button As Button)

' handle buttons on the toolbar

' buttons 1, 3 and 5 are defined; 2 and 4 are separators

' all ActiveMovie objects are defined only if the user

' has already selected a filename and initialized the objects

    ' 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 = 3 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 = 5 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 shows the code that adjusts the volume (by setting the g_objBasicAudio.Volume property) is found in the slVolume_Change procedure:

Private Sub slVolume_Change()

    'Set the volume on the slider

    g_objBasicAudio.Volume = slVolume.Value

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.

The sample application moves the destination window to a position below the other controls on its main form. In addition to moving the window, the sample application alters the window style by removing the caption, border, and dialog box frame. This is done by setting 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® Win32® Software Development Kit (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 ActiveMovie object properties to be used without conversion. The ActiveMovie object properties are also expressed in pixels. The default units for a Visual Basic form are twips.

The sample application uses the left top of the placeholder rectangle, then resizes the shape based on the size of the specified video. The application determines 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 g_objBasicVideo 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 g_objVideoWindow.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 the tasks that are accomplished in the mnu_FileOpen procedure:

    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 the ScaleMode property is initialized in the Form_Load procedure:

' code fragment from the Form_Load procedure

' ...

    frmMain.ScaleMode = 3    ' pixels

' ...

Avoid attempting to scale the destination window by setting the Width and Height properties for the g_objVideoWindow object because performance suffers considerably.

Tracking Status

The g_objMediaPosition object exposes a number of properties that you can use to retrieve or set the current position, stop point, duration, and rate. When the user selects a file, the sample application retrieves and displays the duration, starting position, and rate. The corresponding code appears in the mnu_FileOpen procedure, as shown in the following example:

    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)

The current position is also displayed, using a timer that is started when the user clicks the Run button. When the user clicks the Run button, a global Boolean variable, g_fVideoRun, is set to True, indicating that the program should retrieve and display the current media position, which is expressed as the elapsed rendering time from the absolute beginning of the multimedia stream.

If the Pause or Stop button is clicked, the variable is set to False, and the current media position is not retrieved. The corresponding code (which displays the current position) appears in the Timer1_Timer procedure, as shown in the following example:

Private Sub Timer1_Timer()

    'Retrieve the Elapsed Time and

    'display it in the corresponding

    'textbox.

Dim Dbl As Double

    If g_fVideoRun = True Then

        Dbl = g_objMediaPosition.CurrentPosition

        If Dbl < g_dblRunLength Then

            txtElapsed.Text = CStr(Dbl)

        Else

            txtElapsed.Text = CStr(g_dblRunLength)

        End If

    End If

End Sub

Start Position

The sample application uses the IMediaPosition.CurrentPosition property to let the user adjust the point at which the video begins rendering. If the user enters a new CurrentPosition and then clicks the Play button, the video begins rendering at the frame whose timestamp is closest to the requested time.

In addition to adjusting the starting time, the user can jump to new frames while the video is rendering by specifying a new value in the corresponding text box and then pressing the ENTER key.

The code that handles the CurrentPosition property is found in the following example of the txtStart_KeyDown procedure:

 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

Rate

The sample application uses 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 code that handles the Rate property is found in the following txtRate_KeyDown procedure:

Private Sub txtRate_KeyDown(KeyCode As Integer, Shift As Integer)

' ActiveMovie 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 instantiate a new ActiveMovie object, it must include a corresponding Set statement to remove that object (and its corresponding resources) from memory prior to shutdown. For example, in the mnu_FileOpen procedure, a new g_objBasicAudio object is instantiated with the following syntax:

Set g_objBasicAudio = g_objMediaControl

When the user selects the Exit command from the File menu, a corresponding Set statement removes this object:

Set g_objBasicAudio = Nothing


Constructing Filter Graphs Using Visual Basic

This article describes how to use the methods, events, and properties exposed by the Microsoft® ActiveMovie™ dynamic-link library, quartz.dll, to manage the components of a filter graph—filters and pins—in applications based on Microsoft® Visual Basic®. More specifically, these methods, events, and properties let an application:

•	Create a new (empty) filter graph.

•	Retrieve a collection of all filters registered on the computer.

•	Add filters to the filter graph.

•	Retrieve a collection of all filters present in the filter graph.

•	Retrieve a collection of all pins defined for a filter.

•	Connect a pin to a specific pin on another filter.

•	Retrieve pin information, including direction and connection information.

•	Generate the complete filter graph from a multimedia source or from a stored filter graph.

•	Generate the filters and pin connections required to render a specific pin.

This article is written for the Microsoft Visual Basic developer who is already familiar with application programming in Microsoft Windows® Windows multimedia programming, and OLE Automation (OA) features of the Microsoft Visual Basic programming system.

Before reading this article, see About Filter Graph Architecture, and Controlling Filter Graphs Using Visual Basic.

About Filter Graphs

The filter graph editor provided with the ActiveMovie Software Development Kit (SDK) is a graphical tool that creates and manages filter graphs. It lets you connect the three types of filters—source filters, transform filters, and renderer filters—with a graphical user interface that lets you quickly and easily establish connections between filter pins. For example, you can render the filter graph for a specific multimedia source file, such as Dolphin.mov, and see each of the connections in the graph, as in the following example:

The same filter graph objects, filters and pins, can be managed from a sample Visual Basic-based application that uses quartz.dll. For simplicity, the Visual Basic-based application uses list boxes rather than graphical elements to show the parts of the filter graph, and displays information for only one filter and only one pin at a time. (The purpose of the application is not to compete with the filter graph editor, but to demonstrate how to retrieve and manage the same underlying filter graph information using Visual Basic.)

The following illustration shows the same multimedia source file, Dolphin.mov, as depicted by the Visual Basic-based sample application:

The list box labeled "Filters in current filter graph" lists the four filters required for this source file. The list box labeled "Pins in selected filter" lists the two pins defined for the selected "IV41 Decompression Filter": the "XForm In" and "XForm Out" pins. The "XForm In" pin is selected, so the application displays detailed information about this pin, including its direction and connection information.

The remainder of this article discusses the Visual Basic code that you can use to retrieve and manage such filter graph information. In addition to the general-purpose code that works with any source input, the application includes a routine that illustrates a more likely use of these properties and methods—building a specific hard-coded filter graph for your Visual Basic-based application.

This article assumes that you have already set up your Visual Basic environment to use quartz.dll. For more information about setting up your Visual Basic environment, see Controlling Filter Graphs Using Visual Basic.

About the ActiveMovie 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 examine connection information and other information for the pin.

Creating a Filter Graph

There are three distinct ways to use qurtz.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 individual filter and pin connection. The three approaches are as follows:

1	Automatic.

Generate the complete filter graph from either a multimedia source or a stored filter graph file.

2	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.

3	Manual.

Create a new (empty) filter graph, add individual filters to the graph, and explicitly add connections between pins.

The sample application, Builder, demonstrates all three approaches. The application's Generate from input file command on the FilterGraph menu supports the first approach. The FilterGraph menu New command (empty) supports the other two approaches.

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" (its IMediaControl.FilterCollection property contains no filter objects), the application calls the IMediaControl.RenderFile method to build up the complete graph:

' fragment from the Filter Graph menu's Generate from input file command

    ' 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:

' fragment from the Filter Graph menu's New (empty) command handler

    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.

The main form of the application includes a button labeled "Add Source Filter..." that uses the common File Open dialog box to query the user for the name of the source file or stored filter graph. The application supplies the specified file as the parameter to AddSourceFilter.

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.

In the sample program, the list box labeled "Registered filters" contains the names of all the filters that appear in the RegFilterCollection property. 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 sample application contains a button labeled "Add" that adds the selected registered filter to the current filter graph. The following code fragment illustrates step 3 in the previous procedure:

' code fragment from the event handler for the "Add" button

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 ActiveMovie 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.

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.

Whenever the user adds a filter to the filter graph, the application refreshes the list of current filters by using the IMediaControl.FilterCollection property as shown in the following code fragment:

' refresh the 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.

The sample application connects two pins using the IPinInfo.Connect method, as shown in the following code fragment. You can call the Connect method from either of the two pins that are to be connected.

' The sample application displays another form to select the second pin

' or "other pin" that is to be connected to this pin.

    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 filter graph editor, 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.

The application includes a command button labeled "Connect Downstream." The code that handles this command automatically establishes all pin connections downstream from the specified pin object as shown in the following code fragment:

' 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.

The sample application uses the IPinInfo.ConnectedTo property to obtain the pin object to which it is connected, as shown in the following code fragment:

' Add detailed pin information to the text box on the right

' when the user clicks on a pin in the list box on the left

  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

Creating a Custom Graph

The sample application featured in this article is similar to the filter graph editor utility, allowing a user to create and manage any filter graph. Most applications will not provide such a general-purpose interface—they are more likely to create only the specific filter graphs needed by the application.

The sample application provides one subroutine that creates such a custom filter graph. The Options menu offers a Build custom graph command that calls this subroutine.

The routine that handles this command creates five filter objects and eight pin objects. The routine then connects pins by calling the IPinInfo.Connect method.

The graph connects the following filters: AVI Source, AVI Decompressor, AVI Splitter, Video Renderer, and Audio Renderer. These filters can be connected by reusing just two pin object variables. For clarity, however, each pin object is defined using a name that indicates its position in the filter graph.

The filters and pins are declared as follows:

Dim pSourceFilter As IFilterInfo  ' AVI Source Filter; has two pins

Dim SourceOutputPin As IPinInfo  'Source Filter output pin

Dim pAVISplitter As IFilterInfo ' AVI Splitter

Dim SplitterInPin As IPinInfo   ' AVI Splitter pin "Input"

Dim SplitterOut00Pin As IPinInfo  ' AVI Splitter pin "Stream 00"

Dim SplitterOut01Pin As IPinInfo  ' AVI Splitter pin "Stream 01"

Dim pDECFilter As IFilterInfo  ' AVI Decompressor; has two pins

Dim DECInPin As IPinInfo   'AVI Decompressor pin "XForm In"

Dim DECOutPin As IPinInfo   ' AVI Decompressor pin "XForm Out"

Dim pVidRenderer As IFilterInfo ' Video Renderer, has one pin

Dim VidRendInPin As IPinInfo  ' Video Renderer pin "Input"

Dim pAudioRenderer As IFilterInfo 'Audio Renderer, has one pin

Dim AudioRendInPin As IPinInfo ' Audio Renderer pin "Input"

The application adds the source filter object by calling the IMediaControl.AddSourceFilter method:

' create the source filter using IMediaControl.AddSourceFilter

    CommonDialog1.ShowOpen  ' get the name of the source AVI file

    g_objMC.AddSourceFilter CommonDialog1.filename, pSourceFilter

The application adds the other filter objects by searching for a specific name in the registered filter collection (the filter collection is available from the IMediaControl.RegFilterCollection property) and calling the IRegFilterInfo.Filter method when it finds the specific filter to add:

' add all non-source filters from the collection of registered filters

    Set g_objRegFilters = g_objMC.RegFilterCollection

' use the local subroutine AddFilter to find the filter named

' "AVI Decompressor" in the collection, and set the variable pDECFilter

    AddFilter "AVI Decompressor", pDECFilter

The AddFilter subroutine of the application loops through all of the filters present in the collection. When the names match, it calls the IRegFilterInfo.Filter method to add the filter to the filter graph:

Private Sub AddFilter(FName As String, f As IFilterInfo)

' call IRegFilterInfo.Filter

    Set LocalRegFilters = g_objMC.RegFilterCollection

    Dim filter As IRegFilterInfo

    For Each filter In LocalRegFilters

        If filter.Name = FName Then

            filter.filter f

            Exit For

        End If

    Next filter

The application calls similar code for the AVI Compressor, AVI Splitter, Video Renderer, and Audio Renderer filters. After obtaining all of the filter objects, the application uses the IFilterInfo.Pins property to find specific pin objects. The code loops through all pin objects in the collection, searching for the specific pin names and setting the individual pin objects when they are found as shown in the following code fragment:

' Get the source filter pin we need to build the graph

For Each pPin In pSourceFilter.Pins

      Debug.Print pPin.Name

      If pPin.Name = "Output" Then

          Set SourceOutputPin = pPin

      End If

    Next pPin

'Add DEC filter

    AddFilter "AVI Decompressor", pDECFilter

    'Print out list of pins on decompressor filter

    For Each pPin In pDECFilter.Pins

      Debug.Print pPin.Name

      ' save specific pins to connect them

      If pPin.Name = "XForm In" Then

          Set DECInPin = pPin

      End If

      If pPin.Name = "XForm Out" Then

          Set DECOutPin = pPin

      End If

    Next pPin

'Add AVI Splitter

    AddFilter "AVI Splitter", pAVISplitter

    'Print out list of pins on decompressor filter

    For Each pPin In pAVISplitter.Pins

      Debug.Print pPin.Name

      ' save specific pins to connect them

      ' pin 0, pin 1

      If pPin.Name = "input pin" Then

          Set SplitterInPin = pPin

      ElseIf pPin.Name = "Stream 00" Then

          Set SplitterOut00Pin = pPin

      ElseIf pPin.Name = "Stream 01" Then

          Set SplitterOut01Pin = pPin

      End If

    Next pPin

After initializing the eight pin objects, it is a simple matter to call the IPinInfo.Connect method to establish the four connections between them. The following code fragment demonstrates the connection calls:

' connect the pins

' Note:  error handling omitted for brevity

'Connect Source video output pin to AVI splitter input pin

    SourceOutputPin.Connect SplitterInPin

' Connect AVI splitter stream 00 to AVI decompressor

    SplitterOut00Pin.Connect DECInPin

' Connect AVI splitter stream 01 to audio renderer

    SplitterOut01Pin.Connect AudioRendInPin

 'Connect AVI decompressor output pin to Video renderer input pin

    DECOutPin.Connect VidRendInPin

You can establish the connection from either pin; after a successful call to the Connect method, you can access the connection information from either pin object.

Summary

In summary, this article discusses the use of the following ActiveMovie objects, properties, and methods:

Task	ActiveMovie 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.


Using the ActiveMovie Control in Visual Basic

This article describes how to use the ActiveMovie™ control in your applications that are based on Microsoft® Visual Basic®. The ActiveMovie control provides methods, properties, events, and user interface elements to support the following tasks:

•	Run, pause, or stop an ActiveMovie multimedia source file.

•	Control the current, start, and end positions that play the ActiveMovie source file.

•	Control the volume, balance, and playback rate.

•	Provide common user interface elements that let the end users of applications position and play the ActiveMovie source file.

This article is written for the Microsoft Visual Basic developer who is already familiar with application programming for Windows® and knows how to use ActiveX™ controls with the Microsoft Visual Basic programming system.

The ActiveMovie control is a high-level interface that meets the needs of most multimedia application developers. Additional lower-level interfaces are also available to Visual Basic programmers. The ActiveMovie dynamic-link library, quartz.dll, exposes programmable objects that offer additional methods and properties to manage ActiveMovie filter graphs. For more information about these other programming interfaces, see Controlling Filter Graphs Using Visual Basic and Constructing Filter Graphs Using Visual Basic.

Using the ActiveMovie Control in Visual Basic

The ActiveMovie control manages most of the details of the display and playback of ActiveMovie files while giving the Visual Basic developer control over the image size, playback rate, volume, balance, and position. With the control, the developer can manage a variety of standard user interface controls, such as rewind and fast forward, and a slider control to set positions within the media file.

The sample application consists of two forms: the main control form (frmMain) and the display form (frmViewer).

The main control form, frmMain, provides menu commands that call ActiveMovie control methods to let you run, pause, and stop multimedia playback. The form also provides menu commands that let you set ActiveMovie control properties that control the enabled and visible properties of the user interface elements.

The main control form contains two command buttons that change the CurrentPosition property of the IMediaPosition object, letting you move forward or backward through the multimedia source file, if the multimedia source type supports this functionality. The main control form provides a slider control that sets the Playback property, setting the playback rate to a value between 0.5 and 1.5. This is used as a multiplier value, where 1.0 is the authored speed, so that 0.5 is half the authored speed and 2.0 is twice the authored speed. You can set this property to values outside this range, but the audio portion tends to become incomprehensible.)

The main control form also contains option buttons that set the display configuration to half size, full size (default), and double size. The main control form appears as follows:

The display form, frmViewer, contains the ActiveMovie control that is displayed when the ActiveMovie multimedia source file is active or when the source is playing. The application resizes the display form to correspond to the selected source. The display form, with all ActiveMovie control user interface elements visible and enabled, appears as follows:

To use the ActiveMovie control in your Visual Basic-based application, you must add the custom control to your project. Use the Custom Controls command from the Tools menu. Select the Microsoft ActiveMovie Control:

The following sections describe how to use some of the properties, methods, and events.

Opening and Running ActiveMovie Source Files

To load and play an ActiveMovie file, set the Filename property of the ActiveMovie control. Depending on the requirements of your application, you can play the file from your code by using methods like Run and Stop, or you can let the user interact with the user interface elements offered by the control.

The Filename property specifies the name of the multimedia source file. When you set the Filename property, several other properties are updated to indicate characteristics of that source file.

Once the Filename property contains a valid filename, you can call the Run method of the control to play the multimedia file. Or, you can enable the control buttons on the display form and let the user play the file.

The sample application contains an Open command on the File menu that sets the value of the Filename property. It invokes the File Open common dialog box to obtain a filename:

   Private Sub mnu_File_Open_Click()

      CommonDialog1.Filter = "All files (*.*)|*.*|ActiveMovie files

(*.mpg;*.mpa;*.mpv;*.mov;*.mpeg;*.enc;*.m1v;*.mp2)|*.mpg;*.mpa;*.mpv;*.mov;*.mpeg;*.enc;*.m1v;*.

mp2|ActiveMovie Streaming Format (*.asf)|*.asf|Audio files (.wav)|*.wav|Video for Windows files

(.avi)|*.avi"

      CommonDialog1.Flags = 4 'Hide read-only check box

      CommonDialog1.ShowOpen

      ' only set the property if the user selected a filename from the common dialog

      If CommonDialog1.filename <> "" Then

         frmViewer.ActiveMovie1.filename = CommonDialog1.filename

         g_FileOpened = True

         g_FileExtension = Right$(CommonDialog1.filename, Len(CommonDialog1.filename) -

InStr(CommonDialog1.filename, "."))

      Else

         GoTo err_FileOpen

      End If

      Call ResizeViewer

      ...

First, the subroutine prepares the common dialog box to only display movie files. After the common dialog box returns, the subroutine checks to determine if a filename was returned.

If a filename was returned, the subroutine sets the Filename property of the ActiveMovie control in addition to some other global variables: gFileOpened to determine whether or not a file has been opened and gFileExtension to determine the type of the file.

Finally, the subroutine calls the ResizeViewer subroutine to make the dimensions of the viewer form match those of the ActiveMovie file. The dimensions of the Visual Basic form are expressed in twips while the dimensions of the multimedia source are expressed in pixels. The ResizeViewer subroutine considers these differences to size the form by using the ScaleHeight and ScaleWidth properties of the form:

' Resize form to dimensions of ActiveMovie control + nonclient region.

    With frmViewer

        .Visible = False

        .Height = .ActiveMovie1.Height + (.Height - .ScaleHeight)

        .Width = .ActiveMovie1.Width + (.Width - .ScaleWidth)

        .Visible = True

    End With

Once the file is loaded successfully, you can play it by clicking the Play button on the control, or by using the Run method. The sample application provides a Run command on its File menu that calls the Run method:

   Private Sub mnu_File_Run_Click()

      If g_FileOpened = True Then

         frmViewer.ActiveMovie1.Run

         frmViewer.ZOrder 0

      End If

Managing the User Interface of the ActiveMovie Control

The display form of the sample application (Viewer.frm) contains the ActiveMovie control. The following illustration shows the control with the status bar visible and the control bar hidden:

You can use the ActiveMovie control properties to show or hide and enable or disable user interface elements of the ActiveMovie control. The sample application includes checked menu commands that let you individually control each of the user interface elements. The commands on the View menu let you control whether the element is visible. The commands on the Enable menu let you control whether the element is enabled.

Whenever the sample application loads a new file, it resets the ActiveMovie control properties to default values and initializes the values of these checked menu commands. This fragment is from the mnu_File_Open_Click procedure:

   With frmViewer.ActiveMovie1

      .EnablePositionControls = False              'Disable/Enable controls.

      .EnableSelectionControls = False

      .EnableTracker = False

      .ShowPositionControls = False                'Show/don't show controls.

      .ShowSelectionControls = False

      .ShowTracker = True

      mnu_Enable_PositionControls.Checked = False  'Check/uncheck menus to match

      mnu_Enable_SelectionControls.Checked = False 'controls.

      mnu_Enable_Tracker.Checked = False

      mnu_View_Tracker.Checked = True

      mnu_View_PositionControls.Checked = False

      mnu_View_SelectionControls.Checked = False

      ...

   End With

Many of the control elements have two properties associated with them: one to enable them and another to make them visible. To use the position controls, set both the EnablePositionControls and ShowPositionControls properties. The following illustration shows the display controls and all position controls with all elements of the user interface both visible and enabled:

Monitoring ActiveMovie Control Events

The ActiveMovie control automatically monitors certain events and calls event procedures accordingly. To handle one of these events, you only provide the event handling code. For example, the StateChange event indicates a change in the state of the multimedia source, such as the change from running to stopped, or the change from paused to running. To take some action when this event occurs, the application provides code as part of the StateChange event of the control.

To demonstrate these event handlers, the sample application provides trivial code that increments a variable. The variable represents a count of the number of times the event has occurred. The current values for these counter variables are displayed at the bottom of the main form. The code for the StateChange event is shown in the following example:

   Private Sub ActiveMovie1_StateChange(ByVal oldState As Long, ByVal newState As Long)

      g_cStateChange = g_cStateChange + 1

      UpdateStatusBar

Each event procedure passes some informational parameters too. For the StateChange event, you can determine the previous state in addition to the current state of the control by examining the oldState and newState parameters.


Controlling Filter Graphs Using C

This article describes how to use the interfaces and methods exposed by the Microsoft® ActiveMovie™ quartz.dll dynamic-link library. These interfaces and methods render a stream of time-stamped video data in applications that are based in Microsoft® Windows®. This article provides an overview of the interfaces and methods to use and then describes their use in the ActiveMovie C-Player sample application. More specifically, these methods let an application:

•	Run, pause, or stop the video stream.

•	Set the position in the video stream (seek).

•	Control the audio volume and balance.

•	Size and position the video window.

This article is written for the C programmer who is already familiar with the Windows application programming interface (API), Windows multimedia programming, and the fundamentals of the OLE Component Object Model (COM).

The Filter Graph Manager

The stream architecture allows applications to communicate with the filter graph manager, and the filter graph manager to communicate with individual filters to control the movement of data through the filter graph. It also allows filters to post events that an application can retrieve, so an application can, for example, retrieve status information about a special filter it has installed.

An application communicates with the filter graph manager and the filters in a specific graph by using the interfaces that are exposed by either the filter graph manager or the filters. The following table identifies these interfaces.

Interface 	Description

IAMCollection 	Represents a collection of objects of type IFilterInfo, IRegFilterInfo, IMediaTypeInfo, and IPinInfo.

IBasicAudio 	Controls and retrieves current volume setting.

IBasicVideo 	Controls a generic video renderer.

IDeferredCommand 	Used in conjunction with IQueueCommand methods to defer the execution of

IFilterInfo methods and properties. 	Allows an OLE Automation client to set and retrieve filter properties.

IGraphBuilder 	Instantiates the filter graph manager.

IMediaControl 	Instantiates the filter graph; controls media flow (running, paused, stopped).

IMediaEvent 	Allows customized event handling for events such as repainting, user termination, completion, and so on.

IMediaPosition 	Controls or retrieves start time, stop time, preroll rate, and current position.

IMediaTypeInfo 	Allows an OLE Automation client retrieve the major type and subtype of a media type.

IQueueCommand 	Allows an application to queue methods and properties so that they are invoked during the rendering of a video stream.

IPinInfo 	Allows an OLE Automation client to set and retrieve filter properties.

IRegFilterInfo 	Allows an OLE Automation client retrieve the name of a registered filter and add a filter to the filter graph.

IVideoWindow 	Controls window aspects of a video renderer.

Of all the interfaces for the filter graph manager, the following are most effectively used by C and C++ programmers. These include:

•	IBasicAudio

•	IBasicVideo

•	IDeferredCommand

•	IGraphBuilder

•	IMediaControl

•	IMediaEvent

•	IMediaPosition

•	IQueueCommand

•	IVideoWindow

The remainder are collection interfaces, which allow OLE Automation clients, such as Visual Basic®, to access the properties of filters, pins, and media types that are not otherwise exposed to these types of applications.

Implementation of Dual Interfaces

Most of the interfaces are implemented as dual interfaces. This means that the methods in each interface can be called directly or through OLE Automation (using the IDispatch::Invokemethod). OLE Automation support is provided for the developer using Microsoft Visual Basic. The developer using C or C++ can avoid the indirection (and accompanying overhead) associated with OLE Automation by calling the methods directly.

The three interfaces that are not implemented as dual interfaces are IQueueCommand, IDeferredCommand, and IGraphBuilder. The methods in these interfaces must be called directly.

Installing and Registering Quartz.dll

Before you begin using the filter graph manager, you must install and register quartz.dll. Currently, the ActiveMovie SDK setup program automates this process. Run setup.exe and choose the Runtime option. This program copies quartz.dll to your windows\system directory and adds the appropriate entries to your system's registration database.

Instantiating the Filter Graph Manager

Once you have registered quartz.dll, you can begin using the filter graph manager in your Windows-based application. The first step is to initialize the COM library by calling the OLE CoInitialize function. The sample application calls CoInitialize within its InitApplication function in the cplay.c file of the C-Player sample application.

The second step is to instantiate the filter graph manager. Most applications should use the CoCreateInstance function to instantiate the filter graph. Both CoCreateInstance and CoGetClassObject can instantiate an object; however, applications typically use the former to instantiate a single object and the latter to instantiate multiple instances of an object.

The complete call to CoCreateInstance appears as follows:

hr = CoCreateInstance( &CLSID_FilterGraph,          // get this documents graph object

  NULL,

  CLSCTX_INPROC_SERVER,

  & IID_IGraphBuilder,

  (void **) &media.pGraph);

The first parameter, CLSID_FilterGraph, is the class identifier (CLSID) for the filter graph manager. This CLSID is defined in the uuids.h file. This file is installed as part of the ActiveMovie SDK.

The CLSID is a 128-bit value that the registration database uses to identify the dynamic-link library (DLL or inproc server). Using this value, COM is able to locate and then load the appropriate DLL.

The fourth parameter passed to the CoCreateInstance function identifies the interface that the application will use to communicate with the object. The REFIID should be IID_IGraphBuilder. This value is defined internally in the ActiveMovie sources and then exposed in the strmif.h file.

If the call to CoCreateInstance is successful, this function returns a pointer to a filter graph manager object in the media.pGraph parameter. Once this pointer is returned, the application begins to call the methods in the IGraphBuilder interface. Typically, the first method called is IGraphBuilder::RenderFile. This method creates a filter graph for the type of file that was supplied as one of the parameters. In addition, the application can use the IGraphBuilder::QueryInterface method to retrieve pointers to any of the interfaces exposed by the filter graph manager. The IGraphBuilder interface derives from IUnknown.

If you are writing your application in C (rather than C++), you must use a vtable pointer to call the methods exposed by IGraphBuilder. The following example illustrates a call to the QueryInterface method on the IGraphBuilder interface from within an application written in C:

hr = media.pGraph->lpVtbl->QueryInterface(media.pGraph,

    &IID_IMediaEvent, (void **) &pME);

If you are writing your application in C++, the function is simpler; it requires less indirection and one less parameter:

hr = m_pGraph->QueryInterface(IID_IMediaEvent, (void **) &pME);

Invoking Methods on the Interfaces

An application can retrieve a pointer to any of the other interfaces exposed by the filter graph manager when calling the IGraphBuilder::QueryInterface method and supplying a REFIID for the corresponding interface. Once this interface pointer is retrieved, the application can begin calling the methods by using the interface's vtable pointer (just as the IGraphBuilder's vtable pointer called the IGraphBuilder::QueryInterface method in the previous example). Having acquired an interface, the application must release it by calling the IUnknown::Release method on that interface.

C-Player Tutorial

The sample described in this tutorial is C-Player, one of the examples included in the ActiveMovie SDK. The source files for this application are in the samples\player\cplay subdirectory of the ActiveMovie SDK project.

This tutorial does not describe the Windows API code that is found in the source files. Instead, it focuses almost exclusively on the code that:

•	Instantiates the filter graph manager.

•	Processes media events.

•	Runs, pauses, and stops the media stream.

The C-Player Sample Application

You can use the C-Player sample application to open an .mov, .mpg, or .avi file and then run, pause, or stop the corresponding media stream. The user interface of the application consists of menus and a toolbar. The menus include File, Media, and Help. The toolbar includes Play, Pause, and Stop buttons.

Once you open a file and click the Play button, the video stream is rendered in the default window of the filter graph manager.

The Modules of C-Player

The sample application consists of six source files. Each file contains source code that accomplishes a specific set of tasks. For example, the about.c module contains the code that displays the About dialog box. The following table identifies each source file and describes its purpose.

File	Description
about.c	Displays the About dialog box.
assert.c	Displays a message box with debugging information.
cplay.c	Processes user input.
file.c	Displays the File Open dialog box.
media.c	Instantiates the filter graph; invokes the filter graph methods to run, pause, and stop the video rendering.
toolbar.c	Draws the toolbar buttons.
The remainder of this article focuses primarily on the code found in the media.c file; however, references to other files appear when describing some of the tasks accomplished by this application.

Using the Filter Graph Manager

The media.c file contains initialization, destruction and cleanup, command handling, and state change code. The initialization code instantiates a filter graph for a particular file type. The destruction code releases the resources and cleans up the variables used by the filter graph. The command handling code invokes the methods required to play, pause, or stop the video rendering. The state change code sets a global variable that indicates valid media states (that is, can stop, can pause, can play).

Initializing the Filter Graph Manager and the Filter Graph

Typically, the first thing a user does with C-Player is open a multimedia file (either an .mpg, .avi, or .mov file). The extension is really unimportant, because the ActiveMovie filter graph examines the file header to ensure that the file contains a Motion Motion Picture Experts Group (MPEG), audio-video interleaved (AVI), or Apple® QuickTime® file.

The user opens a file by choosing the Open option from the File menu. This action calls the OpenMediaFile function (in media.c), which displays the File Open common dialog box and passes the name of the user's request to another function in media.c. This instantiates the filter graph manager and the filter graph as shown in the following example:

 void OpenMediaFile( HWND hwnd, LPSTR szFile ){

/* File..Open has been selected */

    static char szFileName[ _MAX_PATH ];

    static char szTitleName[ _MAX_FNAME + _MAX_EXT ];

    if( szFile!=NULL && RenderFile( szFile ) ){

        LPSTR szTitle;

        // Work out the full path name and the file name from the

        // specified file.

        GetFullPathName( szFile, _MAX_PATH, szFileName, &szTitle );

        strncpy( szTitleName, szTitle, _MAX_FNAME + _MAX_EXT );

        szTitleName[ _MAX_FNAME + _MAX_EXT -1 ] = '\0';

        // Set the main window title and update the state.

        SetTitle( hwnd, szTitleName );

        ChangeStateTo( Stopped );

    } else if( DoFileOpenDialog( hwnd, szFileName, szTitleName )

               && RenderFile( szFileName ) ){

        // Set the main window title and update the state.

        SetTitle( hwnd, szTitleName );

        ChangeStateTo( Stopped );

    }

}

The OpenMediaFile function passes the name of the user's chosen file to the RenderFile function (which also is found in media.c). RenderFile instantiates the filter graph manager and creates a filter graph.

To instantiate the filter graph manager, the RenderFile function calls CreateFilterGraph. This function instantiates the filter graph manager by calling the COM CoCreateInstance function. It saves the pointer returned by CoCreateInstance in the pGraph member of a global media structure (a structure defined in media.h) as shown in the following example:

BOOL RenderFile( LPSTR szFileName ){

    HRESULT hr;

    WCHAR wPath[MAX_PATH];

...

    if ( !CreateFilterGraph() ) {

        PlayerMessageBox( IDS_CANT_INIT_QUARTZ );

        return FALSE;

    }

...

}

Using the pointer returned by CoCreateInstance, the CreateFilterGraph function retrieves a pointer to the IMediaEvent interface by calling the IGraphBuilder::QueryInterface method. The interface pointer retrieves an event notification handle by calling the IMediaEvent::GetEventHandle method. This handle is used in a special event-notification function that is called from within the main message loop (DoMainLoop) in cplay.c.

Finally, the pointer to the IMediaEvent interface is released by calling the IGraphBuilder::Release method. This is part of the COM contract; once an application finishes using a pointer retrieved by calling IGraphBuilder::QueryInterface, it should inform COM that it is no longer using the interface (or the corresponding pointer) by calling the release method.

The CreateFilterGraph function, which creates the filter graph manager, appears as follows:

BOOL CreateFilterGraph( void ){

    IMediaEvent *pME;

    HRESULT hr;            // return code

    ASSERT(media.pGraph == NULL);

    hr = CoCreateInstance( &CLSID_FilterGraph,    // get this

                                                  // document's graph

                                                  // object

                          NULL,

                          CLSCTX_INPROC_SERVER,

                          & IID_IGraphBuilder,

                          (void **) &media.pGraph);

if (FAILED(hr)){

              media.pGraph = NULL;

        return FALSE;

    }

    // Set up an event file so that we can be notified when the

    // graph stops playing.

    hr = media.pGraph->lpVtbl->QueryInterface(media.pGraph,

        &IID_IMediaEvent, (void **) &pME);

    if (FAILED(hr)) {

        DeleteContents();

        return FALSE;

    }

After creating the filter graph manager, the RenderFile function calls the IGraphBuilder::RenderFile method to create the actual filter graph:

BOOL RenderFile( LPSTR szFileName ){

    HRESULT hr;

    WCHAR wPath[MAX_PATH];

...

hr = media.pGraph->lpVtbl->RenderFile(media.pGraph, wPath, NULL);

...

}

Playing, Pausing, and Stopping the Video Stream

Once the filter graph manager and the filter graph have been created, the application can expose the user interface, which lets the user play, pause, and stop video rendering. In the case of C-Player, the toolbar buttons (Play, Pause, and Stop) are redrawn in color after the user chooses a valid file.

When the user clicks the Play button, the OnMediaPlay function is called. This function accomplishes the following tasks:

1	Examines the global state variable in the media structure to ensure that the video can be rendered.

2	Retrieves a pointer to the IMediaControl interface.

3	Invokes the IMediaControl::Run method.

4	Releases the IMediaControl interface.

5	Sets the global state variable.

The OnMediaPlay function appears as follows:

void OnMediaPlay( void ){

    if( CanPlay() ){

        HRESULT   hr;

        IMediaControl *pMC;

        // Obtain the interface to our filter graph.

        hr = media.pGraph->lpVtbl->QueryInterface(media.pGraph,

            &IID_IMediaControl, (void **) &pMC);

        if( SUCCEEDED(hr) ){

            // Ask the filter graph to play and release the interface.

            hr = pMC->lpVtbl->Run( pMC );

            pMC->lpVtbl->Release( pMC );

            if( SUCCEEDED(hr) ){

                ChangeStateTo( Playing );

                return;

            }

        }

        // Inform the user that an error occurred.

        PlayerMessageBox( IDS_CANT_PLAY );

    }

}

The code that handles pausing and stopping the video stream is nearly identical to the code that plays the media stream. The actual functions that handle these tasks are OnMediaPause and OnMediaStop, respectively. All of this code can be found in the media.c file.

Handling Events

The IMediaEvent interface allows an application to receive events that are raised by the filter graph or by individual filters within the graph. Following are some of the possible events and corresponding event messages.

Event notification message	Description
EC_COMPLETE	The video has finished rendering.
EC_USERABORT	A user has forced the termination of a requested operation.
EC_ERRORABORT	An error forced the termination of a requested operation.
EC_PALETTE_CHANGED	The video palette has changed.
EC_REPAINT	The display should be repainted.
The sample application tracks the EC_COMPLETE, EC_USERABORT, and EC_ERRORABORT events by using the IMediaEvent::GetEvent method. This method is from within the OnGraphNotify function found in media.c. If any of these events are raised, OnGraphNotify immediately stops video rendering by calling the OnMediaStop function.

The OnGraphNotify function appears as follows:

void OnGraphNotify(void) {

    IMediaEvent *pME;

    long lEventCode, lParam1, lParam2;

    ASSERT( media.hGraphNotifyEvent != NULL );

    if( SUCCEEDED(media.pGraph->lpVtbl->QueryInterface(media.pGraph,

            &IID_IMediaEvent, (void **) &pME))){

        if( SUCCEEDED(pME->lpVtbl->GetEvent(pME, &lEventCode, &lParam1,

                &lParam2, 0))

            && ( lEventCode == EC_COMPLETE

                || lEventCode == EC_USERABORT

                || lEventCode == EC_ERRORABORT

                )

          )

            OnMediaStop();

              pME->lpVtbl->Release( pME );

              }

}

The OnGraphNotify function is called from within the main message loop function (DoMainLoop) of the application, which is found in the cplay.c file.


Debugging with ActiveMovie

Debugging in Microsoft® ActiveMovie™ can mean several things. If you are developing a filter using the ActiveMovie class library, you'll probably be writing in Microsoft Visual C++®. This presents one set of debugging problems. If you are developing an application, you might be using C, C++, Visual Basic®, or MCI commands. The debugging paths you choose will vary depending on your approach.

This article discusses debugging practices in ActiveMovie for the C and C++ language. Many of these practices apply both to writing filters and to writing applications that use the ActiveMovie runtime.

This article first provides some tips on writing code that can be easily debugged and tested. It then discusses the use of debug and performance builds, and the need to obtain symbols for use in debugging. Then it gives a warning about the difficulty of debugging real-time ActiveMovie code, and hints for debugging real-time code anyway. Next are some general debugging topics. These topics are followed by a section on debugging new filters. Finally, some hints are given on detecting leaks in the ActiveMovie environment, and dealing with memory corruption.

Writing Code You Can Test and Debug

Debugging code in the ActiveMovie environment can be easier if it's written to be testable and debuggable in the first place. Some techniques supported by ActiveMovie include the following:

•	Use assertion checking.

•	Pass debug names to class constructors.

•	Add debug logging by module level.

•	Use iostream C++ sample code.

•	Check critical section usage.

•	Consider pointer validation.

•	Avoid DLL base address conflicts.

Assertion Checking

Use assertion checking liberally. ActiveMovie provides a number of assertion macros and functions, including ASSERT. For more information about assertion, see Assert Macros and Functions. For example:

    ASSERT( First != NULL );

Pass Debugging Names

Pass the debugging name to the constructors that support it. For the CBaseObject class and classes derived from it, tracking of object creation and destruction is provided in debugging builds. The object register is the list of objects that have been created but not yet destroyed in those classes. The debugging name that is passed to the constructors of those classes is stored in the object register. For more information about debugging object registers and the DbgDumpObjectRegister function, see the Object Register Debugging.

Debug Logging

Consider debug logging as explained in the ActiveMovie reference section Debug Logging by Module Level. That describes the following:

•	The macros and functions you can call to do debugging logging from code you write.

•	How to enable and disable debugging logging by module level at run time.

•	How to indicate the destination of the output of the debugging log.

IOStream Sample Code

The C and C++ helpers provided in the IOStream helper library, SampIOS.lib, provide text output of the IFilter interface and other ActiveMovie objects. The output from these helpers might be useful during debugging, to help understand the details of a given pin or filter. You can use these helpers in your ActiveMovie filters and applications. For more information about this library, see IOStream Helper Library (SampIOS.lib).

Critical Section Usage

To make deadlocks easier to track, insert assertions in the code that determine whether or not a critical section is owned by the calling code. The CritCheckIn and CritCheckOut functions indicate whether or not the calling thread owns the given critical sections, and are generally called in ASSERT macros. For more information about these functions, see CCritSec Debug Functions.

For debug logging of each lock and unlock of a given critical section, you might want to use the ActiveMovie DbgLockTrace function.

Note  Logging can affect performance.

Pointer Validation

Consider using the pointer validation macros. For example, you can call ValidateReadPtr to ensure that the given pointer actually points to readable memory. Make note of the performance cost of each of these calls. Currently, the ActiveMovie ValidateXxxPtr macros are built on top of the Win32 IsBadXxxPtr functions. On some systems, the IsBadXxxPtr functions swap in every page in the range specified. For more information about validation macros, see Pointer Validation Macros.

DLL Base Address Conflicts

If you copy any sample makefile to create any new DLL, including filters and plug-in distributors (PIDs), make sure you change the base address to avoid collisions with other DLLs. A collision of DLL load address results in one of the DLLs having to be relocated during the time of loading. This increases the load time for that DLL.

In the sample makefiles, the DLL base address is set in DLL_BASE, which is used in ActiveX.mak. Do not let ActiveX.mak use the default value for DLL_BASE, because this will cause collisions.

Using Different Kinds of Builds

ActiveMovie can be built for three kinds of builds: retail, debug, and performance. The Reserved Identifiers reference section explains the kinds of builds. Debugging has varying degrees of difficulty for the three kinds of builds, depending on the situation. For instance, the debug build may provide much more information, but it may run so slowly as to make real-time debugging impossible.

The binaries you create need to match the kind of build you're using. The makefiles provided for each individual sample use ActiveX.mak, which comes with the ActiveMovie SDK. Comments at the head of ActiveX.mak explain the various nmake command-line parameters to use to obtain binaries compatible with the different ActiveMovie builds. Some of these parameters define identifiers like DEBUG and PERF when compiling the C or C++ code.

If you need to have build-dependent code, you may conditionally compile with the same identifiers that the ActiveMovie headers use for that purpose. The Reserved Identifiers section lists the identifiers reserved for that purpose.

For instance, in C or C++, you can conditionally compile code like this:

    ...   /* normal processing */

#ifdef DEBUG

    ...   /* debug only code */

#endif

    ...   /* resume normal processing */

Generating and Installing Debugging Information

Any debugger will need access to the debug information for the code you're debugging. (Debug information might include symbols and/or source line numbers.) The means of requesting the debug information depends on your compiler and operating system. On some systems, the debug information is added to the object files themselves; other systems may have separate files. Refer to your compiler and debugger documentation for explanations of the location and format of the debug information.

For effective debugging in the ActiveMovie environment, you should have access to the debug information for the following components when you're debugging problems:

•	Your own code (filters and/or applications).

•	The operating system code itself.

•	The C/C++ runtime library.

Real-Time Debugging Caveat

Once you get a Run command, ActiveMovie becomes a real-time system, and at that point any normal debug output is liable to upset things. You cannot step through the code and expect it to reproduce a bug.

If you run into this condition, you should consider these ways to work around it:

•	Turn down one or more debug output levels. For more information about setting output levels, see the Debug Logging by Module Level reference section.

•	If your clock source supports it, turn down (or turn off) the clock.

First-Time ActiveMovie Debugging

If you're debugging in the ActiveMovie environment for the first time, there are some things to consider. These are described in the following sections in more detail.

•	calling convention differences

•	memory model

•	C++ "name mangling"

Check for Calling Convention Differences

If you have problems the first time you link to or call ActiveMovie code from your code, here are some things to check:

•	The calling convention must be compatible. ActiveMovie uses the same calling convention as OLE. Different calling conventions might cause link errors or errors at run-time.

•	On x86 systems, the memory model must be compatible.

•	For C++ code, the "name mangling" must be done the same way. "Name mangling" refers to the way some C++ compilers turn possibly overloaded class/method/operator names into unique flat names suitable for linking. Different C++ compilers do this differently.

Debugging New Filters

Avoid GUID Conflicts

ActiveMovie uses GUIDs (Globally Unique IDs) to find each filter, pin, and property page. Avoid reusing any of the same GUIDs when copying from the ActiveMovie sample code. Multiple use of the same GUID for different things can cause trouble in the registry and at run time. Use GUIDGEN.EXE (or UUIDGEN.EXE) and avoid this. For more information about ActiveMovie GUID usage and those tools, see the Globally Unique Identifiers (GUIDs) section.

On the other hand, media types and subtypes are also indicated by GUIDs. If you are supporting the same kind of media as some sample code, then using the same GUID for the media type/subtype is probably correct.

Test With Filter Graph Editor and Other Sample Filters

The ActiveMovie SDK includes a tool called the Filter Graph Editor (GraphEdt.exe). Once you have your new filter's registry information set, you can use the Filter Graph Editor to interactively test your filter. For more information, see The Filter Graph Editor overview.

When the Filter Graph Editor is unable to create an instance of the filter, it displays the following error message: "The filter could not be created. Resources used by this filter may already be in use." Make sure that the class ID and path in the registry match those for your filter. Make sure you re-register your filter after modifying any GUID it uses.

If you are debugging an audio filter, there are two sample filters you might consider debugging with. For overviews on those code samples, see the Audio Synthesizer (Synth.ax) and Oscilloscope Filter (Scope.ax) sample documentation sections.

Once you have the Filter Graph Editor successfully loading your new filter, you can use the File Dump Filter (Dump.ax) as a useful debugging tool. For instance, it can be used to verify, bit by bit, the results of a transform filter. Build a graph manually using the Filter Graph Editor and hook the File Dump Filter onto the output of a transform or any other pin. You can also hook up a Sample Tee Filter (InfTee.ax) and put the File Dump Filter on one leg of the tee and the "normal" output on another to monitor what happens in the real-time case. For more information, see the File Dump Filter (Dump.ax) sample documentation.

Associate the Filter File Type (.ax) in MSDEV Debugger

If you're going to debug your filter with Microsoft Developer Studio (MSDEV), you need to tell the debugger about the new file type (.ax). Here are the MSDEV steps you should follow to identify the filter file type (.ax) as being a debuggable DLL:

1	Go to Build.Settings.Debug.

2	Choose "additional DLLs".

3	Add "whatever.ax" to the list, where "whatever" is the name of your filter.

Detecting Leaks

Leaks of any sort (no matter how small) can cause problems over the long run. Imagine an ActiveMovie-based application as a "video kiosk," running 24 hours a day. What if it has a bug that leaks a HANDLE value for each customer? Even if the first 10,000 customers are happy, the ones after that will be denied service. To avoid all those potential unhappy customers, it is important to be thorough in stamping out all leaks.

Use Memory Leak Tools

Unfortunately, C++ has lots of potential for leaking memory. Code written in C may also leak memory, although there are fewer opportunities for problems. In either language, detecting memory leaks "by hand" is not trivial. You should use tools to help detect memory leaks while you're debugging and testing the code. Some of the available tools (which are useful with ActiveMovie) include the following:

•	Visual C++ has an optional debug heap which can be useful in tracking down memory leaks. See the "Using the Debug Heap" section of the Visual C++ documentation. For example, the Visual C++ _CrtSetDbgFlag function allows you to turn on the memory leak checking flag bit.

•	BOUNDS-CHECKER™ (by Nu-Mega Technologies) is another good tool for detecting memory leaks.

Find COM Object Reference Leaks

Another kind of leak is of COM object references. You can track down object reference leaks by using the following steps:

1	Put a break point on the NonDelegatingAddRef and NonDelegatingRelease of that object.

2	Use MSDEV (though another debugger would probably do) and step through every reference count change, trying to pair them up.

3	Look at the call stack for each one.

Debugging Addressing and Memory Corruption Problems

Debugging memory addressing and corruption problems can be quite difficult. The ActiveMovie environment is not immune to those problems. Fortunately, there are tools which can help.

The debug heap manager supplied with Microsoft Visual C++ version 4.x can be quite useful when used to debug ActiveMovie code. Knowing the kinds of addresses which may be generated may help track down the source of a given problem. Using the Visual C++ debug heap manager may result in the following addresses being generated by buggy code:

Address 	Value

0xFDFDFDFD 	Illegal access before or after an allocated area.

0xDDDDDDDD 	Access to memory after it has been freed.

0xCDCDCDCD 	Uninitialized access within an allocated area.

Use the address values given in the above list to determine the class of bug to look for.

For more information, see the "Memory Management and the Debug Heap" section of the Visual C++ documentation.

Other debug heap managers may also be valuable for detecting memory corruption.


IAMCollection Interface

The filter graph manager exposes IAMCollection, which allows access to collections of objects such as those exporting IPinInfo and IFilterInfo interfaces.

When to Implement

This interface is implemented by the filter graph manager for use by OLE Automation client applications, such as Microsoft® Visual Basic®.

When to Use

Applications that use OLE Automation use this interface indirectly when retrieving collections of objects. For example, the IFilterInfo::get_Pins method retrieves an IAMCollection interface that can be used to access the IPinInfo interfaces corresponding to the pins on the filter.

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.

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

HRESULT get_Count(LONG *plCount);

Retrieves the number of items in the collection.

•	Returns an HRESULT value.

plCount

[out, retval] The number of items in the collection.


IAMCollection::get_NewEnum

HRESULT get_NewEnum(IUnknown **ppUnk);

Retrieves an enumerator object that implements IEnumVARIANT on this collection.

•	Returns an HRESULT value.

ppUnk

[out, retval] The IUnknown for an object that implements IEnumVARIANT on this collection.


IAMCollection::Item

HRESULT Item(long lItem, IUnknown **ppUnk);

Retrieves the indexed item from the collection.

•	Returns an HRESULT value.

lItem

[in] The index into the collection.

ppUnk

[out] The returned IUnknown interface for the contained item.

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.


IAMovieSetup Interface

The IAMovieSetup interface provides methods that allow objects in a dynamic-link library (DLL) to be self-registering. The IAMovieSetup interface works in conjunction with an overall registration architecture that OLE requires; this architecture is partially implemented in the ActiveMovie™ base classes. The remainder of the implementation is described in the following sections.

When to Implement

The two methods in this interface, IAMovieSetup::Register and IAMovieSetup::Unregister, are implemented by the CBaseFilter base class for self-registering filters. However, the implementation requires several steps that are outlined in this section.

To allow objects in a DLL to register themselves, two OLE-defined entry points must be provided in the DLL and exported:

•	DllRegisterServer

•	DllUnregisterServer

With these entry points in your DLL, you can use the regsvr32.exe tool to register and unregister your DLL or setup tools, or applications can register the filter programmatically.

To implement a self-registering filter, carry out the following steps:

1	Add DllRegisterServer and DllUnregisterServer to the export list in the DEF file of your filter.

2	Provide implementations for these functions that call the ActiveMovie AMovieRegisterServer and AMovieUnregisterServer functions, respectively. For example:

  HRESULT DllRegisterServer()

  {

    return AMovieRegisterServer(); //calls CBaseFilter::Register

  }

  HRESULT DllUnregisterServer()

  {

    return AMovieUnregisterServer(); //calls CBaseFilter::Unregister

  }

You can add additional code to these functions to set up custom registry entries. If you need nonstandard registration, override the CBaseFilter::Register and CBaseFilter::Unregister member functions.

3	In the CFactoryTemplate g_Templates array that instantiates your class, ensure that the first parameter has the name of the filter, for example, "Bouncing Ball."

  CFactoryTemplate gTemplates[]={

   L"Bouncing Ball", &CLSID_BouncingBall, CBouncingBall::CreateInstance}

  };

4	Tag the DLL file as self-registering by adding the string "OLESelfRegistering" to its resource.

5	Define the setup data structures for each filter by defining static data structures based on the AMOVIESETUP_MEDIATYPE, AMOVIESETUP_PIN, and AMOVIESETUP_FILTER structures.

For example, here are the structures for the BALL.AX sample filter:

   // setup data

  AMOVIESETUP_MEDIATYPE sudOpPinTypes =

  { &MEDIATYPE_Video

  , &MEDIASUBTYPE_NULL };

  AMOVIESETUP_PIN sudOpPin =

  { L"Output"

  , FALSE

  , TRUE

  , FALSE

  , FALSE

  , &CLSID_NULL

  , NULL

  , 1

  , &sudOpPinTypes };

  AMOVIESETUP_FILTER sudBallax =

  { &CLSID_BouncingBall

  , L"Bouncing Ball"

  , MERIT_UNLIKELY

  , 1

  , &sudOpPin };

6	Override the CBaseFilter::GetSetupData member function to return a pointer to your AMOVIESETUP_FILTER structure. Again, using the BALL.AX sample:

  // GetSetupData

  //

  LPAMOVIESETUP_FILTER CBouncingBall::GetSetupData()

  {

    return &sudBallax;

  }

Note that the IFilterMapper interface also provides methods to enable this functionality. This interface is implemented by the CBaseFilter class, which performs the required COM initialization overhead and then calls the IFilterMapper methods.

When to Use

Call implemented methods on this interface from an entry point on the filter that is called by a setup utility or installation utility. These are used automatically by the ActiveMovie architecture and normally should not need to be called by any other component.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns 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

HRESULT Register(void);

Adds the filter to the registry.

•	Returns an HRESULT value.

This method registers the filter, its pins, and the media type associated with the pins. It should be implemented to call IFilterMapper methods to accomplish this. See the CBaseFilter::Register member function for a description of its implementation.


IAMovieSetup::Unregister

HRESULT Unregister(void);

Removes the filter from the registry.

•	Returns an HRESULT value.

This method should be implemented to call the IFilterMapper::UnregisterFilter method to remove the filter from the registry. This effectively removes the pins and media types as well.


IAsyncReader Interface

The IAsyncReader interface allows multiple overlapped reads from different positions in the media stream. This interface is supported by source filters.

When to Implement

Implement this interface on a pin if your filter reads data of media type MEDIATYPE_Stream from some source.

When to Use

A parser, such as a QuickTime® parser filter, can use this interface to read from a filter that reads from a file, the network, or memory.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns 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

HRESULT BeginFlush(void);

Starts the flushing operation.

•	Returns an HRESULT value.

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

HRESULT EndFlush(void);

Completes the flushing operation.

•	Returns an HRESULT value.

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 IMemInputPin::Receive method again.


IAsyncReader::Length

HRESULT Length(LONGLONG* pTotal, LONGLONG* pAvailable);

Retrieves the total length of the stream, and the currently available length.

•	Returns an HRESULT value.

pTotal

Total allocated length.

pAvailable

Available length.

Read operations beyond the available length but within the total length will normally succeed, but they may block for a long period of time.


IAsyncReader::Request

HRESULT Request(IMediaSample* pSample, DWORD dwUser);

Queues a request for data.

•	Returns an HRESULT value.

pSample

Media sample being requested.

dwUser

[in] User context.

Media sample start and stop times contain the requested absolute byte position (start-inclusive and stop-exclusive). This method may 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 may fail IMediaSample::GetPointer until after returning from IAsyncReader::WaitForNext.

The stop position must be aligned, which means it may 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

HRESULT RequestAllocator(IMemAllocator* pPreferred,

    ALLOCATOR_PROPERTIES* pProps,

    IMemAllocator ** ppActual)

Retrieves the actual allocator to be used.

•	Returns an HRESULT value.

pPreferred

[in] Preferred allocator.

pProps

[in] Preferred allocator properties (size, count, and alignment).

ppActual

[out] Actual allocator used.

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

HRESULT SyncRead(LONGLONG llPosition,

    LONG lLength, BYTE* pBuffer);

Performs a synchronized read.

•	Returns an HRESULT value.

llPosition

[in] Absolute file position.

lLength

[in] Number of bytes required.

pBuffer

[out] Where the data is written.

The SyncRead method works in stopped state as well as in running state. The read is not necessarily aligned. This method fails if the read is beyond the actual total length.


IAsyncReader::SyncReadAligned

HRESULT SyncReadAligned(IMediaSample* pSample);

Performs a synchronized read of the data.

•	Returns an HRESULT value.

pSample

Sample to read.

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

HRESULT WaitForNext(DWORD dwTimeout,

    IMediaSample** ppSample, DWORD * pdwUser);

Blocks until the next sample is completed or the time-out occurs.

•	Returns an HRESULT value.

dwTimeout

[in] Time-out in milliseconds; may be zero or infinite.

ppSample

[out] Completed sample.

pdwUser

User context.

Samples may not be delivered 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 pwdUser parameter represents the information previously passed to IAsyncReader::Request. This is probably a pointer to the request packet from a higher level or a downstream filter that caused the application to make this request. This allows the application to retrieve this information and have some context in which to process it.


IBasicAudio Interface

IBasicAudio is an interface that 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 logarithmic steps. This follows the DirectSound model. 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.

When to Implement

The audio renderer filter supplied with Microsoft® ActiveMovie™ implements this interface. It is also implemented by the filter graph manager (via a plug-in distributor) to pass method calls from the application to the audio renderer filter's implementation of the interface.

Implement this interface if you are writing a replacement audio renderer filter or a replacement ActiveMovie plug-in distributor. You can use the CBasicAudio class, which handles the IDispatch implementation for OLE Automation, to help implement this interface.

When to Use

When this interface is exposed by the filter graph manager, it is used by applications that need to control the properties of the audio renderer filter. Applications should not use the interface exposed by the audio renderer directly. When this interface is exposed by the audio renderer filter, it is used by plug-in distributors, such as the ActiveMovie plug-in distributor, which pass calls from the application.

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.

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

HRESULT get_Balance(long * plBalance);

Retrieves the balance for the audio channel.

•	Returns an HRESULT value.

plBalance

[out] Returned value of the balance property.

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

HRESULT get_Volume(long * plVolume);

Retrieves the volume of the audio channel.

•	Returns an HRESULT value.

plVolume

[out] Returned value of the volume property. Divide by 100 to get equivalent decibel value (for example -10,000 = -100 dB).

The volume property is a value between -10,000 and 0, representing a set of logarithmic steps. Not all devices support 10,000 distinguishable steps.


IBasicAudio::put_Balance

HRESULT put_Balance(long lBalance);

Affects the balance of the audio channel.

•	Returns an HRESULT value.

lBalance

[in] Value to which to set the balance property.

The allowable input range is -10,000 to 10,000. Values outside this range return an error (VFW_E_INVALIDARG).

A value of 0 sets a neutral balance—both left and right speakers will be given the same amplitude audio signal.

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 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

HRESULT put_Volume(long lVolume);

Sets the volume of the audio channel.

•	Returns an HRESULT value.

lVolume

[in] Value to which to set the volume property.

The allowable input range is -10,000 to 0. Values outside this range return an error (VFW_E_INVALIDARG). 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).

Not all devices support 10,000 distinguishable steps.


IBasicVideo Interface

The IBasicVideo interface 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 IVideoWindow interface supports both properties and methods. Properties are more easily accessible from many OLE Automation controllers (such as the Microsoft® Visual Basic® programming system). However, some operations require several properties to be changed simultaneously; for this reason, methods are provided that allow a number of related properties to be changed.

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 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 may select a portion of the video to use. This portion is the source rectangle that the IBasicVideo interface controls. IBasicVideo allows the source rectangle to be set and retrieved. 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.

When to Implement

The video renderer filter supplied with Microsoft ActiveMovie™ implements this interface. It is also implemented by the filter graph manager (via a plug-in distributor) to pass method calls from the application to the video renderer filter's implementation of the interface. Implement this interface if you are writing a replacement video renderer filter or a replacement ActiveMovie plug-in distributor. You can use the CBaseBasicVideo class, which handles the IDispatch implementation for OLE Automation, to help implement this interface.

When to Use

When this interface is exposed by the filter graph manager, it is used by applications that need to control the properties of the video renderer filter.

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.

IBasicVideo methods 	Description

get_AvgTimePerFrame 	Retrieves the average time between successive frames in 100 nanosecond (ns) 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

HRESULT get_AvgTimePerFrame(REFTIME *pAvgTimePerFrame);

Retrieves the average time between successive frames in 100-nanosecond (ns) units.

•	Returns an HRESULT value.

pAvgTimePerFrame

[out] Time between frames.


IBasicVideo::get_BitErrorRate

HRESULT get_BitErrorRate(long *pBitErrorRate);

Retrieves a bit error rate for the video stream (one error for approximately this many bits).

•	Returns an HRESULT value.

pBitErrorRate

[out] Approximate bit error rate.


IBasicVideo::get_BitRate

HRESULT get_BitRate(long *pBitRate);

Retrieves an approximate bit rate for the video stream (in bits per second).

•	Returns an HRESULT value.

pBitRate

[out] Approximate bit rate.


IBasicVideo::get_DestinationHeight

HRESULT get_DestinationHeight(long *pDestinationHeight);

Retrieves the height of the destination rectangle.

•	Returns an HRESULT value.

pDestinationHeight

[out] The current height.


IBasicVideo::get_DestinationLeft

HRESULT get_DestinationLeft(long *pDestinationLeft);

Retrieves the destination x-axis origin coordinate.

•	Returns an HRESULT value.

pDestinationLeft

[out] The current x-axis origin.

Setting this coordinate does not affect the destination rectangle width.


IBasicVideo::get_DestinationTop

HRESULT get_DestinationTop(long *pDestinationTop);

Retrieves the destination y-axis origin coordinate.

•	Returns an HRESULT value.

pDestinationTop

[out] The current y-axis origin.

Setting this coordinate does not affect the destination rectangle height.


IBasicVideo::get_DestinationWidth

HRESULT get_DestinationWidth(long *pDestinationWidth);

Retrieves the width of the destination rectangle.

•	Returns an HRESULT value.

pDestinationWidth

[out] The current width.


IBasicVideo::get_SourceHeight

HRESULT get_SourceHeight(long *pSourceHeight);

Retrieves the height of the source rectangle.

•	Returns an HRESULT value.

pSourceHeight

[out] Current rectangle height.


IBasicVideo::get_SourceLeft

HRESULT get_SourceLeft(long *pSourceLeft);

Retrieves the source rectangle x-axis coordinate.

•	Returns an HRESULT value.

pSourceLeft

[out] The x-axis origin of the source rectangle.

This method has no effect on the source rectangle width.


IBasicVideo::get_SourceTop

HRESULT get_SourceTop(long * pSourceTop);

Retrieves the source rectangle y-axis origin coordinate.

•	Returns an HRESULT value.

pSourceTop

[out] The new top coordinate.

Setting this method has no effect on the source rectangle height.


IBasicVideo::get_SourceWidth

HRESULT get_SourceWidth(long *pSourceWidth);

Retrieves the source rectangle width.

•	Returns an HRESULT value.

pSourceWidth

[out] The current width.

This method has no effect on the source rectangle x-axis coordinate.


IBasicVideo::get_VideoHeight

HRESULT get_VideoHeight(long *pVideoHeight);

Retrieves the native height of the video.

•	Returns an HRESULT value.

pVideoHeight

[out] Native height of the video.

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 may be used by applications to negotiate size requirements with in-place OLE documents.


IBasicVideo::get_VideoWidth

HRESULT get_VideoWidth(long *pVideoWidth);

Retrieves the native width of the video.

•	Returns an HRESULT value.

pVideoWidth

[out] Native width of the video.

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 may be used by applications to negotiate size requirements with in-place OLE documents.


IBasicVideo::GetCurrentImage

HRESULT GetCurrentImage(long *pBufferSize,

    long *pDIBImage);

Retrieves the current image waiting at the renderer.

•	Returns an HRESULT value.

pBufferSize

[in, out] 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.

An application can use this method to get a copy of the current image the video renderer holds when paused. The size of the buffer required to hold the image can be obtained by calling the 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.

Pause the video renderer before calling this method. Calling this method in any other state than paused returns VFW_E_NOT_PAUSED. 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.

When called successfully, 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::GetDestinationPosition

HRESULT GetDestinationPosition(long *pLeft, long *pTop,

    long *pWidth, long *pHeight);

Retrieves the position of the destination rectangle in window coordinates.

•	Returns an HRESULT value.

pLeft

[out] The x-axis origin of the destination window.

pTop

[out] The y-axis origin of the destination window.

pWidth

[out] Width of the destination window.

pHeight

[out] Height of the destination window.

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::GetSourcePosition

HRESULT GetSourcePosition(long *pLeft, long *pTop,

    long *pWidth, long *pHeight);

Retrieves the source position that is clipped to the available video.

•	Returns an HRESULT value.

pLeft

[out] The x-axis origin of the source window.

pTop

[out] The y-axis origin of the source window.

pWidth

[out] Width of the source window.

pHeight

[out] Height of the source window.

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::GetVideoPaletteEntries

HRESULT GetVideoPaletteEntries(long StartIndex,

    long Entries, long *pRetrieved, long *pPalette);

Retrieves the palette colors for the video.

•	Returns an HRESULT value.

StartIndex

[in] Start index for the palette.

Entries

[in] Number of palette entries required.

pRetrieved

[out] Number of entries actually returned.

pPalette

[out] Pointer to an array of Microsoft Win32 PALETTEENTRY structures.

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 currently 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

HRESULT GetVideoSize(long *pWidth, long *pHeight);

Retrieves the native video dimensions.

•	Returns an HRESULT value.

pWidth

[out] Width of the video window.

pHeight

[out] Height of the video window.

This method retrieves the native video width and height, disregarding any source rectangle that may have been set. ActiveX™ controls or other applications may use this information to negotiate space in compound documents.


IBasicVideo::IsUsingDefaultDestination

HRESULT IsUsingDefaultDestination();

Determines if the renderer is using the default destination rectangle.

•	Returns an HRESULT value. Returns OATRUE if currently using the default destination; otherwise, returns OAFALSE.

The IBasicVideo::SetDefaultDestinationPosition method can be used to inform the filter to use the default settings for the destination rectangle. This method returns whether or not they are being used.


IBasicVideo::IsUsingDefaultSource

HRESULT IsUsingDefaultSource();

Determines if the renderer is using the default source rectangle.

•	Returns an HRESULT value. Returns OATRUE if currently using the default destination; otherwise, returns OAFALSE.

The IBasicVideo::SetDefaultSourcePosition method can be used to inform the filter to use the default settings for the source rectangle. This method returns whether or not they are being used.


IBasicVideo::put_DestinationHeight

HRESULT put_DestinationHeight(long DestinationHeight);

Sets the height of the destination rectangle.

•	Returns an HRESULT value.

DestinationHeight

[in] The new height.

Setting this coordinate does not affect the destination rectangle y-axis origin.


IBasicVideo::put_DestinationLeft

HRESULT put_DestinationLeft(long DestinationLeft);

Sets the destination x-axis origin coordinate.

•	Returns an HRESULT value.

DestinationLeft

[in] The new x-axis origin.

Setting this coordinate does not affect the destination rectangle width.


IBasicVideo::put_DestinationTop

HRESULT put_DestinationTop(long DestinationTop);

Sets the destination y-axis origin coordinate.

•	Returns an HRESULT value.

DestinationTop

[in] The new y-axis origin.


IBasicVideo::put_DestinationWidth

HRESULT put_DestinationWidth(long DestinationWidth);

Sets the width of the destination rectangle.

•	Returns an HRESULT value.

DestinationWidth

[in] The new width.

Setting this coordinate does not affect the destination rectangle x-axis origin.


IBasicVideo::put_SourceHeight

HRESULT put_SourceHeight(long SourceHeight);

Sets the height of the source rectangle.

•	Returns an HRESULT value.

SourceHeight

[in] New rectangle height.

Setting the height of the source rectangle has no effect on the source y-axis coordinate.


IBasicVideo::put_SourceLeft

HRESULT put_SourceLeft(long SourceLeft);

Sets the source rectangle x-axis coordinate.

•	Returns an HRESULT value.

SourceLeft

[in] The x-axis origin of the source rectangle.

Setting this method has no effect on the source rectangle width.


IBasicVideo::put_SourceTop

HRESULT put_SourceTop(long SourceTop);

Sets the source rectangle y-axis origin coordinate.

•	Returns an HRESULT value.

SourceTop

[in] The new top coordinate.

Setting this method has no effect on the source rectangle height.


IBasicVideo::put_SourceWidth

HRESULT put_SourceWidth(long SourceWidth);

Sets the source rectangle width.

•	Returns an HRESULT value.

SourceWidth

[in] The new width of the source rectangle.

Setting this method has no effect on the source rectangle x-axis coordinate.


IBasicVideo::SetDefaultDestinationPosition

HRESULT SetDefaultDestinationPosition();

Sets the default destination position of the video window so that the renderer uses the entire window for playback.

•	Returns an HRESULT value.


IBasicVideo::SetDefaultSourcePosition

HRESULT SetDefaultSourcePosition();

Informs the renderer to use the default source rectangle.

•	Returns an HRESULT value.


IBasicVideo::SetDestinationPosition

HRESULT SetDestinationPosition(long Left, long Top,

    long Width, long Height);

Sets the destination rectangle in window coordinates.

•	Returns an HRESULT value.

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.

Height

[in] Height of the destination window.

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

HRESULT SetSourcePosition(long Left, long Top,

    long Width, long Height);

Sets the source rectangle and is clipped against the available video.

•	Returns an HRESULT value.

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.

Height

[in] Height of the source window.

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.


IDeferredCommand Interface

The deferred command mechanism allows filters themselves to handle deferred commands. Where they do not, the filter graph manager queues the command until the requested time and then calls the method on the filter (this would result in coarse rather than accurate synchronization). Note that a filter that does handle deferred commands must make them apply to data appearing at that time. Thus a contrast filter asked to change the contrast at time x must ensure that it applies the change when processing data time-stamped to be rendered at time x; these samples will be processed by the filter somewhat before time x.

The IQueueCommand interface provides two methods, InvokeAtStreamTime, which queues commands at stream time, and InvokeAtPresentationTime, which queues commands at presentation time. Both return an IDeferredCommand interface to the queued command, by which the application can cancel the command, set a new presentation time for it, or get back an estimate of the likelihood of the filter graph manager being able to execute the command on time (implementation of this last method is likely to be highly simplistic in the first release of Microsoft® ActiveMovie™).

Both the queue and the application will hold a reference count on the object (represented to the application by the IDeferredCommand interface), and the object will not be destroyed until both are released. Similarly, calling Release on the IDeferredCommand interface is not sufficient to cancel the command because the queue also holds a reference count.

When to Implement

This method is implemented by the filter graph manager to allow deferred processing of commands. It is implemented via a plug-in distributor to pass deferred commands from the application to the renderer. You can use the CDeferredCommand class to help implement this interface if you are implementing your own plug-in distributor.

When to Use

Applications may use this interface to cancel, postpone, get return values from, or determine a confidence level for commands that have been queued for deferred execution by using the IQueueCommand interface.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IDeferredCommand methods 	Description

Cancel 	Cancels a previously queued IQueueCommand::InvokeAtStreamTime or IQueueCommand::InvokeAtPresentationTime request.

Confidence 	Returns a confidence value that describes the probability of the deferred command being executed on time.

Postpone 	Specifies a new invocation time for a previously queued command.

GetHResult 	Returns the HRESULT value from the invoked command.


IDeferredCommand::Cancel

HRESULT Cancel();

Cancels a previously queued IQueueCommand::InvokeAtStreamTime or IQueueCommand::InvokeAtPresentationTime request.

•	Returns an HRESULT value.


IDeferredCommand::Confidence

HRESULT Confidence(LONG *pConfidence);

Retrieves a confidence value on a scale of 0 to 100 that describes the probability that the deferred command will be executed on time.

•	Returns an HRESULT value.

pConfidence

The confidence level.

Higher confidence values indicate a greater probability of timely execution. For example, a command queued at a presentation time that has already passed will return a value of 0. A value of 100 would indicate, with absolute certainty, that the command can be executed on time. Commands that are not directly supported by the filter but are queued by the filter graph manager will return a lower confidence value than commands queued directly by the filters that execute them. Commands that are queued with times too close to other commands are likely to return lower confidence values. The initial implementation of this method relies mostly on the reporting of the individual filter commands rather than an attempt to estimate resource availability on a filter graph-wide basis.


IDeferredCommand::GetHResult

HRESULT GetHResult(HRESULT* phrResult)

Returns the HRESULT return value from the invoked command.

phrResult

The HRESULT value.


IDeferredCommand::Postpone

HRESULT Postpone(REFTIME newtime);

Specifies a new presentation time for a previously queued command.

•	Return value is S_OK if completed. Also, if completed, the phrResult parameter is set to the result of the deferred command.

newtime

The new presentation time.


IDirectDrawVideo Interface

This interface is on the video renderer and provides information about DirectDraw™ with respect to its use by the renderer. For example, the interface allows an application to get details of the surface and any hardware capabilities that are available. It also allows the application to adjust the surfaces that the renderer should use and even to set the DirectDraw instance. There is some duplication in this interface with the IDirectDraw interface; however, this interface allows simple access to that information without calling the DirectDraw provider directly.

DirectDraw is not loaded by the renderer until it is connected, and likewise it is unloaded only when disconnected. When the renderer has allocated the DirectDraw surfaces it will be using 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, it 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 used by the renderer are primary surfaces.

When to Implement

This interface is implemented by the Microsoft® ActiveMovie™ video renderer to provide information about DirectDraw surfaces and hardware capabilities.

When to Use

Applications can use this interface to get details of the surface and any hardware capabilities that are available, adjust the surfaces that the renderer should use, and set the IDirectDraw instance. Applications are allowed to set the IDirectDraw instance because DirectDraw can be opened only once per process; this helps to resolve conflicts.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns 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 being used.

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 ActiveMovie might change display mode when going to full-screen mode.

WillUseFullScreen 	Determines whether ActiveMovie will change display mode when going to full-screen mode.


IDirectDrawVideo::CanUseOverlayStretch

HRESULT CanUseOverlayStretch(long * UseOverlayStretch);

Determines whether the renderer will check overlay restrictions.

•	Returns an HRESULT value.

UseOverlayStretch

Set to OATRUE if the renderer can use overlay stretching; otherwise, set to OAFALSE.

For a description of overlay stretching, see IDirectDrawVideo::UseOverlayStretch.


IDirectDrawVideo::CanUseScanLine

HRESULT CanUseScanLine(long * UseScanLine);

Determines whether the renderer will check the current scan line when drawing.

•	Returns an HRESULT value.

UseScanLine

Set to OATRUE if the renderer can use scan line information; otherwise, set to OAFALSE.

For a description of the use of scan line detection in the ActiveMovie video renderer, see IDirectDrawVideo::UseScanLine.


IDirectDrawVideo::GetCaps

HRESULT GetCaps(DDCAPS *pCaps);

Retrieves a DirectDraw-defined DDCAPS structure containing the hardware capabilities.

•	Returns an HRESULT value.

pCaps

DDCAPS structure containing the hardware capabilities.

If DirectDraw has not been loaded by the renderer, this method returns E_FAIL. DirectDraw is not loaded by the renderer until it is connected, and likewise is unloaded only when the renderer is disconnected.


IDirectDrawVideo::GetDirectDraw

HRESULT GetDirectDraw(LPDIRECTDRAW *ppDirectDraw);

Retrieves the IDirectDraw interface.

•	Returns an HRESULT value.

ppDirectDraw

IDirectDraw interface.

If an application wants to load DirectDraw but allow the renderer to also allocate surfaces, it may 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

HRESULT GetEmulatedCaps(DDCAPS *pCaps);

Retrieves a DirectDraw-defined DDCAPS structure containing the emulated capabilities.

•	Returns an HRESULT value.

pCaps

DDCAPS structure containing the emulated capabilities.

If DirectDraw has not been loaded by the renderer, this method returns E_FAIL. DirectDraw is not loaded by the renderer until it is connected, and likewise is unloaded only when disconnected.


IDirectDrawVideo::GetFourCCCodes

HRESULT GetFourCCCodes(DWORD *pCount, DWORD *pCodes);

Retrieves the multimedia format type.

•	Returns an HRESULT value.

pCount

Number of FOURCC codes in the pCodes array.

pCodes

Array of DWORD media tags formerly used for Microsoft multimedia types.

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 four-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 DWORDs for this many FOURCC codes and call the method again with the array pointer in pCodes.


IDirectDrawVideo::GetSurfaceDesc

HRESULT GetSurfaceDesc(DDSURFACEDESC *pSurfaceDesc);

Retrieves a DDSURFACEDESC structure describing the current DirectDraw surface.

•	Returns an HRESULT value.

pSurfaceDesc

DDSURFACEDESC structure describing the current DirectDraw surface.

If no surface has been allocated, this method will return E_FAIL. If a DCI primary surface is being used, the DDSURFACEDESC structure will not be filled in and the call will return S_FALSE. Surfaces are allocated only when the renderer is paused. Once the renderer has been paused, it may not release the surfaces when stopped.


IDirectDrawVideo::GetSurfaceType

HRESULT GetSurfaceType(DWORD *pSurfaceType);

Retrieves the actual surface type as an ActiveMovie DirectDraw Surface (AMDDS) definition.

•	Returns an HRESULT value.

pSurfaceType

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 AMDDS_ALL 	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).

It is not always easy to discover what kind of surface is actually being used by looking at a DDSURFACEDESC structure. Therefore, an application can call GetSurfaceType to retrieve the actual surface type. The field will be filled in with one bit setting selected from the list of AMDDS definitions shown here.


IDirectDrawVideo::GetSwitches

HRESULT GetSwitches(DWORD *pSwitches);

Retrieves the surface types that the renderer is allowed to use.

•	Returns an HRESULT value.

pSwitches

Bit mask containing one or more of the following ActiveMovie 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 AMDDS_ALL 	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).


IDirectDrawVideo::SetDefault

HRESULT SetDefault();

Makes the current property settings the global default.

•	Returns an HRESULT value.

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 ActiveMovie instances of this interface. Once called, the current property settings will persist between the subsequent starting of other ActiveMovie filter graphs and between any machine reboots.


IDirectDrawVideo::SetDirectDraw

HRESULT SetDirectDraw(LPDIRECTDRAW pDirectDraw);

Passes the IDirectDraw interface to a loaded driver.

•	Returns an HRESULT value.

pDirectDraw

IDirectDraw interface to be passed.

To have the renderer release a DirectDraw interface previously passed in through SetDirectDraw, an application can call SetDirectDraw, passing 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. The renderer only initializes itself to use DirectDraw when it is connected, so calling SetDirectDraw after connection will not cause the renderer to use the interface until subsequently reconnected.

This method was created because only one instance of IDirectDraw could be loaded per process in DirectDraw 1.0. If an application wanted to load IDirectDraw but allow the 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 ActiveMovie ships with DirectDraw 2.0, however, this method is not required.


IDirectDrawVideo::SetSwitches

HRESULT SetSwitches(DWORD pSwitches);

Sets the surface types that the renderer is allowed to use.

•	Returns an HRESULT value.

pSwitches

Bit mask containing one or more of the following ActiveMovie 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 AMDDS_ALL 	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).


IDirectDrawVideo::UseOverlayStretch

HRESULT UseOverlayStretch(long UseOverlayStretch);

Determines whether the renderer should check overlay stretch limitations.

•	Returns an HRESULT value.

UseOverlayStretch

Set to OATRUE for the renderer to use overlay stretching; otherwise, set to OAFALSE.

Some display cards provide the use of overlay surfaces through DirectDraw. An overlay surface is a block of video memory whose contents are overlayed onto the display during the monitor's vertical refresh. ActiveMovie 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 On (the default), ActiveMovie will make sure the overlay is adequately stretched before displaying it. If it is set to Off, ActiveMovie 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

HRESULT UseScanLine(long UseScanLine);

Determines whether the renderer should check the current scan line when drawing a video.

•	Returns an HRESULT value.

UseScanLine

Set to OATRUE for the renderer to use scan line information; otherwise, set to OAFALSE.

Some display cards provide, through DirectDraw, special blocks of memory that the display hardware can blt directly (rather than drawing through GDI). These are called "offscreen plain surfaces." Some hardware can also return the current scan line during a vertical refresh. By default, ActiveMovie uses the scan line information, if available, and waits until the scan line is outside the video being displayed before issuing the DirectDraw call to blt the image to the primary (screen) surface from an off-screen plain surface. By doing this, ActiveMovie reduces the amount of video "tearing" experienced by the user.

The effort to reduce tearing must be balanced, however, with time spent waiting for the current scan line to move down the display, which in some cases can result in approximately 10 percent less frame throughput. The UseScanLine parameter can be set to Off to improve throughput at the expense of video quality. It is set to On by default to maximize the quality of the presentation by checking the scan line, if available.


IDirectDrawVideo::UseWhenFullScreen

HRESULT UseWhenFullScreen(long UseWhenFullScreen);

Determines whether ActiveMovie might change display mode when going to full-screen mode.

•	Returns an HRESULT value.

UseWhenFullScreen

Set to OATRUE to cause the renderer to use DirectX in full-screen mode; otherwise, set to OAFALSE.

When asked to go to full-screen mode, ActiveMovie 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 x 768 pixels, a video may look relatively small, but when displayed in a 320 x 240 display mode it may 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

HRESULT WillUseFullScreen(long * UseWhenFullScreen);

Determines whether ActiveMovie will change display mode when going to full-screen mode.

•	Returns an HRESULT value.

UseWhenFullScreen

Set to OATRUE if ActiveMovie is set to use DirectX in full-screen mode; otherwise, set to OAFALSE.

For a description of this feature, see IDirectDrawVideo::UseWhenFullScreen.


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.

When to Implement

Implement this interface when writing a plug-in distributor (PID) that plugs in to the filter graph manager if you want the PID to receive notifications of control and changes in the composition of filter graphs.

When to Use

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 IFilter 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 	Returns 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

HRESULT NotifyGraphChange(void);

Called when the set of filters in the filter graph change or their connections change.

•	Returns an HRESULT value.

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 call Release on any held filters that have been removed at this point. For performance reasons, PIDs may choose not to rescan the filters until the PIDs actually need the interfaces because there may be several separate notifications sent. However, it is important to release any cached interfaces immediately.


IDistributorNotify::Pause

HRESULT Pause(void);

Called when the filter graph is entering a paused state.

•	Returns S_OK if the transition is complete; otherwise, returns one of the following values.

Value 	Meaning

Error value 	Transition failed.

S_FALSE 	Transition is not complete, but no error has occurred.

This method is called before the filters are notified.


IDistributorNotify::Run

HRESULT Run(REFERENCE_TIME tStart);

Called when the filter graph is entering a running state.

•	Returns an HRESULT value.

tStart

Stream-time offset that will be passed to every filter's IFilter::Run parameter.

This method is called before the filters are notified.


IDistributorNotify::SetSyncSource

HRESULT SetSyncSource(IReferenceClock * pClock);

Called when a new clock is registered.

•	Returns an HRESULT value.

pClock

[in] Pointer to the IReferenceClock interface.

This method is called before the filters are notified. Make sure to call AddRef on the pClock parameter if the plug-in distributor intends to hold it beyond this method call.


IDistributorNotify::Stop

HRESULT Stop(void);

Called when the filter graph is entering a stopped state.

•	Returns S_OK if the transition is complete; otherwise, returns one of the following values.

Value 	Meaning

Error value 	Transition failed.

S_FALSE 	Transition is not complete, but no error has occurred.

This method is called before the filters are notified.


IEnumFilters Interface

The IFilterGraph::EnumFilters method returns the enumerator interface. It is based on the OLE IEnum style of enumerators.

When to Implement

This interface is implemented on the filter graph manager and is not intended for implementation by developers.

When to Use

This interface is used by applications or other filters to determine what filters exist in 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.

IEnumFilters methods 	Description

Next 	Retrieves the specified number of filters in the enumeration sequence.

Skip 	Skips a specified number of filters in the enumeration sequence.

Reset 	Resets the enumeration sequence to the beginning.

Clone 	Returns a duplicate enumerator containing the same enumeration state as the current one.


IEnumFilters::Clone

HRESULT Clone(IEnumFilters ** ppEnum);

Returns a duplicate enumerator containing the same enumeration state as the current one.

ppEnum

[out] Duplicate of the enumerator.

This method produces two enumerators (the original and the duplicate); both are set at the same filter. After they are created, however, they are independent; therefore, calling the IEnumFilters::Next method for one does not affect the other.


IEnumFilters::Next

HRESULT Next(ULONG cFilters, IFilter ** ppFilter,

    ULONG * pcFetched);

Retrieves the specified number of filters in the enumeration sequence.

•	Returns an HRESULT value.

cFilters

[in] Number of filters to place.

ppFilter

[out] Array in which to place IFilter pointers.

pcFetched

[out] Actual number of filters placed in the array.

The interface returned by this method has had its reference count incremented. Be sure to call IUnknown::Release on the interface to decrement the reference count when you have finished using the interface.


IEnumFilters::Reset

HRESULT Reset(void);

Resets the enumeration sequence to the beginning.

•	Returns an HRESULT value.

This method affects the return value of the next call to the IEnumFilters::Next method.


IEnumFilters::Skip

HRESULT Skip(ULONG cFilter);

Skips a specified number of filters in the enumeration sequence.

cFilter

[in] Number of filters to skip.

This method affects the return value of the next call to the IEnumFilters::Next method.


IEnumMediaTypes Interface

The IEnumMediaTypes interface enumerates the preferred formats for a pin.

When to Implement

This interface must be implemented and made available by the IPin::EnumMediaTypes method. The CBasePin::EnumMediaTypes member function automatically does this in the ActiveMovie™ class library and uses the CEnumMediaTypes class to create the enumerator object.

When to Use

This interface is normally used by a connecting pin to determine the media type when negotiating a connection. It may also be passed through to other pins either upstream or downstream of the filter when intervening filters do not have a list of preferred media types. For example, a transform-inplace filter may pass the IEnumMediaTypes interface of a downstream input pin to the connecting output pin of the upstream filter instead of providing its own IEnumMediaTypes interface.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IEnumMediaTypes methods 	Description

Next 	Retrieves the specified number of items in the enumeration sequence.

Skip 	Skips a specified number of elements in the enumeration sequence.

Reset 	Resets the enumeration sequence to the beginning.

Clone 	Returns another enumerator containing the same enumeration state as the current one.


IEnumMediaTypes::Clone

HRESULT Clone(IEnumMediaTypes ** ppEnum);

Returns another enumerator containing the same enumeration state as the current one.

•	Returns an HRESULT value.

ppEnum

[out] New copy of the enumerator.


IEnumMediaTypes::Next

HRESULT Next(ULONG cMediaTypes,

    AM_MEDIA_TYPE ** ppMediaTypes, ULONG * pcFetched);

Retrieves the specified number of items in the enumeration sequence.

•	Returns an HRESULT value.

cMediaTypes

[in] Number of media types to place.

ppMediaTypes

[out] Array in which to place the pointers to the next media type.

pcFetched

[out] Actual count passed.

To call this method, pass an array of pointers to media types. (If you want only a single media type, you can pass a pointer to a media type pointer in place of an array of media type pointers.) The interface allocates the necessary AM_MEDIA_TYPE structures and initializes them with the variable format block. Free each media type by calling DeleteMediaType, which will free the format block and the media type itself.


IEnumMediaTypes::Reset

HRESULT Reset(void);

Resets the enumerator to the beginning so that the next call to the IEnumMediaTypes::Next method returns, at a minimum, the first media type (if any) in the enumeration.

•	Returns S_OK if successful; otherwise, returns S_FALSE.


IEnumMediaTypes::Skip

HRESULT Skip(ULONG cMediaTypes);

Skips a specified number of elements in the enumeration sequence.

•	Returns an HRESULT value.

cMediaTypes

[in] Number of media type elements to skip.


IEnumPins Interface

The IFilter::EnumPins method returns this interface. It is based on the IEnumX protocol of the Component Object Model (COM).

Note that actions that cause the number of pins to change may cause the enumerator to fail.

When to Implement

This interface must be implemented and made available by the IFilter::EnumPins method. The CBaseFilter::EnumPins member function automatically does this in the ActiveMovie™ class library and uses the CEnumPins class to create the enumerator object.

When to Use

This interface is normally used by the filter graph manager when connecting filters. It can, however, be used by an application that needs to find the pins associated with filters in the filter graph—for example, to add another filter to the graph.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IEnumPins methods 	Description

Next 	Puts pointers to IPin interfaces for the next pins into the specified array.

Skip 	Skips the specified number of pins.

Reset 	Resets the position to the beginning so that the next call to the IEnumPins::Next method returns, at a minimum, the first pin of the filter.

Clone 	Provides another enumerator, which is a duplicate of the current one.


IEnumPins::Clone

HRESULT Clone(IEnumPins ** ppEnum);

Makes a copy of the enumerator. This allows the calling application to retain two positions in the list of pins.

•	Returns an HRESULT value.

ppEnum

[out] New enumerator, which is a copy of this enumerator.


IEnumPins::Next

HRESULT Next(ULONG cPins, IPin ** ppPins,

    ULONG * pcFetched);

Places pointers to IPin interfaces into the specified array.

•	Returns an HRESULT value.

cPins

[in] Number of pins to place.

ppPins

[out] Array in which to place the interface pointers.

pcFetched

[out] Actual number of pins placed in the array.

The interface returned by this method has had its reference count incremented. Be sure to call IUnknown::Release on the interface to decrement the reference count when you have finished using the interface.


IEnumPins::Reset

HRESULT Reset(void);

Resets the enumerator to the beginning so that the next call to the IEnumPins::Next method returns, at a minimum, the first pin of the filter.

•	Returns an HRESULT value.


IEnumPins::Skip

HRESULT Skip(ULONG cPins);

Skips the next specified number of pins.

•	Returns an HRESULT value.

cPins

[in] Number of pins to skip.

This method affects the next call to the IEnumPins::Next method.


IEnumRegFilters Interface

The purpose of the mapper is to help the filter graph manager avoid loading filters when attempting to build a filter graph to render a given media type. By looking at filter properties recorded in the registry, the number of filters that must be loaded and tried can be reduced.

The IFilterMapper::EnumMatchingFilters method returns the enumerator that enumerates the filters that match specific requirements. The enumerator returns descriptors of filters, including the globally unique identifiers (GUIDs) that the Microsoft® Win32® CoCreateInstance function can instantiate. The filters are not loaded. The IEnumRegFilters interface is a Component Object Model (COM) enumerator.

When to Implement

This interface is implemented by the filter mapper and need not be implemented elsewhere.

When to Use

Although the filter graph manager is the primary user of this interface, applications can also use it to determine available filters in the system—for example, to construct a unique filter graph by adding and connecting filters itself, or to allow users to choose from a list of available filters.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns 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 	Skips a specified number of elements in the enumeration sequence.

Reset 	Makes the Next method start again, beginning at the first filter.

Clone 	Returns another enumerator containing the same enumeration state as the current one.


IEnumRegFilters::Clone

HRESULT Clone(IEnumRegFilters **ppEnum);

Creates another enumerator with the same enumeration state as the current one.

•	Returns an HRESULT value. Currently returns E_NOTIMPL.

ppEnum

[out] Pointer to the duplicate enumerator interface.

Currently, this method is not implemented.


IEnumRegFilters::Next

HRESULT Next(ULONG cFilters,

    REGFILTER ** apRegFilter, ULONG * pcFetched);

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.

•	Returns an HRESULT value.

cFilters

[in] Number of filters.

apRegFilter

[out] Pointer to an array of REGFILTER pointers.

pcFetched

[out] Actual number of filters passed.

The calling application must use the Microsoft Win32 CoTaskMemFree function to free each REGFILTER pointer returned in the array.


IEnumRegFilters::Reset

HRESULT Reset(void);

Resets the enumerator so that the next call to the IEnumRegFilters::Next method begins again at the first filter, if any.

•	Returns an HRESULT value.


IEnumRegFilters::Skip

HRESULT Skip(ULONG celt);

Skips a specified number of items in the enumeration sequence.

•	Returns an HRESULT value. Currently returns E_NOTIMPL.

celt

[in] Number of items to skip.

Currently, this method is not implemented.


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 will want to allow the user to enter the name of the file to be written to. This interface enables the communication of this information.

When to Implement

If a filter needs the name of a file to open, it should expose this interface to allow a user to set the file name. Note that there is currently no class available to implement this.

When to Use

Any application that needs to 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 	Returns 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 are to be written.

GetCurFile 	Retrieves the file name of the current sink file.


IFileSinkFilter::GetCurFile

HRESULT GetCurFile(LPOLESTR *ppszFileName,

    AM_MEDIA_TYPE *pmt);

Retrieves the file name of the current sink file.

•	Returns an HRESULT value.

ppszFileName

[out] Name of the file set to receive media samples.

pmt

Type of media samples to be written to the file.

If a file name is not assigned, this method returns E_FAIL.


IFileSinkFilter::SetFileName

HRESULT SetFileName(LPCOLESTR pszFileName,

    const AM_MEDIA_TYPE *pmt);

Sets the name of the file into which media samples are to be written.

•	Returns an HRESULT value.

pszFileName

[in] Name of the file to receive the media samples.

pmt

[in] Type of media samples to be written to the file and the media type of the sink filter's input pin.

If the pszFileName parameter names a non-existent file, the file will be created. If it names an existing file, the sink filter will overwrite the file without first deleting it.


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 OLE IPersistFile interface. If the file has a type that can be determined by the algorithm described in the topic Registering a Custom File Type, the recommended file source filter CLSID is used when the filter graph manager attempts to render the filter graph.

When to Implement

If a filter needs the name of a file to open, it should expose this interface to allow a user to set the file name. Note that there is no class available to implement this.

When to Use

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 GraphEdit 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

HRESULT GetCurfile(LPOLESTR *ppszFileName,

    AM_MEDIA_TYPE *pmt);

Collects information about the file to open.

•	Returns an HRESULT value.

ppszFileName

[out] Path to the loaded file.

pmt

[out] Media type.


IFileSourceFilter::Load

HRESULT Load(LPCOLESTR pszFileName,

    const AM_MEDIA_TYPE *pmt);

Loads a media file.

•	Returns an HRESULT value.

pszFileName

[in] Absolute path of the file to open.

pmt

[in] Media type of the file. This can be NULL.

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.

Note that 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.


IFilter Interface

The IFilter interface abstracts an object that has typed input and output connections and can be aggregated dynamically. All ActiveMovie™ filters expose this interface.

Since the IFilter interface derives from the IMediaFilter interface, it inherits IPersist.

When to Implement

Implement this interface on every ActiveMovie filter. It is recommended that you use the CBaseFilter class library to implement this interface.

When to Use

The filter graph manager is the primary user of this interface. Applications or other filters may use IFilter methods directly to enumerate or retrieve pins or to get vendor information but should not call any methods derived from IMediaFilter to control media streaming (use the IMediaControl methods on the filter graph manager instead).

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 	Informs the filter to transition to the new (stopped) state.

Pause 	Informs the filter to transition to the new (paused) state.

Run 	Informs the filter to transition to the new (running) state.

GetState 	Determines the state of the filter.

SetSyncSource 	Identifies the reference clock to which the filter should synchronize activity.

GetSyncSource 	Retrieves the current reference clock (or NULL if there is no clock). Passes a time value to synchronize independent streams.

IFilter methods 	Description

EnumPins 	Enumerates the specified pins available on this filter.

FindPin 	Retrieves a pointer to the pin with the specified identifier.

QueryFilterInfo 	Retrieves information about the specified filter.

JoinFilterGraph 	Notifies a filter that it has joined a filter graph.

QueryVendorInfo 	Retrieves optional information supplied by a vendor for the specified filter.


IFilter::EnumPins

HRESULT EnumPins(IEnumPins ** ppEnum);

Enumerates all the pins available on this filter.

•	Returns an HRESULT value.

ppEnum

[out] Pointer to the IEnumPins interface to retrieve.

The interface returned by this method has had its reference count incremented. Be sure to call IUnknown::Release on the interface to decrement the reference count when you have finished using the interface.


IFilter::FindPin

HRESULT FindPin(LPCWSTR Id, IPin **ppPin);

Retrieves the pin with the specified identifier.

•	Returns an HRESULT value.

Id

[in] Identifier of the pin.

ppPin

[out] Pointer to the IPin interface for this pin after the filter has been restored. The returned IPin pointer has been reference counted. The caller should call the Release method on the pointer when finished with it.

This method, along with the IPin::QueryId method, is used to implement persistent filter graphs. A filter must be able to translate the IPin interface pointers to its pins into identifiers that can be saved along with the configuration of the filter graph. It does this by using the IPin::QueryId method. It must then be able to convert those identifiers back into IPin interface pointers when the filter and its connections are restored as part of a persistent filter graph. This is accomplished by using the IFilter::FindPin method.

The ppPin parameter is set to NULL if the identifier cannot be matched.


IFilter::JoinFilterGraph

HRESULT JoinFilterGraph(IFilterGraph * pGraph,

    LPCWSTR pName);

Notifies a filter that it has joined a filter graph.

•	Returns an HRESULT value.

pGraph

[in] Pointer to the filter graph to join.

pName

[in, string] Name of the filter being added.

The filter should store this interface for later use because it may need to notify the interface about events. The filter should not add a reference count to this interface. Doing so causes circular references and prevents the graph or the filter from ever being correctly released. The filter graph manager does hold a reference on the filter. The filter does not need to hold a reference to ensure that the interface does not disappear; it is notified of any such disappearance by a further call to IFilter::JoinFilterGraph with a NULL value for the pGraph parameter to indicate that the filter is no longer part of the graph.


IFilter::QueryFilterInfo

HRESULT QueryFilterInfo(FILTER_INFO * pInfo);

Returns information about the filter.

•	Returns an HRESULT value.

pInfo

[out] Pointer to a FILTER_INFO structure.

The FILTER_INFO structure is defined as follows:

typedef struct _FilterInfo  {

    [string] WCHAR achName[MAX_FILTER_NAME]; // allowed to be null

    IFilterGraph * pGraph;                   // null if not part of graph

    } FILTER_INFO ;

Note that on return, if the pGraph member of the FILTER_INFO structure is non-null, it will have an outstanding reference count and should be released when the interface is no longer needed.


IFilter::QueryVendorInfo

HRESULT QueryVendorInfo(LPWSTR * pVendorInfo);

Returns a vendor information string.

•	Returns an HRESULT value.

pVendorInfo

[out] Pointer to a string containing vendor information.

This method is optional and can return E_NOTIMPL. If implemented, memory returned should be freed using the Microsoft® Win32® CoTaskMemFree function when the application is done using it.


IFilterGraph Interface

The IFilterGraph interface is an abstraction representing a graph of filters. All filters in the graph share the same clock. They may or may not also be connected and stream data between them. This interface allows filters to be joined into a graph and operated as a unit. Unlike the IGraphBuilder interface, this interface does not use heuristics to connect and build the filter graph.

When to Implement

This interface is implemented on the filter graph manager and is not intended for implementation by developers.

When to Use

Applications should not use this interface directly but instead should use the IGraphBuilder interface, which inherits 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.

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 the two IPin objects directly (without intervening filters).

Reconnect 	Breaks the existing pin connection and reconnects it to the same pin.

Disconnect 	Disconnects this pin, if connected.

SetDefaultSyncSource 	Sets the default synchronization source (a clock).


IFilterGraph::AddFilter

HRESULT AddFilter(IFilter * pFilter, LPCWSTR pName);

Adds a filter to the graph and names it by using the pName parameter.

•	Returns an HRESULT value.

pFilter

[in] Filter to add to the graph.

pName

[in] Name of the filter.

The name of the filter may 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 IFilter::JoinFilterGraph method to inform the filter that it has been added. AddFilter must be called before attempting to call the IGraphBuilder::Connect, IFilterGraph::ConnectDirect, or IGraphBuilder::Render method to connect or render pins belonging to the added filter.


IFilterGraph::ConnectDirect

HRESULT ConnectDirect(IPin * ppinOut, IPin * ppinIn,

    const AM_MEDIA_TYPE * pmt);

Connects the two pins directly (without intervening filters).

•	Returns an HRESULT value.

ppinOut

[in] Output pin.

ppinIn

[in] Input pin.

pmt

[in] Media type to use for the connection (optional; that is, may be NULL).


IFilterGraph::Disconnect

HRESULT Disconnect(IPin * ppin);

Disconnects this pin.

•	Returns an HRESULT value.

ppin

[in] Pin to disconnect.

This method does not completely break the connection. To completely break the connection, both ends must be disconnected.

This method results in a successful no operation (no-op) if the pin is not connected.


IFilterGraph::EnumFilters

HRESULT EnumFilters(IEnumFilters ** ppEnum);

Provides an enumerator for all filters in the graph.

•	Returns an HRESULT value.

ppEnum

[out] Enumerator.

The interface returned by this method has had its reference count incremented. Be sure to call IUnknown::Release on the interface to decrement the reference count when you have finished using the interface.


IFilterGraph::FindFilterByName

HRESULT FindFilterByName(LPCWSTR pName,

    IFilter ** ppFilter);

Finds a filter that was added to the filter graph with a specific name.

•	Returns an HRESULT value.

pName

[in, string] Name to search for.

ppFilter

[out] Pointer to an IFilter interface on the found filter.

This function fails and sets pointers to the ppFilter parameter to NULL if the name is not in this graph.


IFilterGraph::Reconnect

HRESULT Reconnect(IPin * ppin);

Disconnects this and the pin to which it connects and then connects it back to the same pin. This allows the details of the connection, such as media type and allocator, to be renegotiated.

•	Returns an HRESULT value.

ppin

[in] Pin to disconnect and reconnect.

This method performs its operation on a separate thread that will not hold any relevant locks. It may be called by a pin or filter to allow 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 may 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

HRESULT RemoveFilter(IFilter * pFilter);

Removes a filter from the graph.

•	Returns an HRESULT value.

pFilter

[in] Pointer to the filter to be removed from the graph.

The filter graph implementation informs the filter that it is being removed by calling the IFilter::JoinFilterGraph method with a NULL argument.


IFilterGraph::SetDefaultSyncSource

HRESULT SetDefaultSyncSource(void);

Sets the default source of synchronization.

•	Returns an HRESULT value.

This method is used when no clock has been given to the filter graph, and the filter graph manager consequently has to find a clock to use as the synchronization source. The filter graph manager first tries all filters, starting with renderers, to see if any filter exports a clock (by providing an IReferenceClock interface). The filter graph manager will choose the first filter that it finds, providing that filter is connected to an upstream source. If no connected filters are found, the first filter providing IReferenceClock is used. Typically this will be the audio rendering filter. If no filter exports a clock, the filter graph manager uses a system clock.


IFilterInfo Interface

IFilterInfo is an interface that 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 IFilter interface that can be accessed through OLE Automation. This was created to provide access to the IFilter methods from Microsoft® Visual Basic® applications without incurring the overhead of OLE Automation in the IFilter interface itself.

When to Implement

This interface is implemented by the filter graph manager for use by OLE Automation client applications, such as Microsoft Visual Basic.

When to Use

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 	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.

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 IFilter interface for the filter.

get_Pins 	Retrieves an IAMCollection interface providing 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

HRESULT FindPin(BSTR strPinID, IDispatch **ppUnk);

Locates a pin, given an identifier, and returns an IPinInfo interface.

•	Returns an HRESULT value.

strPinID

[in] The string pin identifier.

ppUnk

[out] The IPinInfo interface.

This method corresponds to the IFilter::FindPin method. This method is exposed for use by OLE Automation clients and is not expected to be used by C or C++ developers.


IFilterInfo::get_Filename

HRESULT get_Filename(BSTR *pstrFilename);

Retrieves the file name associated with the source filter.

•	Returns an HRESULT value.

pstrFilename

[out, retval] The file name containing the source media.

This method is exposed for use by OLE Automation clients and is not expected to be used by C or C++ developers.


IFilterInfo::get_Filter

HRESULT get_Filter(IUnknown **ppUnk);

Retrieves the IFilter interface of the filter.

•	Returns an HRESULT value.

ppUnk

[out, retval] The IFilter interface of the filter represented by IFilterInfo.

This method is exposed for use by OLE Automation clients and is not expected to be used by C or C++ developers.


IFilterInfo::get_IsFileSource

HRESULT get_IsFileSource(LONG *pbIsSource);

Determines if the filter is a file source filter.

•	Returns an HRESULT value. Returns OATRUE if filter is a file source filter; otherwise, returns OAFALSE.

pbIsSource

[out, retval] Returned Boolean value.

This method is exposed for use by OLE Automation clients and is not expected to be used by C or C++ developers.


IFilterInfo::get_Name

HRESULT get_Name(BSTR *strName);

Retrieves the filter name.

•	Returns an HRESULT value.

strName

[out, retval] The name of the filter.

This method is exposed for use by OLE Automation clients and is not expected to be used by C or C++ developers.


IFilterInfo::get_Pins

HRESULT get_Pins(IDispatch **ppUnk);

Retrieves an IAMCollection interface, which provides access to the IPinInfo interfaces for the pins on this filter.

•	Returns an HRESULT value.

ppUnk

[out, retval] An IAMCollection interface.

This method is exposed for use by OLE Automation clients and is not expected to be used by C or C++ developers. Visual Basic applications can enumerate the IPinInfo interfaces in the returned IAMCollection object by using the For Each ...Next syntax.


IFilterInfo::get_VendorInfo

HRESULT get_VendorInfo(BSTR *strVendorInfo);

Retrieves a string containing optional information supplied by a vendor about the specified filter.

•	Returns an HRESULT value.

strVendorInfo

[out, retval] String containing vendor information.

This method is exposed for use by OLE Automation clients and is not expected to be used by C or C++ developers.


IFilterInfo::put_Filename

HRESULT put_Filename(BSTR strFilename);

Sets the file name containing the media source.

•	Returns an HRESULT value.

strFilename

[in] The name of the file for the source filter to read from.

This method is exposed for use by OLE Automation clients and is not expected to be used by C or C++ developers.


IFilterMapper Interface

The IFilterMapper interface is an abstraction that represents registered information about filters. This allows properties of filters to be looked up during loading.

When to Implement

This interface is implemented on the filter mapper and is not intended to be implemented by developers.

When to Use

This interface is used by filters to register and unregister themselves. This is handled in the base classes by the CBaseFilter::Register and CBaseFilter::Unregister member functions. It is also used by the filter graph manager to look up filters and determine their characteristics when building a filter graph to render a given media type.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns 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 filter 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

HRESULT EnumMatchingFilters(IEnumRegFilters ** ppEnum,

    DWORD dwMerit, BOOL bInputNeeded, CLSID clsInMaj,

    CLSID clsInSub, BOOL bRender, BOOL bOutputNeeded,

    CLSID clsOutMaj, CLSID clsOutSub);

Provides an enumerator that enumerates registered filters that meet specified requirements.

•	Returns an HRESULT value.

ppEnum

[out] Enumerator returned.

dwMerit

[in] Enumerate only filters with at least this merit.

bInputNeeded

TRUE if there must be at least one input pin.

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] Option that specifies if the input must be rendered by this filter.

bOutputNeeded

TRUE if there must be at least one output pin.

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.

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

HRESULT RegisterFilter(CLSID clsid, LPCWSTR Name,

    DWORD dwMerit);

Adds a filter to the registry; the filter can then be enumerated.

•	Returns an HRESULT value.

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.

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 as 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 may 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 need to 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.


IFilterMapper::RegisterFilterInstance

HRESULT RegisterFilterInstance(CLSID clsid,

    LPCWSTR Name, CLSID *MRId);

Registers an identifiable instance of a filter.

•	Returns an HRESULT value.

clsid

[in] Globally unique identifier (GUID) of the filter.

Name

[in] Descriptive name of the instance.

MRId

[out] Returned media resource ID. This parameter is a locally unique identifier for this instance of this filter.

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

HRESULT RegisterPin(CLSID Filter, LPCWSTR Name,

    BOOL bRendered, BOOL bOutput, BOOL bZero,

    BOOL bMany, CLSID ConnectsToFilter,

    LPWSTR ConnectsToPin);

Records the details of the pin in the registry.

•	Returns an HRESULT value.

Filter

[in] Globally unique identifier (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. Note that pin names longer than 99 characters should not be used because this causes filter enumeration problems.

bRendered

[in] Set to TRUE if the filter renders this input; otherwise, set to FALSE.

bOutput

[in] Set to TRUE if this is an output pin; otherwise, set to FALSE.

bZero

[in] If the filter may have zero instances of this pin, set to TRUE; otherwise, set to FALSE. For example, a decompression filter may choose to not create a sound output pin for a movie without a sound track.

bMany

[in] If the filter may have many instances of this pin, set to TRUE; otherwise, set to FALSE. For example, a mixer may 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.


IFilterMapper::RegisterPinType

HRESULT RegisterPinType(CLSID clsFilter, LPCWSTR strName,

    CLSID clsMajorType, CCLSID clsSubType);

Registers this pin type.

•	Returns an HRESULT value.

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.

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

HRESULT UnregisterFilter(CLSID Filter);

Removes the registration of this filter from the registry.

•	Returns an HRESULT value.

Filter

[in] Globally unique identifier (GUID) of the filter.


IFilterMapper::UnregisterFilterInstance

HRESULT UnregisterFilterInstance(CLSID MRId);

Removes the registration of this filter instance from the registry.

•	Returns an HRESULT value.

MRId

[in] Media resource identifier of this instance.


IFilterMapper::UnregisterPin

HRESULT UnregisterPin(CLSID Filter, LPCWSTR Name);

Removes the registration of this pin from the registry.

•	Returns an HRESULT value.

Filter

[in] Globally unique identifier (GUID) of the filter that this pin is part of.

Name

[in] Name of the pin.


IFullScreenVideo Interface

This interface allows an application or plug-in distributor to control a full-screen renderer. The Microsoft® ActiveMovie™ full-screen renderer supports this interface. When connected, a renderer should load the display modes that are available. The 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 ActiveMovie 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.

The filter graph manager uses the full-screen renderer to help implement the full-screen property that can be set through IVideoWindow::put_FullScreenMode. When used in this manner, the expected behavior is to switch seamlessly between full-screen mode and then back into normal window playback when the user presses the ESC key or other escape sequences. In this case the renderer is required to hide its window rather than minimize it when switching away from it. The renderer can be made to hide rather than minimize (the default action) by calling IFullScreenVideo::HideOnDeactivate.

When to Implement

Implement this interface if you are writing an alternate full-screen video renderer. The Microsoft full-screen video renderer implements this interface by default.

When to Use

Use this interface from any application that needs to interact with the full-screen video renderer in order to set or determine video modes or other full-screen renderer properties.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns 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 	Specifes 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

HRESULT CountModes(long *pModes);

Retrieves the number of modes available on the full-screen renderer.

•	Returns an HRESULT value.

pModes

[out] Returned mode count.

The Microsoft ActiveMovie full-screen renderer supports eight modes (320 x 200 x 8/16 bit, 320 x 240 x 8/16, 640 x 400 x 8/16, and 640 x 480 x 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

HRESULT GetCaption(BSTR *pstrCaption);

Retrieves the caption associated with the full-screen window.

•	Returns an HRESULT value.

pstrCaption

[out] Retrieved caption.

The Microsoft ActiveMovie full-screen renderer will show itself as an icon when it is deactivated (it can be deactivated by using the ALT+TAB key combination 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

HRESULT GetClipFactor(long *pClipFactor);

Retrieves the current clip loss factor setting.

•	Returns an HRESULT value.

pClipFactor

[out] Maximum allowable amount of the image to lose.

For a description of the clip loss factor setting, see IFullScreenVideo::SetClipFactor.


IFullScreenVideo::GetCurrentMode

HRESULT GetCurrentMode(long *pMode);

Retrieves the video mode currently in effect.

•	Returns an HRESULT value.

pMode

[out] Retrieved full-screen video mode.

When the full-screen video renderer is connected, it will have chosen 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 Microsoft ActiveMovie full-screen video renderer, see IFullScreenVideo::SetEnabled.


IFullScreenVideo::GetMessageDrain

HRESULT GetMessageDrain(HWND *hwnd);

Retrieves the window set to receive window messages sent to the renderer.

•	Returns an HRESULT value.

hwnd

[out] Window handle of the window specified as the message drain.

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 may watch for the CTRL+P key combination as a cue to pause the video.


IFullScreenVideo::GetModeInfo

HRESULT GetModeInfo(long Mode, long *pWidth,

    long *pHeight, long *pDepth);

Retrieves information about a specified mode.

•	Returns an HRESULT value.

Mode

[in] Specified mode for which to retrieve information.

pWidth

[out] Width in pixels of the mode's image display.

pHeight

[out] Height in pixels of the mode's image display.

pDepth

[out] Number of color bits per pixel.

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.

Dor a list of modes available to the Microsoft ActiveMovie full-screen video renderer, see IFullScreenVideo::SetEnabled.


IFullScreenVideo::GetMonitor

HRESULT GetMonitor(long *Monitor);

Retrieves the monitor type in use.

•	Returns an HRESULT value.

Monitor

[out] Monitor currently in use.

The Microsoft ActiveMovie full-screen renderer always returns zero (the primary monitor). In future versions of ActiveMovie, the renderer may allow applications to select the monitor on which to play the full-screen video.


IFullScreenVideo::HideOnDeactivate

HRESULT HideOnDeactivate(long Hide);

Hides the window icon when the full-screen window is deactivated.

•	Returns an HRESULT value.

Hide

[in] Set to OATRUE to hide the video window icon when deactivated; set to OAFALSE to display the icon.

The default setting for the Microsoft ActiveMovie 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 iconized.


IFullScreenVideo::IsHideOnDeactivate

HRESULT IsHideOnDeactivate(void);

Retrieves the state of the HideOnDeactivate property.

•	Returns an HRESULT value (OATRUE or OAFALSE).

For a description of the HideOnDeactivate property, see IFullScreenVideo::HideOnDeactivate.


IFullScreenVideo::IsModeAvailable

HRESULT IsModeAvailable(long Mode);

Determines if a specified video mode is available.

•	Returns OATRUE if available; otherwise, returns OAFALSE.

Mode

[in] Full-screen mode to check.

The display modes supported by the Microsoft ActiveMovie full-screen renderer are different than the actual modes available on any given display card. An application can use this method to discover which display modes are available. This method can be called only when the renderer is connected, because until then it may not have allocated the resources it needs to make this information available. Even if a mode is available does not necessarily mean that it will be used for video playback; that also depends on the filters available in the filter graph.


IFullScreenVideo::IsModeEnabled

HRESULT IsModeEnabled(long Mode);

Determines if a specified mode is enabled.

•	Returns an HRESULT value.

Mode

[in] Full-screen video mode to check.

This method can be used to enable and disable specific display modes supported by the renderer. As with IFullScreenVideo::IsModeAvailable, the fact that a mode is enabled does not mean that it will be used for playback.

For a list of available modes for the Microsoft ActiveMovie full-screen video renderer, see IFullScreenVideo::SetEnabled.


IFullScreenVideo::SetCaption

HRESULT SetCaption(BSTR strCaption);

Sets the title associated with the full-screen window.

•	Returns an HRESULT value.

strCaption

[in] String containing the caption.


IFullScreenVideo::SetClipFactor

HRESULT SetClipFactor(long ClipFactor);

Specifies the video mode based on the maximum data that will be lost.

•	Returns an HRESULT value.

ClipFactor

[in] Maximum allowable amount of the image to lose.

Clip loss factor is a means of enabling full-screen modes that is more generic and easier to use by applications. 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 x 288) into a 320 x 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 x 288 pixels) to be played in a 320 x 200 display mode, it defaults to 25 percent.


IFullScreenVideo::SetDefault

HRESULT SetDefault(void);

Sets the default full-screen video renderer settings.

•	Returns an HRESULT value.

The properties set through this interface apply to the current renderer instance only. They may, however, be made the global default by calling this interface method.


IFullScreenVideo::SetEnabled

HRESULT SetEnabled(long Mode, long bEnabled);

Enables and disables video modes.

•	Returns an HRESULT value.

Mode

[in] Mode to be enabled or disabled (see table below).

bEnabled

[out] The bEnabled flag can be set to one of the following values.

Value 	Meaning

OATRUE 	Enable mode.

OAFALSE 	Disable mode.

Microsoft ActiveMovie available modes are defined as follows.

Mode	Width	Height	RGB Depth (in bits)
0	320	200	8
1	320	200	16
2	320	240	8
3	320	240	16
4	640	400	8
5	640	400	16
6	640	480	8
7	640	480	16


IFullScreenVideo::SetMessageDrain

HRESULT SetMessageDrain(HWND hwnd);

Specifies a window that will receive window messages sent to the renderer.

•	Returns an HRESULT value.

hwnd

[in] Window handle of the message drain window.

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 may watch for the CTRL+P key combination as a cue to pause the video.


IFullScreenVideo::SetMonitor

HRESULT SetMonitor(long Monitor);

Sets the monitor type in use.

•	Returns an HRESULT value.

Monitor

[in] Monitor being used.

Setting this method to anything but the primary display (0) will return an error. In future versions of Microsoft ActiveMovie, the renderer may allow applications to select the monitor on which to play back the full-screen video.


IGraphBuilder Interface

The IGraphBuilder interface allows applications to call upon the filter graph manager to attempt to build a complete filter graph, or parts of a filter graph given only partial information such as the name of a file or the interfaces of two separate pins. The filter mapper looks up filters in the registry to configure the filter graph in a meaningful way.

IGraphBuilder inherits from the IFilterGraph interface and exposes all of its methods. For this reason, IFilterGraph should normally not be used directly.

When to Implement

This interface is implemented on the filter graph manager and is not intended for implementation by developers.

When to Use

Applications use this interface to create a filter graph, add filters to or remove filters from a filter graph, enumerate all of the filters in a filter graph, and force connections when adding a filter. Filters typically use the interface to reconnect pins during the connection and negotiation process of building a 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.

IFilterGraph methods 	Description

AddFilter 	Adds a filter to the graph and gives it a name.

RemoveFilter 	Removes a filter from the graph.

Reconnect 	Breaks the existing pin connection and reconnects it to the same pin.

EnumFilters 	Provides an enumerator for all filters in the graph.

FindFilterByName 	Finds a filter that was added with a specified name.

ConnectDirect 	Connects the two IPin objects directly (without intervening filters).

Reconnect 	Breaks the existing pin connection and reconnects it to the same pin.

Disconnect 	Disconnects this pin, if connected.

SetDefaultSyncSource 	Sets the default synchronization source (a clock).

IGraphBuilder methods 	Description

Connect 	Connects two IPin objects. If they will not connect directly, this method connects them with intervening transforms.

Render 	Adds a chain of filters to this output pin so as 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 log file into which actions taken in attempting to perform an operation are logged.


IGraphBuilder::AddSourceFilter

HRESULT AddSourceFilter(LPCWSTR lpwstrFileName,

    LPCWSTR lpwstrFilterName, IFilter* * ppFilter);

Adds a source filter to the filter graph for this file.

•	Returns an HRESULT value.

lpwstrFileName

[in] Pointer to the file.

lpwstrFilterName

[in] Name to give the source filter when it is added.

ppFilter

[out] Pointer to an IFilter interface on the filter that was added.

This method allows you to obtain and retain more control over building the rest of the graph. For example, you can call the IFilterGraph::AddFilter method to add a renderer of your choice, and then call the IGraphBuilder::Connect method to connect the two filters. The IFilter 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 responsibility of the application 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. Note that, 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 only be connected to a parser filter, such as the MPEG splitter filter.

Note that the IGraphBuilder::RenderFile method adds the same source filter.


IGraphBuilder::Connect

HRESULT Connect(IPin * ppinOut, IPin * ppinIn);

Connects the two pins, using intermediates if necessary.

•	Returns an HRESULT value.

ppinOut

[in] Output pin.

ppinIn

[in] Input pin.

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.


IGraphBuilder::Render

HRESULT Render(IPin * ppinOut);

Builds a filter graph that renders the data from this output pin.

•	Returns an HRESULT value.

ppinOut

[in] Output pin.

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.


IGraphBuilder::RenderFile

HRESULT RenderFile(LPCWSTR lpwstrFile,

    LPCWSTR lpwstrPlayList);

Builds a filter graph that renders the specified file.

•	Returns an HRESULT value.

lpwstrFile

[in] Name of the file containing the data to be rendered.

lpwstrPlayList

[in] Playlist name. Reserved; must be NULL. (This parameter is currently unimplemented.)

If the lpwstrPlayList parameter is NULL, this method would use the default playlist, which typically renders the entire file.


IGraphBuilder::SetLogFile

HRESULT SetLogFile(HANDLE hFile);

Sets the file into which actions taken in attempting to perform an operation are logged.

•	Returns an HRESULT value.

hFile

Handle to the log file.

The hFile parameter must be an open file handle. After calling this method with a valid file handle, actions taken by IGraphBuilder methods when attempting to build a filter graph are logged to this file. This is intended to help you determine the cause of any failure to automatically build a filter graph.


IGraphVersion Interface

The IGraphVersion interface is provided by the filter graph manager to let other objects, especially plug-in distributors and the GraphEdit tool, know when the graph has changed.

When to Implement

This interface is implemented by the filter graph manager.

When to Use

Use this interface if your application or plug-in distributor needs to know when filters have been added, deleted, or reconnected.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IGraphVersion methods 	Description

QueryVersion 	Returns the current graph version number.


IGraphVersion::QueryVersion

HRESULT QueryVersion(LONG* pVersion);

Returns the current graph version number.

•	Returns an HRESULT value.

pVersion

Current graph version.

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 needs to be re-enumerated.


IMediaControl Interface

The filter graph exposes the IMediaControl interface 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 of building graphs to play back media files.

When to Implement

This interface is implemented by the filter graph manager. Implement this only if you are writing a plug-in distributor that needs to export the control methods.

When to Use

Use this interface from any application that wants to control the playing of media through Microsoft® ActiveMovie™ filter graphs. Applications can also use it to enumerate the filters in the filter graph and all the filters in the registry, to add a source filter to the filter graph, and to instruct the filter graph manager to build a filter graph capable of rendering the media type in a file.

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.

IMediaControl methods 	Description

Run 	Switches the entire filter graph into running mode.

Pause 	Pauses all filters in the filter graph.

Stop 	Switches all filters in the filter graph to a stopped state.

GetState 	Retrieves the state of the filter graph.

RenderFile 	Adds and connects filters needed to play the specified file.

AddSourceFilter 	Adds to the graph the source filter that can read the given file name, and returns an IDispatch interface pointer to the filter object.

get_FilterCollection 	Retrieves a collection of IFilterInfo interfaces representing the filters in the graph.

get_RegFilterCollection 	Retrieves a collection of IRegFilterInfo interfaces representing the filters available in the registry.


IMediaControl::AddSourceFilter

HRESULT AddSourceFilter(BSTR strFilename,

    IDispatch **ppUnk);

Adds to the graph the source filter that can read the given file name, and returns an IDispatch interface pointer to the filter object.

•	Returns an HRESULT value.

strFilename

[in] The name of the file containing the source video.

ppUnk

[out] The pointer to the IFilterInfo interface on the filter.

This method is primarily for use by OLE Automation clients because it returns an IDispatch interface pointer. C and C++ applications should call the IGraphBuilder::AddSourceFilter method to perform this operation.


IMediaControl::get_FilterCollection

HRESULT get_FilterCollection(IDispatch **ppUnk);

Retrieves a collection of IFilterInfo interfaces representing the filters in the graph and returns IDispatch for an object that supports the IAMCollection interface.

•	Returns an HRESULT value.

ppUnk

[out, retval] The IFilterInfo object for the graph.

This method is primarily for use by OLE Automation clients because it returns an IDispatch interface pointer. C and C++ applications should call the IFilterGraph::EnumFilters method to perform this operation.


IMediaControl::get_RegFilterCollection

HRESULT get_RegFilterCollection(IDispatch **ppUnk);

Retrieves a collection of IRegFilterInfo interfaces representing the filters available in the registry.

•	Returns an HRESULT value.

ppUnk

[out, retval] The IDispatch interface of the IAMCollection object.

This method is primarily for use by OLE Automation clients because it returns an IDispatch interface pointer. C and C++ applications should call the IFilterMapper::EnumMatchingFilters method to perform this operation.


IMediaControl::GetState

HRESULT GetState(LONG msTimeout, OAFilterState* pfs);

Retrieves the current state of the graph.

•	Returns an HRESULT value, which will be VFW_S_STATE_INTERMEDIATE if the state transition is not complete, or S_OK if it has been successfully completed.

msTimeout

[in] Duration of the time-out, in milliseconds. To block indefinitely, pass INFINITE.

pfs

[out] Holds the returned state of the graph.

Not all state transitions are synchronous. For example, even though the IMediaControl::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 S_OK 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 VFW_S_STATE_INTERMEDIATE, and the returned state will be the state into which the graph is transitioning (either State_Stopped, State_Paused or State_Running).

If you specify an infinite time-out, the method does not return VFW_S_STATE_INTERMEDIATE. A call on another thread to change the state while this method is blocked will result in this method returning an error.


IMediaControl::Pause

HRESULT Pause();

Pauses all the filters in the filter graph.

•	Returns an HRESULT value.

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 paused state cues the graph for immediate rendering when put into running state.


IMediaControl::RenderFile

HRESULT RenderFile(BSTR strFilename);

Adds and connects filters needed to play the specified file.

•	Returns an HRESULT value.

strFilename

The name of the file to render.

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. This method is OLE Automation-compatible and is equivalent to IGraphBuilder::RenderFile, which should be used by C and C++ applications.


IMediaControl::Run

HRESULT Run();

Switches the entire filter graph into a running state.

•	Returns an HRESULT value.

In a running state, data is pushed down the filter graph and rendered. The graph remains in a running state until it is stopped by the IMediaControl::Pause or IMediaControl::Stop method. The graph remains in a running state even after notifying the application of completion (that is, the EC_COMPLETE notification is sent to the application). This allows the application to determine whether to pause or stop after completion.

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 may have successfully entered the running state. In a multistream graph, entire streams may be playing successfully. The application must determine whether to stop execution or not.


IMediaControl::Stop

HRESULT Stop();

Switches all filters in the filter graph to the stopped state.

•	Returns an HRESULT value.

In this mode, filters release resources and no data is processed. If the filters are in the 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 Interface

This interface supports event notification from the filter graph and filters within it to the application. It is decoupled by using a queuing scheme rather than callbacks because events can be notified from worker threads that cannot safely call back into application code.

An event code and two DWORD 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. The filter graph exposes an IMediaEventSink interface that the filters within the graph can call to pass event notifications to the application.

Event notifications are placed in a queue. An application calls the IMediaEvent::GetEvent method to retrieve the next notification from the queue. This method blocks until there is an event to return. The GetEvent time-out parameter allows the application to specify the time, in milliseconds, to wait for an event, including values of zero and infinite.

In addition, applications can retrieve the event handle. IMediaEvent::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 IMediaEvent::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 manager 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 IMediaEvent::CancelDefaultHandling method with the event value as a parameter. The IMediaEvent::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 running state on any filter, an error value is returned by the IMediaControl::Run method. In this case, some filters within the graph may 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 IMediaControl::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 manager asks filters if they can report EC_COMPLETE by means of seekable renderers.

A seekable renderer is a renderer that supports the IMediaPosition interface from the filter and that has only input pins, or whose input pins report through IPin::QueryInternalConnections that they are rendered at that point. The filter graph uses IPin::QueryInternalConnections and IMediaPosition to detect seekable renderers. A seekable renderer should report 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 IMediaControl::Pause or IMediaControl::Stop method.

The aggregation of EC_COMPLETE messages can be disabled by calling IMediaEvent::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 ActiveMovie Event Notification Codes.

When to Implement

This interface is implemented by the filter graph manager.

You can use the CMediaEvent class, which handles the IDispatch implementation for OLE Automation, to help implement this interface.

When to Use

This interface is used by applications to retrieve event notifications or event handles from the filter graph manager. For example, the EC_COMPLETE notification can be retrieved to know when a media stream has finished being rendered.

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.

IMediaEvent methods 	Description

GetEventHandle 	Retrieves a handle to a manual-reset event that will be signaled.

GetEvent 	Retrieves the next notification event.

WaitForCompletion 	Waits until the graph's operation has completed.

CancelDefaultHandling 	Cancels any default handling of the specified event by the filter graph.

RestoreDefaultHandling 	Restores default handling for this event.

FreeEventParams 	Frees resources associated with the parameters to an event.


IMediaEvent::CancelDefaultHandling

HRESULT CancelDefaultHandling(long lEvCode);

Cancels any default handling by the filter graph of the specified event and ensures that it is passed to the application.

•	Returns S_OK if successful, or S_FALSE if the event does not have any default handling.

lEvCode

Event code for which to cancel default handling.

Currently the filter graph manager applies default handling only to EC_COMPLETE and EC_REPAINT.


IMediaEvent::FreeEventParams

HRESULT FreeEventParams(long * lEventCode,

    long * lParam1, long * lParam2);

Frees resources associated with the parameters of an event.

•	Returns an HRESULT value.

lEventCode

[in] Next event notification.

lParam1

[in] First parameter of the event.

lParam2

[in] Second parameter of the event.

Event parameters can be of type LONG or BSTR, or can be an IUnknown interface pointer. If a BSTR is passed as an event, it will have been allocated by the task allocator and should be freed. If an IUnknown pointer was passed as an event, it was reference counted and should be released. This method performs these services.


IMediaEvent::GetEvent

HRESULT GetEvent(long * lEventCode, long * lParam1,

    long * lParam2, long msTimeout);

Retrieves the next notification event.

•	Returns an HRESULT value.

IEventCode

[out] Next event notification.

lParam1

[out] First parameter of the event.

lParam2

[out] Second parameter of the event.

msTimeout

[in] Time, in milliseconds, to wait before assuming that there are no events.

If the time-out is zero and there is no event waiting, or if the time-out elapses before an event appears, this method returns E_ABORT. A time-out value of INFINITE can be passed to indicate that the method should block until there is an event.

For a list of notification codes and event parameter values, see ActiveMovie Event Notification Codes.


IMediaEvent::GetEventHandle

HRESULT GetEventHandle(OAEVENT * hEvent);

Retrieves a handle to a manual-reset event that will be signaled as long as there are event notifications to deliver.

•	Returns an HRESULT value.

hEvent

[out] Handle for the event.

The event can be passed to the Microsoft Win32 WaitForMultipleObjects or MsgWaitForMultipleObjects function to wait for event notifications at the same time as other messages and events on a single thread.


IMediaEvent::RestoreDefaultHandling

HRESULT RestoreDefaultHandling(long lEvCode);

Reinstates the normal default handling by a filter graph for the specified event if there is one.

•	Returns S_OK if successful, or S_FALSE if there is no default handling for this event.

lEvCode

[in] The event to restore.

Events that have default handling in place, such as EC_REPAINT, are not typically passed to the application.


IMediaEvent::WaitForCompletion

HRESULT WaitForCompletion(long msTimeout,

    long * pEvCode);

Provides a simplified way for applications to wait until the filter graph's operation has completed. It is the equivalent of blocking until the event notification EC_COMPLETE, EC_ERRORABORT, or EC_USERABORT is received.

•	Returns an HRESULT value.

msTimeout

[in] Duration of the time-out, in milliseconds. To block indefinitely, pass INFINITE.

pEvCode

[out] The event to wait for.

Upon return, the filter graph is still in a running state. This method assumes that separate calls to the IMediaEvent interface are not being made. This method fails if the graph is not in or transitioning into a running state. The time-out parameter specifies the length of time to wait for completion. A zero value returns immediately, and the special value INFINITE can be used to block indefinitely. The pEvCode parameter returns the event notification that terminated the wait. A value of zero indicates that the operation has not completed.


IMediaEventSink Interface

The filter graph manager exposes the IMediaEventSink interface; it is called from filters to notify events. Applications call the IMediaEvent interface on the filter graph manager to retrieve these events.

When to Implement

There is no need to implement this method because it is implemented by the filter graph manager.

When to Use

Filters use this interface to post event notifications.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IMediaEventSink methods 	Description

Notify 	Notifies an event.


IMediaEventSink::Notify

HRESULT Notify(long EventCode, long EventParam1,

    long EventParam2);

Notifies an event.

•	Returns an HRESULT value.

EventCode

[in] Identifier of the event.

EventParam1

[in] First event parameter.

EventParam2

[in] Second event parameter.

The event is queued but not delivered to the application on this thread. For a list of notification codes and event parameter values, see the ActiveMovie Event Notification Codes.


IMediaFilter Interface

Multimedia components that provide time-based data expose the IMediaFilter interface. This interface abstracts an object that processes time-based data streams and represents a multimedia device (possibly implemented in software). It controls the active or running state of the object and the synchronization of this state with other objects in the system.

This interface inherits the IPersist interface.

When to Implement

Methods on this interface should be implemented as part of any filter. This is typically done by using the base class CBaseFilter, which implements IFilter and IMediaFilter.

When to Use

Because the IMediaFilter interface is inherited by the IFilter interface, which adds other necessary methods required to be exported by filters, this interface is not normally used directly by the filter graph manager or other filters. It may, however, be of use to plug-in distributors. For example, the filter graph manager internally exports IMediaFilter; its plug-in distributor exports IMediaControl and calls the IMediaFilter methods to implement its own methods.

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 	Informs the filter to transition to the new (stopped) state.

Pause 	Informs the filter to transition to the new (paused) state.

Run 	Informs the filter to transition to the new (running) state.

GetState 	Determines the state of the filter.

SetSyncSource 	Identifies the reference clock to which the filter should synchronize activity.

GetSyncSource 	Retrieves the current reference clock (or NULL if there is no clock). Passes a time value to synchronize independent streams.


IMediaFilter::GetState

HRESULT GetState(DWORD dwMilliSecsTimeout,

    FILTER_STATE * State);

Determines the state of the filter.

•	Returns S_OK if the state is running, paused, or inactive; otherwise, returns VFW_S_STATE_INTERMEDIATE if the transition is not complete (the time-out expired). The state returned in the latter case is the one being changed to.

dwMilliSecsTimeout

[in] Duration of the time-out, in milliseconds. To block indefinitely, pass INFINITE.

State

[out] Returned state of the filter. States include stopped, paused, running, or intermediate (in the process of changing).


IMediaFilter::GetSyncSource

HRESULT GetSyncSource(IReferenceClock ** pClock);

Retrieves the current reference clock in use by this filter.

•	Returns an HRESULT value.

pClock

[out] Pointer to a reference clock; it will be set to the IReferenceClock interface.

The returned interface (if it is not NULL) will have a reference added by the IUnknown::AddRef method. The calling application should release the interface by calling the IUnknown::Release method when it has finished with the pointer.


IMediaFilter::Pause

HRESULT Pause(void);

Informs the filter to transition to the new state.

•	Returns S_OK if the transition is complete; otherwise, returns one of the following values.

Value 	Meaning

Error value 	Transition failed.

S_FALSE 	Transition is not complete, but no error has occurred.

The state transition may not be immediate (external mechanical activity may be involved, for example). The state method may return before the transition has completed.


IMediaFilter::Run

HRESULT Run(REFERENCE_TIME tStart);

Informs the filter to transition to the new (running) state. Passes a time value to synchronize independent streams.

•	Returns an HRESULT value.

tStart

Time value of the reference clock.

The tStart parameter is the amount to be added to the IMediaSample time stamp to determine the time at which that sample should be rendered according to the reference clock. That is, it is the reference time at which a sample with a stream time of zero should be rendered.

For example, the time value for the beginning of the stream is the time at which the first sample should appear. If the application restarts from paused mode in midstream, tStart is the amount of time paused, plus the start time.

The filter graph provides this information to its filters. An application calling the filter graph may pass a start time of zero, in which case the filter graph calculates a time that will begin as soon as possible. Filter graphs accept zero to mean as soon as possible; most filters do not.


IMediaFilter::SetSyncSource

HRESULT SetSyncSource(IReferenceClock * pClock);

Identifies the reference clock to which the filter should synchronize activity.

•	Returns an HRESULT value.

pClock

[in] Pointer to the IReferenceClock interface.

This method is of most importance to rendering filters and may not apply to other filters. The pClock parameter can be NULL, meaning that the filter should run as fast as possible at its current quality settings without any attempt to synchronize. For example, a filter graph that is doing compression probably runs in this mode. Each filter takes as long as it needs.


IMediaFilter::Stop

HRESULT Stop(void);

Informs the filter to transition to the new state.

•	Returns S_OK if the transition is complete; otherwise, returns one of the following values.

Value 	Meaning

Error value 	Transition failed.

S_FALSE 	Transition is not complete, but no error has occurred.

The state transition may not be immediate (external mechanical activity may be involved, for example). The state functions may return before the transition has completed.


IMediaPosition Interface

Applications communicating with the filter graph can call methods on this interface to set or retrieve properties such as the duration of the stream, 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 REFTIME parameters used in this interface are double value, representing a fractional number of seconds. Internally, filters will store time to an accuracy of 100 nanoseconds.

When to Implement

The filter graph manager exposes the IMediaPosition interface if any of the filters within the graph are seekable (can seek to an arbitrary position in the stream). This normally means a seekable file source filter. Filters, such as a file source filter, will expose IMediaPosition if they can seek their data or if their output pin represents a seekable stream. The renderer filter should also expose this interface. Output pins of transform filters expose this interface in order to pass the positioning information upstream from the renderer through each intermediate filter to the seekable filter.

Use the CMediaPosition class to help implement this interface on a filter. Use the CPosPassThru base class to implement this interface on output pins of transform filters that are used to pass media positioning information upstream. This is enabled by default in the pin base classes.

When to Use

Applications can use this interface to set or retrieve media positioning properties. Most commonly, an application will use the methods on this interface to play a media stream for some duration starting at some set position in the stream (for example, 10 seconds from the start).

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.

IMediaPosition methods 	Description

get_Duration 	Retrieves the total duration of the media stream.

put_CurrentPosition 	Sets the time that the media stream begins.

get_CurrentPosition 	Retrieves the current position in terms of the total length of the media stream.

get_StopTime 	Retrieves the position within the media stream at which playback should stop.

put_StopTime 	Sets the position within the media stream at which playback should stop.

get_PrerollTime 	Retrieves the time prior to the start position that the filter graph begins any nonrandom access device rolling.

put_PrerollTime 	Sets the time prior to the start position that the filter graph begins any nonrandom access device rolling.

put_Rate 	Sets the playback rate, relative to normal playback of the media stream.

get_Rate 	Retrieves the playback rate, relative to normal playback of the media stream.

CanSeekForward 	Determines if the current position can be moved forward in the media stream.

CanSeekBackward 	Determines if the current position can be moved backward in the media stream.


IMediaPosition::CanSeekBackward

HRESULT CanSeekBackward(LONG *pCanSeekBackward);

Determines if the current position can be moved backward in the media stream.

•	Returns an HRESULT value.

pCanSeekBackward

[out] Set to OATRUE if able to seek backward; otherwise set to OAFALSE.


IMediaPosition::CanSeekForward

HRESULT CanSeekForward(LONG *pCanSeekForward);

Determines if the current position can be moved forward in the media stream.

•	Returns an HRESULT value.

pCanSeekForward

[out] Set to OATRUE if able to seek forward; otherwise set to OAFALSE.


IMediaPosition::get_CurrentPosition

HRESULT get_CurrentPosition(REFTIME* pllTime);

Retrieves the current position in terms of the total length of the media stream.

•	Returns an HRESULT value.

pllTime

[out] Reference time of the current position.

This is 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.

When the filter graph is stopped or paused, this method 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 there has been an IMediaPosition::put_CurrentPosition call in the meantime.


IMediaPosition::get_Duration

HRESULT get_Duration(REFTIME* plength);

Retrieves the total duration of the media stream.

•	Returns an HRESULT value.

plength

[out] The returned length of the media stream.

The duration assumes normal playback speed, and it is therefore unaffected by the rate.


IMediaPosition::get_PrerollTime

HRESULT get_PrerollTime(REFTIME* pllTime);

Retrieves the time prior to the start position that devices should start rolling.

•	Returns an HRESULT value.

pllTime

[out] Returned preroll time as a LONGLONG pointer value.

Preroll time is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.


IMediaPosition::get_Rate

HRESULT get_Rate(double * pdRate);

Retrieves the rate of playback relative to normal playback speed.

•	Returns an HRESULT value.

pdRate

[out] Returned rate.

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.


IMediaPosition::get_StopTime

HRESULT get_StopTime(REFTIME* pllTime);

Retrieves the time at which the media stream stops.

•	Returns an HRESULT value.

pllTime

[out] The returned stop time as a LONGLONG pointer value.

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.


IMediaPosition::put_CurrentPosition

HRESULT put_CurrentPosition(REFTIME llTime);

Sets the time that the media stream begins.

•	Returns an HRESULT value.

llTime

[in] Start time expressed as a LONGLONG value.

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.

If this method is called when the filter graph manager is running, the filter graph manager will pause the graph, execute the method, and then issue a new run command.

If called when the filter graph is paused, this method needs to flush existing data by using IPin::BeginFlush and IPin::EndFlush before pushing the new data (at the new current position).

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.


IMediaPosition::put_PrerollTime

HRESULT put_PrerollTime(REFTIME llTime);

Sets the time prior to the start position that devices should start rolling.

•	Returns an HRESULT value.

llTime

[in] Preroll time to be set.

Preroll time is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.


IMediaPosition::put_Rate

HRESULT put_Rate(double dRate);

Sets the rate of playback relative to normal speed.

•	Returns an HRESULT value.

dRate

[in] The rate to set.

This method 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 samples.

Negative rates indicate reverse play. This will not be supported by all media types.


IMediaPosition::put_StopTime

HRESULT put_StopTime(REFTIME llTime);

Sets the time at which the media stream will stop.

•	Returns an HRESULT value.

llTime

[in] Stop time as a LONGLONG value.

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.


IMediaSample Interface

The IMediaSample interface provides shared memory buffer functionality, holds some properties about the data, and holds a pointer to the data itself. It is used by connected pins to transport media samples from one pin to another.

When to Implement

Implement this interface if you are providing an allocator (buffer) to be used for transporting media samples between filters. This interface is implemented by the CMediaSample class in the ActiveMovie™ class library.

When to Use

Filters call methods on this interface to set properties and pass data to another filter. Downstream filters call methods on this interface to read the media sample's data and properties. Filters can modify the data in a media sample in place or can make a copy of the sample, modify the copy, and pass it on.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns 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 	Returns the size, in bytes, of the buffer data area.

GetTime 	Retrieves the media time stamps for this sample.

SetTime 	Sets the media time stamps for this sample

IsSyncPoint 	Determines if the beginning of a sample is a synchronization point.

SetSyncPoint 	Sets the synchronization point.

IsPreroll 	Indicates a preroll property. If TRUE, this sample is for preroll only and should not be displayed.

SetPreroll 	Sets the preroll property. If TRUE, this sample is for preroll only and should not be displayed.

GetActualDataLength 	Retrieves the data length of the sample.

SetActualDataLength 	Sets the data length of the sample.

GetMediaType 	Retrieves the media type of the sample.

SetMediaType 	Sets the media type of the sample.

IsDiscontinuity 	Indicates a discontinuity property. If S_OK is returned, sample is not contiguous with previous sample.

SetDiscontinuity 	Sets the discontinuity property. Set to TRUE if sample is new after a seek or dropped sample.

GetMediaTime 	Retrieves the media time stamps for the sample.

SetMediaTime 	Sets the media time stamps for the sample.


IMediaSample::GetActualDataLength

HRESULT GetActualDataLength(void);

Retrieves the data length of the sample.

•	Returns an HRESULT value that is the length.

Note that although this is typed as returning an HRESULT value, it actually returns the length in bytes, not an error value.


IMediaSample::GetMediaTime

HRESULT GetMediaTime(LONGLONG * pTimeStart,

    LONGLONG * pTimeEnd);

Retrieves the media time stamps for this sample.

•	Returns NOERROR if the sample contains valid time stamps. Returns VFW_E_MEDIA_TIME_NOT_SET if the time has not been set in the sample.

pTimeStart

[out] Retrieved beginning media time.

pTimeEnd

[out] Retrieved ending media time.


IMediaSample::GetMediaType

HRESULT GetMediaType(AM_MEDIA_TYPE ** ppMediaType);

Retrieves the media type of the IMediaSample object.

•	Returns an HRESULT value. When a sample is received and there is no format change, this method returns S_FALSE.

ppMediaType

[in] Pointer to a pointer to the retrieved media type.

This method allows for limited in-band format changes. Free the format block with FreeMediaType, and then free the entire media type with the Microsoft® Win32® CoTaskMemFree function.


IMediaSample::GetPointer

HRESULT GetPointer(BYTE ** ppBuffer);

Retrieves a read/write pointer to this buffer's memory.

•	Returns an HRESULT value.

ppBuffer

[out] Retrieved pointer to the buffer.


IMediaSample::GetSize

HRESULT GetSize(void);

Returns the size, in bytes, of the buffer data area.

•	Returns an HRESULT value.

Note that although this is typed as returning an HRESULT value, it actually returns the length in bytes, not an error value.


IMediaSample::GetTime

HRESULT GetTime(REFERENCE_TIME * pTimeStart,

    REFERENCE_TIME * pTimeEnd);

Retrieves the stream time at which this sample should begin and finish.

•	Returns NOERROR if the sample contains valid time stamps. Returns VFW_E_MEDIA_TIME_NOT_SET if the time has not been set in the sample.

pTimeStart

[out] Retrieved beginning stream time.

pTimeEnd

[out] Retrieved ending stream time.


IMediaSample::IsDiscontinuity

HRESULT IsDiscontinuity(void);

Determines if there is discontinuity in the data stream.

•	Returns S_OK if the sample is a discontinuous sample and S_FALSE if not; otherwise, returns an HRESULT error value.

Discontinuity occurs when a source filter seeks to a different place in the stream or when a filter drops samples for quality control.

Note that while calling SetDiscontinuity with a value of TRUE (1) sets the discontinuity property, calling IsDiscontinuity on a discontinuous sample returns S_OK (0).


IMediaSample::IsPreroll

HRESULT IsPreroll(void);

Preroll property. If TRUE, this sample is for preroll only and should not be displayed.

•	Returns S_OK if the sample is a preroll sample and S_FALSE if not; otherwise, returns an HRESULT error value. Note that while calling SetPreroll with a value of TRUE (1) sets the preroll property, calling IsPreroll on a preroll sample returns S_OK (0).


IMediaSample::IsSyncPoint

HRESULT IsSyncPoint(void);

Determines if the beginning of a sample is a synchronization point.

•	Returns S_OK if the sample is a synchronization point and S_FALSE if not; otherwise, returns an HRESULT error value.

If the bTemporalCompression member of the AM_MEDIA_TYPE structure is FALSE, all samples are synchronization points. A filter can begin a stream at any synchronization point.

Note that while calling SetSyncPoint with a value of TRUE (1) sets the synchronization point, calling IsSyncPoint on a synchronization point sample returns S_OK (0).


IMediaSample::SetActualDataLength

HRESULT SetActualDataLength(long lLen);

Sets the data length of the sample.

•	Returns an HRESULT value.

lLen

Length of the data in the media sample, in bytes.


IMediaSample::SetDiscontinuity

HRESULT SetDiscontinuity(BOOL bIsDiscontinuity);

Sets the discontinuity property.

•	Returns an HRESULT value.

bIsDiscontinuity

[in] Set to TRUE to specify the media sample as discontinuous with the previous sample.

Discontinuous samples occur when a source filter seeks to a different place in the media stream or when a filter drops samples for quality control.

Note that while calling SetDiscontinuity with a value of TRUE (1) sets the discontinuity property, calling IsDiscontinuity on a discontinuous sample returns S_OK (0).


IMediaSample::SetMediaTime

HRESULT SetMediaTime(LONGLONG * pTimeStart,

    LONGLONG * pTimeEnd);

Sets the media time stamps for this sample.

•	Returns an HRESULT value.

pTimeStart

[in] Beginning media time.

pTimeEnd

[in] Ending media time.

To reset the time, call this method with both pTimeStart and pTimeEnd set to null. This will cause IMediaSample::GetMediaTime to return an error.


IMediaSample::SetMediaType

HRESULT SetMediaType(AM_MEDIA_TYPE * pMediaType);

Sets the media type for the IMediaSample object.

•	Returns an HRESULT value.

pMediaType

Pointer to a pointer to a media type structure to be set.

This method allows for limited in-band format changes.


IMediaSample::SetPreroll

HRESULT SetPreroll(BOOL bIsPreroll);

Sets the preroll property. If TRUE, this sample is for preroll only and should not be displayed.

•	Returns an HRESULT value.

bIsPreroll

Set to TRUE to specify the media sample as a preroll sample; otherwise, set to FALSE.

Preroll samples are samples that are processed but not displayed and are located in the media stream before the displayable samples.

Note that while calling SetPreroll with a value of TRUE (1) sets the preroll property, calling IsPreroll on a preroll sample returns S_OK (0).


IMediaSample::SetSyncPoint

HRESULT SetSyncPoint(BOOL bIsSyncPoint);

Property of a synchronization point.

•	Returns S_OK.

bIsSyncPoint

[in] Set to TRUE to specify the sample as a synchronization point; otherwise, set to FALSE.

A filter can begin a stream at any synchronization point. Note that while calling SetSyncPoint with a value of TRUE (1) sets the synchronization point, calling IsSyncPoint on a synchronization point sample returns S_OK (0).


IMediaSample::SetTime

HRESULT SetTime(REFERENCE_TIME * pTimeStart,

    REFERENCE_TIME * pTimeEnd);

Sets the stream time when this sample should begin and finish.

•	Returns an HRESULT value.

pTimeStart

[in] Stream time at which the sample begins.

pTimeEnd

[in] Stream time at which the sample ends.

To reset the time, call this method with both pTimeStart and pTimeEnd set to null. This will cause IMediaSample::GetTime to return an error.


IMediaSelection Interface

Although IMediaPosition allows applications a simple seeking interface on a filter graph, it has a number of limitations. The IMediaPosition interface only allows seeking by using REFTIME time-based units; however, many filter graphs would prefer to seek on units of samples, video frames, or fields in a compressed stream. Also, the IMediaPosition interface uses separate methods to set and retrieve position properties, which can cause unnecessary filter flushing.

IMediaSelection improves on the IMediaPosition interface by allowing arbitrary formats for seekable units, called time formats. It also combines several of the operations for setting media positions into a single IMediaSelection::SetSelection method.

The IMediaSelection interface is set by using a defined time format, such as frames or samples, which then defines how parameters in IMediaSelection::SetSelection and IMediaSelection::GetCurrentPosition are interpreted. The format can be changed only when the filter graph is stopped. Only one time format is available at any given time, although calls can be freely intermixed between IMediaPosition and IMediaSelection.

IMediaPosition provides all time-based seeking, while IMediaSelection can be used for media time seeking. A filter graph stream is said to be seeked when the current position is moved forward or backward in the stream. When an application seeks a filter graph stream through IMediaPosition, all filters are seeked to that time. When seeking in media time, it only makes sense to seek a single filter, which leaves any other seekable filters at a different point in time. The filter graph manager therefore makes sure that after a media time seek, all other filters are seeked in time to the appropriate point.

When a filter is seeked in media time, it must return a time at which the media seek positioned it. For example, if a source filter is seeked to frame 30, it might return 2 seconds if the video is 15 frames per second. With that position time (of 2 seconds), the filter graph manager can then seek all the other filters to time 2 seconds so that the graph as a whole remains in sync.

Time formats are GUIDs, which are defined as follows.

GUID 	Defined as

7b785570-8c82-11cf-bc0c-00aa00ac74f6 	TIME_FORMAT_FRAME

7b785572-8c82-11cf-bc0c-00aa00ac74f6 	TIME_FORMAT_SAMPLE

7b785573-8c82-11cf-bc0c-00aa00ac74f6 	TIME_FORMAT_FIELD

When to Implement

The filter graph manager exposes the IMediaSelection interface if any of the filters within the graph are seekable (can seek to an arbitrary position in the stream). This normally means a seekable file source filter. Filters, such as a file source filter, will expose IMediaSelection if they can seek their data or if their output pin represents a seekable stream. The renderer filter should also expose this interface. Output pins of transform filters expose this interface in order to pass the positioning information upstream from the renderer through each intermediate filter to the seekable filter.

Use the CPosPassThru base class to implement this interface on output pins of transform filters that are used to pass media positioning information upstream. This is enabled by default in the pin base classes. The same class can be used by renderers, although in most cases they should use CRendererPosPassThru.

When to Use

Applications can use this interface to set or retrieve properties such as the duration of the stream, the current position, the stop time, and the media time format being used. Most commonly, an application will use the methods on this interface to play a media stream for some duration starting at some set position in the stream (for example, 10 seconds from the start).

A transform filter will call the IMediaSelection methods on the connected upstream pin when passing media times upstream from the renderer.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IMediaSelection methods 	Description

IsFormatSupported 	Determines if a specified time format is supported.

QueryPreferredFormat 	Retrieves the preferred time format to be used by the interface.

SetTimeFormat 	Sets the time format, which determines the format of units used during seeking.

GetTimeFormat 	Retrieves the current time format.

GetDuration 	Retrieves the length of time that the media stream will play.

GetCurrentPosition 	Retrieves the current position within the media stream.

GetStopPosition 	Retrieves the position within the media stream at which playback should stop.

SetSelection 	Sets the start time and end time.


IMediaSelection::GetCurrentPosition

HRESULT GetCurrentPosition(LONGLONG* pCurrent);

Retrieves the current position in terms of the total length of the media stream.

•	Returns an HRESULT value.

pCurrent

[out] Current position in current time format units.

The current position is 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 filter graph is paused, this is the position at which it will restart.

When the filter graph is stopped or paused, this method returns the position at which playback will recommence. When the filter graph is running, the filter graph manager returns the position according to the data arriving at the renderer. If an individual filter implements this method, it should return the media 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 there has been an IMediaSelection::SetSelection call in the meantime to reset the start position.


IMediaSelection::GetDuration

HRESULT GetDuration(LONGLONG* pDuration);

Retrieves the length of time that the media stream will play.

•	Returns an HRESULT value.

pDuration

[out] Returned length of the media stream.

The duration assumes normal playback speed, and it is therefore unaffected by the rate. Although IMediaSelection allows filters to be seeked in media time, it still requires that the media samples it sends downstream are time stamped appropriately. Therefore, a filter that implements IMediaSelection may also implement IMediaPosition if it can be seeked in time. The rate can be set only through IMediaPosition.


IMediaSelection::GetStopPosition

HRESULT GetStopPosition(LONGLONG* pStop);

Retrieves the time at which the media stream stops.

•	Returns an HRESULT value.

pStop

[out] Returned stop time.

The stop position is a time 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.


IMediaSelection::GetTimeFormat

HRESULT GetTimeFormat(const GUID Format);

Sets the media time format, which determines the format of units used during seeking.

•	Returns an HRESULT value.

Format

[out] Time format currently supported by this interface.

See the IsFormatSupported method for a list of time formats. Note that the filter graph must be stopped before calling this method or a VFW_E_WRONG_STATE error will be returned. Only one time format can be set on the filter graph at any one time, although calls to IMediaPosition and IMediaSelection can be freely intermixed.


IMediaSelection::IsFormatSupported

HRESULT IsFormatSupported(const GUID Format);

Determines if a specified time format is supported.

•	Returns S_OK if the time format is supported; otherwise, returns S_FALSE.

Format

[in] Time format to compare.

Time formats are defined as follows.

GUID 	Defined as

TIME_FORMAT_FRAME 	Seeks to specific video frames.

TIME_FORMAT_SAMPLE 	Seeks to samples in the stream.

TIME_FORMAT_FIELD 	Seeks to interlaced video fields.


IMediaSelection::QueryPreferredFormat

HRESULT QueryPreferredFormat(GUID *pFormat);

Retrieves the preferred time format to be used by the interface.

•	Returns an HRESULT value.

pFormat

[out] Time format preferred by the interface.

See the description for IsFormatSupported for a list of available time formats. If the time format returned is not satisfactory, use the IsFormatSupported method to query for supported time formats that you can use.


IMediaSelection::SetSelection

HRESULT SetSelection(LONGLONG Current,

    LONGLONG Stop, REFTIME pTime);

Sets the time that the media stream begins and stops.

•	Returns an HRESULT value.

Current

[in] Start time expressed as a LONGLONG value.

Stop

[in] Stop time expressed as a LONGLONG value.

pTime

[out] Stream time implied by the current media position.

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.

If this method is called when the filter graph manager is running, the filter graph manager will pause the graph, execute the method, and then issue a new run command.

If called when the filter graph is paused, this method needs to flush existing data, using IPin::BeginFlush and IPin::EndFlush, before pushing the new data (at the new current position). 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. Once the downstream filters have been flushed, a filter is obliged to send a new segment call, IPin::NewSegment.

The filter, once seeked, must also return the time it was seeked to in the pTime parameter. So if the media is a 100-frame video sequence of 15 frames per second, and the selection was to start at frame 30 and stop at frame 40, the filter should return 2 seconds as the time it was seeked to. The filter graph manager needs this information to keep all the other seekable filters in the filter graph in sync.


IMediaSelection::SetTimeFormat

HRESULT SetTimeFormat(const GUID Format);

Sets the time format, which determines the format of units used during seeking.

•	Returns an HRESULT value.

Format

[in] Time format to be supported by this interface.

See the IsFormatSupported method for a list of time formats. Note that the filter graph must be stopped before calling this method or a VFW_E_WRONG_STATE error will be returned.


IMediaTypeInfo Interface

The filter graph manager exposes the IMediaTypeInfo interface to allow access by OLE Automation client applications such as Microsoft® Visual Basic® to the media type information associated with pins on filters.

When to Implement

This interface is implemented by the filter graph manager for use by OLE Automation client applications, such as Microsoft Visual Basic.

When to Use

OLE Automation-compatible applications retrieve an object supporting this interface by calling the IPinInfo::get_ConnectionMediaType method. This interface then presents the major and minor media types as properties on an IMediaTypeInfo object.

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.

IMediaTypeInfo methods 	Description

get_Type 	Retrieves the major type GUID as a string.

get_Subtype 	Retrieves the subtype GUID as a string.


IMediaTypeInfo::get_Subtype

HRESULT get_Subtype(BSTR *strType);

Retrieves the subtype GUID as a string.

•	Returns an HRESULT value.

strType

[out, retval] A string containing the subtype GUID.


IMediaTypeInfo::get_Type

HRESULT get_Type(BSTR *strType);

Retrieves the major type GUID as a string.

•	Returns an HRESULT value.

strType

[out, retval] String containing the major type GUID.


IMemAllocator Interface

The IMemAllocator interface allocates IMediaSample blocks to be used for data transfer between pins. The blocks can be provided by the input pin, output pin, or a third party. Release the IMediaSample object by calling the IUnknown::Release method.

When to Implement

Implement this interface if you are providing a buffer for media samples. This is typically done by filters that originate, copy, or provide a destination for the media stream. For example, a source filter provides an allocator corresponding to the incoming media, and a renderer filter provides an allocator corresponding to the hardware memory (DirectX™, for example). Intermediate transform filters may create their own allocator if copying samples and not writing directly to the renderer's allocator. Use the CBaseAllocator class to implement the IMemAllocator interface.

When to Use

Filters use this interface when retrieving or sending media samples. The allocator used may actually belong to a filter further upstream or downstream than the next filter, because many filters choose to pass the allocators through and simply modify the data in place.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IMemAllocator methods 	Description

SetProperties 	Specifies a desired number of blocks, size of the blocks, and block alignment figure. This method returns the actual values for the same.

GetProperties 	Determines the size, number, and alignment of blocks.

Commit 	Commits the memory for the specified buffers.

Decommit 	Releases the memory for the specified buffers.

GetBuffer 	Retrieves a container for a sample.

ReleaseBuffer 	Releases a container for a sample.


IMemAllocator::Commit

HRESULT Commit(void);

Commits the memory for the specified buffers.

•	Returns an HRESULT value.

The IMemAllocator::SetProperties method must be called before calling this method. The IMemAllocator::GetBuffer method fails if it is called before this method.


IMemAllocator::Decommit

HRESULT Decommit(void);

Releases the memory for the specified buffers.

•	Returns an HRESULT value.

Any threads waiting in the IMemAllocator::GetBuffer method return with an error after this method is called. The IMemAllocator::GetBuffer method fails if it is called before the IMemAllocator::Commit method or after this method.


IMemAllocator::GetBuffer

HRESULT GetBuffer(IMediaSample ** ppBuffer

    REFERENCE_TIME * pStartTime, REFERENCE_TIME * pEndTime,

    DWORD dwFlags);

Retrieves a container for a sample.

•	Returns an HRESULT value.

ppBuffer

[out] Pointer to a retrieved media sample buffer.

pStartTime

[in] Either NULL or set to the beginning time of the sample to retrieve. Only the video renderer uses this.

pEndTime

[in] Either NULL or set to the ending time of the sample to retrieve. Only the video renderer uses this.

dwFlags

[in] The following flags are supported.

AM_GBF_PREVFRAMESKIPPED 	Set to TRUE if this sample is the first after a discontinuity. Only the video renderer uses this.

AM_GBF_NOTASYNCPOINT 	Dynamic format changes are not allowed on this buffer because it is not a key frame.

IMemAllocator::GetBuffer is a locking, synchronous method to get the next free buffer. Upon return, the properties are invalid, but the buffer pointer and size are correct. This method succeeds only if memory has been committed. GetBuffer returns with an error value if it is blocked waiting for a buffer and the IMemAllocator::Decommit method is called on another thread.


IMemAllocator::GetProperties

HRESULT GetProperties(ALLOCATOR_PROPERTIES * pProps);

Returns the properties being used on this allocator.

•	Returns an HRESULT value.

pProps

[out] Allocator properties.

Calls to this method need not succeed until the IMemAllocator::Commit method is called.


IMemAllocator::ReleaseBuffer

HRESULT ReleaseBuffer(IMediaSample *pBuffer);

Releases the CMediaSample object.

•	Returns an HRESULT value.

pBuffer

[in] Buffer to release.


IMemAllocator::SetProperties

HRESULT SetProperties(ALLOCATOR_PROPERTIES * pRequest,

    ALLOCATOR_PROPERTIES * pActual);

Determines the size, number, and alignment of blocks.

•	Returns an HRESULT value.

pRequest

[in] Requested allocator properties.

pActual

[out] Allocator properties actually set.

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 method cannot be called unless the allocator has been decommitted using the IMemAllocator::Decommit method.

This method assumes that blocks are all the same size.


IMemInputPin Interface

The IMemInputPin interface provides methods on an input pin to facilitate passing data and flush notifications from a connected output pin of an upstream filter.

When to Implement

Implement this interface on the input pin of every filter. The CBaseInputPin class implements this interface.

When to Use

A connected output pin uses this interface to retrieve an IMemAllocator interface, to pass media samples to the input pin, and to flush pending buffers downstream.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IMemInputPin methods 	Description

GetAllocator 	Returns the allocator interface that this input pin proposes as the interface for the output pin to use.

NotifyAllocator 	Notifies the input pin as to which allocator the output pin is actually going to use.

GetAllocatorRequirements 	Optional method to use if the filter has specific alignment or prefix requirements but could use an upstream allocator.

Receive 	Receives the next block of data from the stream.

ReceiveMultiple 	Receives the next block of data from the stream. This method behaves similarly to the IMemInputPin::Receive method, but it works with multiple samples.

ReceiveCanBlock 	Determines if sending the IMemInputPin::Receive method might block.


IMemInputPin::GetAllocator

HRESULT GetAllocator(IMemAllocator ** ppAllocator);

Returns the allocator interface that this input pin proposes as the interface for the output pin to use.

•	Returns an HRESULT value.

ppAllocator

[out] Pointer to an obtained IMemAllocator object.


IMemInputPin::GetAllocatorRequirements

HRESULT GetAllocatorRequirements(

    ALLOCATOR_PROPERTIES * pProps);

Optional method to use if the filter has specific alignment or prefix requirements but could use an upstream allocator.

•	Returns an HRESULT value. Returns E_NOTIMPL if not implemented.

pProps

[in] ALLOCATOR_PROPERTIES structure containing the required size, count, and alignment of the allocator.


IMemInputPin::NotifyAllocator

HRESULT NotifyAllocator(IMemAllocator * pAllocator,

    BOOL bReadOnly);

Notifies the input pin as to which allocator the output pin is actually going to use.

•	Returns an HRESULT value.

pAllocator

[in] Pointer to the IMemAllocator object to use. This may or may not be the same IMemAllocator object that the input pin provided in the IMemInputPin::GetAllocator method (the output pin could provide its own allocator).

bReadOnly

[out] Flag to indicate if the samples from this allocator are read-only.

This method is called by the connecting output pin to notify the pin on which this interface is implemented of the allocator it chooses to use for transporting media samples. If the bReadOnly parameter is TRUE, all samples in the allocator are read-only and a copy must be made before modifying any of them.


IMemInputPin::Receive

HRESULT Receive(IMediaSample * pSample);

Receives the next block of data from the stream.

•	Returns an HRESULT value.

pSample

[in] Pointer to a media sample.

This is a blocking synchronous call. Typically, no blocking occurs, but if a filter cannot process the sample immediately it may use the calling application's thread to wait until it can.

Call the IUnknown::AddRef method if you need to hold the returned data block beyond the completion of the IMemInputPin::Receive method. If you call AddRef, be sure to call IUnknown::Release when done with it.


IMemInputPin::ReceiveCanBlock

HRESULT ReceiveCanBlock(void);

Determines if the implementation of the IMemInputPin::Receive method might block on the connected output pin.

•	Can return any HRESULT value. The following specific success values can be returned.

Value 	Meaning

S_FALSE 	Input pin will not block on a Receive method.

S_OK 	Input pin may block on a Receive method.

An output pin from a filter might require notification if its thread might be blocked when it calls the Receive method on the connected input pin. For example, a source filter might prefer to keep reading and buffering data rather than to be blocked, and may choose to start another thread to wait on the blocking Receive method.

If your implementation of Receive calls a downstream filter's Receive method on the same thread, the application will block if that filter blocks, and this method must indicate this.


IMemInputPin::ReceiveMultiple

HRESULT ReceiveMultiple(IMediaSample ** pSamples,

    long nSamples, long * nSamplesProcessed);

Returns the next block of data from the stream. This method behaves much like the IMemInputPin::Receive method, but it works with multiple samples.

•	Returns an HRESULT value.

pSamples

[in] Pointer to an array of samples.

nSamples

[in] Number of samples to process.

nSamplesProcessed

[out] Number of samples processed.

This method allows a connected output pin to deliver multiple samples at one time. Use it if, like COutputQueue, the output pin batches samples for delivery together. Implement this if your filter can handle batched samples more efficiently than individual samples. The base class implementation of this method simply calls IMemInputPin::Receive repeatedly. Override this implementation if you can do something more efficiently in your derived class.


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.

When to Implement

This interface is implemented on the Microsoft® ActiveMovie™ video renderer filter. It may 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 call methods on the IOverlayNotify interface of the filter doing the drawing with notifications of video property changes.

The window-based renderer in ActiveMovie supports both IMemInputPin and IOverlay interfaces. These two interfaces are mutually exclusive. A filter selects 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 call successfully the IOverlay interface. If it connects with any other video formats (such as MEDIASUBTYPE_RGB8), trying to call through IOverlay returns VFW_E_NO_OVERLAY_CONNECTION.

When to Use

Call the methods on this function from an upstream filter that needs to 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

HRESULT Advise(IOverlayNotify * pOverlayNotify,

    DWORD dwInterests);

Sets up an advise link for the overlay events specified by the dwInterests parameter.

pOverlayNotify

[in] Notification interface.

dwInterests

[in] Callbacks of interest, which can be any subset of the following events:

Event 	Meaning

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_ALL 	All of the above.

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. An advise link can be canceled by calling IOverlay::Unadvise.


IOverlay::GetClipList

HRESULT GetClipList(RECT * pSourceRect,

    RECT * pDestinationRect, RGNDATA ** ppRgnData);

Retrieves the clipping list.

pSourceRect

[out] Bounding client rectangle.

pDestinationRect

[in] Destination rectangle.

ppRgnData

[out] Header and data describing clipping. If successful, the Microsoft Win32® CoTaskMemFree function should free memory.

The IOverlay implementation allocates the memory for the clipping rectangles, as it can be variable in length. The filter calling this method should free the memory (using CoTaskMemFree) when it is finished with it.


IOverlay::GetColorKey

HRESULT GetColorKey(COLORKEY * pColorKey);

Retrieves the current color key used for chroma keying.

pColorKey

[out] Pointer to where the current color key for chroma keying is copied.

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

HRESULT GetDefaultColorKey(COLORKEY * pColorKey);

Retrieves the default color key used for a chroma key overlay.

•	Returns an HRESULT value.

pColorKey

[out] Pointer to where the default color key is copied.

A filter using color keys can get a default color from the video renderer. The default color key may 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

HRESULT GetPalette(DWORD * pdwColors,

    PALETTEENTRY ** ppPalette);

Retrieves the current system palette.

•	Returns an HRESULT value.

pdwColors

[out] Number of colors present.

ppPalette

[out] Retrieved palette structure.


IOverlay::GetVideoPosition

HRESULT GetVideoPosition([out] RECT *pSourceRect,

    [out] RECT *pDestinationRect);

Retrieves the current video source and destination rectangles.

•	Returns an HRESULT value.

pSourceRect

[out] Bounding video client rectangle.

pDestinationRect

[in] Destination video rectangle.


IOverlay::GetWindowHandle

HRESULT GetWindowHandle(HWND *pHwnd);

Retrieves the current window handle.

•	Returns a pointer to the window handle.

pHwnd

[out] Window handle.


IOverlay::SetColorKey

HRESULT SetColorKey(COLORKEY * pColorKey);

Changes the color key.

•	Returns an HRESULT value.

pColorKey

[out] Pointer to the color key value to be set. If successful, the actual color key value selected is copied to this parameter.

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 may be uninstalled by requesting a color key with the CK_NOCOLORKEY flag. Likewise, any palette installed through SetPalette may 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

HRESULT SetPalette(DWORD dwColors,

    PALETTEENTRY * pPalette);

Sets the palette.

•	Returns an HRESULT value.

dwColors

[in] Number of colors present.

pPalette

[in] Colors to use for the palette.

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.


IOverlay::Unadvise

HRESULT Unadvise();

Terminates the advise link established with the IOverlayNotify interface.

•	Returns an HRESULT value.

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.

When to Implement

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 IOverlay::Advise 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.

When to Use

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 call 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 visible region of the window has changed.

OnColorKeyChange 	Provides notification that the chroma key has changed.

OnPositionChange 	Provides notification that the position has changed.


IOverlayNotify::OnClipChange

HRESULT OnClipChange(RECT *pSourceRect,

    RECT *pDestinationRect, RGNDATA *pRgnData);

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.

•	Returns an HRESULT value.

pSourceRect

[in] Region of the video to use.

pDestinationRect

[in] Video destination.

pRgnData

[in] Clipping information.

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. The filter must take a copy of the information if it needs to store it.


IOverlayNotify::OnColorKeyChange

HRESULT OnColorKeyChange(COLORKEY * pColorKey);

Provides notification that the window's color key has changed.

•	Returns an HRESULT value.

pColorKey

[in] Defines the new chroma key.


IOverlayNotify::OnPaletteChange

HRESULT OnPaletteChange(DWORD dwColors,

    const PALETTEENTRY * pPalette);

Provides notification that the palette of the window has changed.

•	Returns an HRESULT value.

dwColors

[in] Number of colors present.

pPalette

[in] Array of palette colors.

Before returning, the filter should copy the array of RGBQUAD values, if necessary.


IOverlayNotify::OnPositionChange

HRESULT OnPositionChange(const RECT *pSourceRect,

    const RECT *pDestinationRect);

Provides notification that the position has changed.

•	Returns an HRESULT value.

pSourceRect

[in] Source video rectangle.

pDestinationRect

[in] Destination video rectangle. Note that this is not clipped to the visible display area.

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.


IPin Interface

The IPin interface represents a single, unidirectional connection point on a filter. A pin connects to exactly one other pin on another filter. Other objects can call this interface on this pin. The interface between the filter and the pin is private to the implementation of a specific filter.

During the connection process, one pin takes the lead. The base classes assume that this is the output pin of the upstream connecting filter. The filter graph manager calls the IPin::Connect method on this pin's IPin interface, passing the IPin pointer for the connecting pin. This connecting pin then calls the IPin::ReceiveConnection method located on the other pin, in addition to its format-enumeration, IUnknown::QueryInterface and possibly IPin::QueryAccept methods, to establish whether the connection is possible.

When to Implement

All filters must implement this interface on each of its pins. Which methods are implemented depends on whether the pin is an input pin or an output pin. Use the CBasePin, CBaseInputPin, or CBaseOutputPin class, or classes derived from these classes, to implement this interface.

When to Use

This interface is used by other connecting pins and by the filter graph manager. Applications should not use this interface directly but should go through the filter graph manager. Connecting pins use the IPin interface on the opposite pin to negotiate a common media type and an agreed allocator to use for passing samples.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.

IPin methods 	Description

Connect 	Makes a connection to another pin.

ReceiveConnection 	Makes a connection to this pin and is called by a connecting pin.

Disconnect 	Breaks a connection.

ConnectedTo 	Returns a pointer to the connecting pin.

ConnectionMediaType 	Returns the media type of this pin's connection.

QueryPinInfo 	Retrieves information about this pin (for example, the name, owning filter, and direction).

QueryId 	Retrieves an identifier for the pin.

QueryAccept 	Queries whether a given media type is acceptable by the pin.

EnumMediaTypes 	Provides an enumerator for this pin's preferred media types.

QueryInternalConnections 	Provides an array of the pins to which this pin internally connects.

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.

NewSegment 	Specifies that samples following this call are grouped as a segment with a given start time, stop time, and rate.

QueryDirection 	Retrieves the direction for this pin.


IPin::BeginFlush

HRESULT BeginFlush(void);

Informs the pin to begin a flush operation.

•	Returns an HRESULT value.

When this method is called, the pin is entering flush state. In this case, carry out the following steps:

1	Set a flushing flag to prevent any more IMemInputPin::Receive methods from succeeding.

2	Discard any queued data.

3	Free the pin if it was blocked by the Receive method, if possible.

4	Pass the IPin::BeginFlush method to any downstream pins.

The BeginFlush notification is passed downstream until it reaches the renderer, which must free any output pin connected to its input pin (usually in the IMemAllocator::GetBuffer method). This unblocks other pins and allows them to be freed.

After BeginFlush is called, all samples passed by the Receive method to the pin, or on another transport, are rejected with S_FALSE until the IPin::EndFlush method is called.

This method is implemented in the base classes by CBaseInputPin::BeginFlush.


IPin::Connect

HRESULT Connect(IPin * pReceivePin,

    const AM_MEDIA_TYPE * pmt);

Initiates a connection from this pin to the other pin.

•	Returns an HRESULT value.

pReceivePin

[in] Other pin to connect to.

pmt

[in] Type to use for the connections (optional).

This method calls the IPin::ReceiveConnection method for the other pin. The IPin::Connect method verifies that the connection is possible and may reject it. This pin proposes a media type to the other pin.

This method is implemented in the base classes by CBasePin::Connect.

Applications should not call this method. Instead, call IFilterGraph::ConnectDirect, which will call this method. Changing connections underneath the filter graph manager can cause commands to be distributed incorrectly and can cause a deadlock.


IPin::ConnectedTo

HRESULT ConnectedTo(IPin ** ppPin);

If this pin is connected to another pin, the IPin::ConnectedTo method returns a pointer to that pin.

•	Returns an HRESULT value.

ppPin

[out] Pointer to an IPin pointer to the IPin interface of the other pin (if any) to which this pin is connected. If there is no connection, the other pin interface pointer will be NULL.

This method is implemented in the base classes by CBasePin::ConnectedTo. The interface returned by this method has had its reference count incremented. Be sure to call IUnknown::Release on the interface to decrement the reference count when you have finished using the interface.


IPin::ConnectionMediaType

HRESULT ConnectionMediaType(AM_MEDIA_TYPE *pmt);

Determines the media type associated with the current connection of the pin. This method fails if the pin is unconnected.

•	Returns an HRESULT value.

pmt

[out] Pointer to an AM_MEDIA_TYPE structure. If the pin is connected, the media type is returned. Otherwise, the structure is initialized to a default state in which all elements are 0, with the exception of lSampleSize, which is set to 1, and bFixedSizeSamples, which is set to TRUE.

The returned structure can contain an allocated format block and a reference-counted IUnknown interface pointer. These resources should be released by calling the FreeMediaType utility function.

This method is implemented in the base classes by CBasePin::ConnectionMediaType.


IPin::Disconnect

HRESULT Disconnect(void);

Breaks a connection.

•	Returns NOERROR if there is no connection.

There are no parameters because there is only one possible connection on this pin.

This method is implemented in the base classes by CBasePin::Disconnect.

A pin should never use this method to disconnect from its peer. An application should not call this method. Use IFilterGraph::Disconnect instead.


IPin::EndFlush

HRESULT EndFlush(void);

Informs the pin to end a flush operation.

•	Returns an HRESULT value.

When this method is called, the pin is beginning to end a flush operation. It should perform the following steps:

1	Ensure that your filter will not push any additional data. (To do this, synchronize with a thread, stop it pushing, and discard any queued data.)

2	Reenable the IMemInputPin::Receive method by clearing the internal flushing flag.

3	Pass the EndFlush method downstream by calling the method on the connecting input pin.

This method is implemented in the base classes by CBaseInputPin::EndFlush.


IPin::EndOfStream

HRESULT EndOfStream(void);

Informs the input pin that no additional data is expected until a new run command is issued.

•	Returns one of the following HRESULT values.

Value 	Meaning

S_OK 	No error occurred.

E_UNEXPECTED 	Method was probably called on an output pin that does not support this.

Calling this method notifies the pin that no additional data is expected until a new run command is issued. The end-of-stream notification should be queued and delivered after all queued data is delivered. It can be delivered immediately if there is no queued data.

The IPin::BeginFlush method flushes any queued end-of-stream notifications. This is intended for input pins only.

This method is implemented in the base classes by CBaseOutputPin::EndOfStream.


IPin::EnumMediaTypes

HRESULT EnumMediaTypes(IEnumMediaTypes ** ppEnum);

Provides an enumerator for this pin's preferred media types.

•	Returns an HRESULT value.

ppEnum

[out] Pointer to an enumerator for the media types.

If an enumerator is received, it must be released when the operation is finished.

This method is implemented in the base classes by CBasePin::EnumMediaTypes.


IPin::NewSegment

HRESULT NewSegment(REFERENCE_TIME tStart,

    REFERENCE_TIME tStop, double dRate);

Specifies that samples following this method are grouped as a segment with a given start time, stop time, and rate.

•	Returns an HRESULT value.

tStart

[in] Start time of the segment.

tStop

[in] Stop time of the segment.

dRate

[in] Rate of the segment.

This method allows filters that process buffers containing more than one sample to delineate the rendering of the samples between start and stop time, as indicated by the tStart and tStop parameters.

This method is intended to be implemented on an input pin. A connected output pin on the upstream filter calls this method after completing delivery of previous data and before calling IMemInputPin::Receive with any new data. It indicates that all data arriving after this call is part of a segment delineated by the parameters.


IPin::QueryAccept

HRESULT QueryAccept(const AM_MEDIA_TYPE * pmt);

Determines if the pin could accept the format type.

•	Returns S_OK if the format is acceptable; otherwise, returns S_FALSE.

pmt

[in] Pointer to a proposed media type.

This method is implemented in the base classes by CBasePin::QueryAccept.


IPin::QueryDirection

HRESULT QueryDirection(PIN_DIRECTION * pPinDir);

Retrieves the direction for this pin.

•	Returns an HRESULT value.

pPinDir

[out] Pointer to a PIN_DIRECTION variable.

The returned pPinDir parameter will contain PINDIR_INPUT if the pin is an input pin or PINDIR_OUTPUT otherwise. The same information is available by using QueryPinInfo, but this method is more direct and more efficient.


IPin::QueryId

HRESULT QueryId(LPWSTR * Id);

Retrieves an identifier for the pin.

•	Returns an HRESULT value.

Id

[out] Pin identifier.

This method and the IFilter::FindPin method allow connections in a filter graph to be saved and restored. Because pins are identified only by their IPin interface pointers at run time, and pointer information cannot be reliably saved, an identifier is necessary to specify which pins belong to each filter. The implementation of this method by the pin provides a unique name that the filter graph manager can use to turn into an IPin interface pointer by calling IFilter::FindPin when the filter graph is restored.

The storage is allocated by the filter using the Microsoft® Win32® CoTaskMemAlloc function. The caller should free it by using CoTaskMemFree.

This method is implemented in the base classes by CBasePin::QueryId.


IPin::QueryInternalConnections

HRESULT QueryInternalConnections(IPin ** apPin,

    ULONG * nPin);

Provides an array of pointers to the IPin interface of the pins to which this pin internally connects.

•	Returns one of the following HRESULT values.

Value 	Meaning

E_FAIL 	Undetermined.

S_FALSE 	Insufficient number of array elements to return all the results, in which case no pins are returned in the apPin array.

E_NOTIMPL 	Filter graph manager interprets E_NOTIMPL as meaning that any input pin connects to all visible output pins, and vice versa.

apPin

[out] Array of IPin pointers.

nPin

[out] Upon input, indicates the number of array elements; upon output, indicates the number of pins.

All pins put in the array are added by the IUnknown::AddRef method. The apPin parameter can be NULL if the nPin parameter is equal to zero. This allows the calling application to determine the number of required arrays.

This method is implemented in the base classes by CBasePin::QueryInternalConnections.


IPin::QueryPinInfo

HRESULT QueryPinInfo(PIN_INFO * pInfo);

Retrieves information about the pin.

•	Returns an HRESULT value.

pInfo

[out] Pointer to a PIN_INFO structure that specifies the name of the pin, a pointer to an IFilter interface on its owning filter, and the direction of the pin.

Unlike the pin name in the IPin::QueryId method, which is used by the filter graph manager, the name in the PIN_INFO structure is intended to be read by users.

Note that on return, the pFilter member of PIN_INFO has an outstanding reference count if it is non-null, and therefore should be released when the interface is no longer needed.


IPin::ReceiveConnection

HRESULT ReceiveConnection(IPin * pConnector,

    AM_MEDIA_TYPE *pmt);

Makes a connection to the calling pin.

•	Returns an HRESULT value.

pConnector

[in] Connecting pin.

pmt

[in] Media type of the samples to be streamed.

This method is intended for input pins only. Output pins should implement this to return an error. The pin should verify that it accepts the media type passed to it and return S_OK if so.

This method is implemented in the base classes by CBasePin::ReceiveConnection.


IPinInfo Interface

The filter graph manager exposes the IPinInfo interface, which allows access to pin information such as the media type and the pin direction. It also allows control of pins; for example, connecting and disconnecting pins and rendering a filter graph for a pin's media type.

When to Implement

This interface is implemented by the filter graph manager for use by OLE Automation client applications, such as Microsoft® Visual Basic®.

When to Use

Applications that do not have access to the IFilterGraph or IGraphBuilder interface use this interface to retrieve pin information, to connect and disconnect pins, and to have the filter graph manager automatically generate filter graphs given the output pin of a source filter.

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.

IPinInfo methods 	Description

get_Pin 	Retrieves the pin object that supports the IPin interface.

get_ConnectedTo 	Retrieves the IPinInfo object for the pin to which the filter 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 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 from its connected pin.

Render 	Creates a filter graph capable of rendering the pin's media type.


IPinInfo::Connect

HRESULT Connect(IUnknown *pPin);

Connects to the pin using other transform filters as necessary.

•	Returns an HRESULT value.

pPin

[in] The pin to connect with.

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.


IPinInfo::ConnectDirect

HRESULT ConnectDirect(IUnknown *pPin);

Connects directly to the given pin, not using any intermediate filters.

•	Returns an HRESULT value.

pPin

[in] The pin to connect directly to.

This method will return an error if a common media type for the connecting pins cannot be agreed upon. This method is essentially an OLE Automation wrapper for the IFilterGraph::ConnectDirect method.


IPinInfo::ConnectWithType

HRESULT ConnectWithType(IUnknown *pPin,

    IDispatch *pMediaType);

Connects directly to the specified pin by using the specified media type.

•	Returns an HRESULT value.

pPin

[in] The pin to connect to. pPin is an object that must support either the IPin or the IPinInfo interface.

pMediaType

[in] The media type the pin is connecting with. pMediaType must support the IMediaTypeInfo interface.

This method allows you to determine exactly what media type you want the connection to be made with, rather than letting the pins decide the media type upon connection.


IPinInfo::Disconnect

HRESULT Disconnect(void);

Disconnects this pin from its connected pin.

•	Returns an HRESULT value.

This method calls IPin::Disconnect on both pins.


IPinInfo::get_ConnectedTo

HRESULT get_ConnectedTo(IDispatch **ppUnk);

Retrieves the IPinInfo interface for the connected pin.

•	Returns an HRESULT value.

ppUnk

[out, retval] The IPinInfo interface for the pin.

This method is essentially an OLE Automation wrapper for the IPin::ConnectedTo method.


IPinInfo::get_ConnectionMediaType

HRESULT get_ConnectionMediaType(IDispatch **ppUnk);

Retrieves the IMediaTypeInfo object containing the connection information.

•	Returns an HRESULT value.

ppUnk

[out, retval] The returned IMediaTypeInfo interface.

This method is essentially an OLE Automation wrapper for the IPin::ConnectionMediaType method.


IPinInfo::get_Direction

HRESULT get_Direction(LONG *ppDirection);

Retrieves the pin direction.

•	Returns an HRESULT value.

ppDirection

[out, retval] The pin direction; either PINDIR_INPUT or PINDIR_OUTPUT.


IPinInfo::get_FilterInfo

HRESULT get_FilterInfo(IDispatch **ppUnk);

Retrieves the IFilterInfo interface for the filter to which this pin belongs.

•	Returns an HRESULT value.

ppUnk

[out, retval] The retrieved IFilterInfo interface.


IPinInfo::get_MediaTypes

HRESULT get_MediaTypes(IDispatch **ppUnk);

Retrieves an IAMCollection interface providing access to the preferred media types supported by this pin.

•	Returns an HRESULT value.

ppUnk

[out, retval] The IAMCollection interface containing the preferred media types as IMediaTypeInfo objects.

This method is essentially an OLE Automation wrapper for the IPin::EnumMediaTypes method.


IPinInfo::get_Name

HRESULT get_Name(BSTR **ppUnk);

Retrieves the name of this pin.

•	Returns an HRESULT value.

ppUnk

[out, retval] The name of the pin.


IPinInfo::get_Pin

HRESULT get_Pin(IUnknown **ppUnk);

Retrieves the pin object that supports the IPin interface.

•	Returns an HRESULT value.

ppUnk

[out, retval] The IUnknown object that supports IPin.


IPinInfo::get_PinID

HRESULT get_PinID(BSTR *strPinID);

Retrieves the pin identifier.

•	Returns an HRESULT value.

strPinID

[out, retval] The pin identifier string.

The returned strPinID string can be passed to IFilterInfo::FindPin. This is often the same as the name of the pin, but may be some other value.


IPinInfo::Render

HRESULT Render(void);

Builds a filter graph capable of rendering the media type belonging to this source filter output pin using any necessary transform and rendering filters.

•	Returns an HRESULT value.

This method is essentially an OLE Automation wrapper for the IGraphBuilder::Render method. This method is valid only on source filter output pins.


IQualityControl Interface

The IQualityControl interface defines quality messages and allows a quality manager to install itself as the sink for these messages. The following structures are defined for quality management:

•	QualityMessageType

•	Quality

The IQualityControl::Notify method receives a Quality message. A filter may call IQualityControl::Notify to send a Quality message to another filter to ask for help in managing the quality of the graph (typically to achieve graceful degradation on a processor that is not powerful enough to handle all the data). Quality messages usually flow upstream.

The IQualityControl::SetSink method tells a filter where to send it. If no sink has been explicitly set or if the last SetSink set the sink to NULL, the message should go upstream. The filter sends a message upstream by calling QueryInterface on the output pin to which its input pin is connected in order to retrieve an IQualityControl interface. Filters export the IQualityControl interface through their pins.

Messages start with rendering filters, because these must run in real time. Other filters must run so as to keep the renderers supplied; these do not originate messages, but they may pass them on.

If a filter receives a quality message, it returns S_OK if it agrees to act on the quality message to handle the situation, or S_FALSE if it cannot handle it. For example, if the video renderer receives S_FALSE (or failure codes), it will readily drop frames to try to maintain synchronization. If it receives S_OK, it will trust the upstream filter; it also will allow frames to be played much earlier than their due time and will allow frames to be played much later without dropping them. Normally the video renderer causes early frames to be blocked until their due time. But if this is the first frame after a dropped frame, the video renderer will play the frame as soon as possible so as not to lose time.

A reasonable implementation for a filter that cannot handle a message is to pass the message upstream and to pass on the result. For example:

HRESULT Notify(IFilter * pSelf, QualityMessage qm)

{

    if (m_QualitySink!=NULL)

        // note how pSelf has changed into Myself

        return m_QualitySink->ChangeQuality(pMyself, qm);

    else

        return  m_Upstream->Notify(pMyself, qm);

}

A quality managing component would typically set the sink for all filters to itself. It can identify filters by their IFilter interface pointers in the Self parameters. A filter must always supply the same value for its IFilter interface. (The official COM way of determining if two filters are the same is to call QueryInterface on them both for their IUnknown interfaces and compare those. However, because ActiveMovie™ is a real-time system and because these calls are made during streaming, it is implemented this way for efficiency.)

A quality managing component (for example, an application) typically returns S_OK when called upon to help. However, it should be prepared to find that when it sends a message to a filter requesting help from that filter, it immediately gets a request from that filter for help, and that whatever return code it gives to that filter in response to the request immediately comes back from the filter as the reply to its original message. This happens if the filter uses the suggested default implementation of passing the messages upstream, but with the Quality managing component intercepting all the traffic.

The Quality message structure is:

typedef enum {

    Famine,

    Flood

} QualityMessageType;

typedef struct {

    QualityMessageType Type;

    long               Proportion;

    REFERENCE_TIME     Late;

} Quality;

The Type member of the structure indicates which filter appears to have the problem. If set to Famine, it indicates that the renderer is not getting enough samples and the receiver of the message should speed up by any means possible. If set to Flood, the sender of the message cannot keep up with the data being sent and the receiver must send less data. Other methods of degradation are not appropriate.

The Proportion member gives a rate (expressed in parts per thousand) to be used by a recipient that cannot seek (dropping frames is equivalent to seeking) but can only control its rate. For example, a proportion of 823 means that it should degrade enough to go faster by a factor of 1000/823. Likewise, a proportion of 1200 means that it can improve its quality by 20 percent, even if this results in going slower. The numbers are not cumulative. In particular, if a filter can only degrade in steps of, say, 20 percent, and if it receives a series of Quality messages all with Proportion equal to 990, it should ignore them all. It should not multiply them (for example, it should not deduce that a 20 percent reduction is called for after the 23rd message in this case).

The Late member says how late the application is running at the moment. Negative values mean that there is some slack (probably the renderer is waiting for this time before rendering the samples). A positive value from an audio renderer does not necessarily mean that there is an audio break; it means that the audio renderer's buffer queue is running low and is heading for a break.

When to Implement

Pins that are required to pass quality control messages upstream must implement this interface. The CBasePin class inherits IQualityControl and provides a pass-through implementation for output pins. Any filter that can act upon a quality control message to adjust the rate of data flow should implement this interface. Any quality management component external to the filter graph should implement this interface in order to receive quality control messages.

When to Use

The rendering filter (usually the video renderer) is the primary user of this interface because it originates the quality control messages. Because the messages pass from one filter to another upstream, each downstream filter calls the IQualityControl::Notify method on the upstream output pin and so is a user.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns 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

HRESULT Notify(IFilter * pSelf, Quality q);

Receives a notification that a quality change is requested.

•	Returns an HRESULT value.

pSelf

[in] Pointer to the filter that is sending the quality notification.

q

[in] Quality notification structure.


IQualityControl::SetSink

HRESULT SetSink(IQualityControl *piqc);

Sets the IQualityControl object that will receive quality messages.

•	Returns an HRESULT value.

piqc

Pointer to the IQualityControl object to which the notifications should be sent.

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 is exposed by renderers, typically a video renderer, to return information about the performance achieved—for example, the number of frames per second (fps). The values returned through the interface are reset each time the filter is stopped. The base classes of the Microsoft® ActiveMovie™ Software Development Kit (SDK) have a standard property page that displays the information available from this interface.

When to Implement

The IQualProp interface is implemented by the ActiveMovie video renderer. Other video renderers may want to implement this interface as well, although it is optional.

When to Use

Applications use this interface to retrieve video renderer 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

HRESULT get_AvgFrameRate(int *piAvgFrameRate) PURE;

Retrieves the average frame rate since streaming started.

•	Returns an HRESULT value.

piAvgFrameRate

Number of frames per second (fps) since the streaming began.


IQualProp::get_AvgSyncOffset

HRESULT get_AvgSyncOffset(int *piAvg);

Retrieves the average time difference between when the video frames should have been displayed and when they actually were.

•	Returns an HRESULT value.

piAvg

Time difference expressed in milliseconds.


IQualProp::get_DevSyncOffset

HRESULT get_DevSyncOffset(int *piDev);

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.

•	Returns an HRESULT value.

piDev

Value denoting the accuracy of the video frames displayed.

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

HRESULT get_FramesDrawn(int *pcFramesDrawn);

Retrieves the number of frames drawn since streaming started.

•	Returns an HRESULT value.

pcFramesDrawn

Number of frames drawn since streaming started.


IQualProp::get_FramesDroppedInRenderer

HRESULT get_FramesDroppedInRenderer(int *pcFrames);

Retrieves the number of frames dropped by the renderer.

•	Returns an HRESULT value.

pcFrames

Number of frames dropped by the renderer.

The property page uses this method to retrieve data from the scheduler.


IQualProp::get_Jitter

HRESULT get_Jitter(int *piJitter);

Expresses the average time between successive frames delivered to the video renderer.

•	Returns an HRESULT value.

piJitter

Standard deviation, in milliseconds, of the interframe time.


IQueueCommand Interface

The IQueueCommand interface provides a way of deferring commands and property changes. The deferred command mechanism allows filters themselves to handle deferred commands. Where they do not, the filter graph manager queues the command until the requested time and then calls the method on the filter (this would result in coarse rather than accurate synchronization). Note that a filter that does handle deferred commands must make them apply to data appearing at that time. Thus a contrast filter asked to change the contrast at time x must ensure that it applies the change when processing data time-stamped to be rendered at time x; these samples will be processed by the filter somewhat before time x.

The IQueueCommand interface provides two methods, InvokeAtStreamTime, which queues commands at stream time, and InvokeAtPresentationTime, which queues commands at presentation time. Both return an IDeferredCommand interface to the queued command, by which the application can cancel the command, set a new presentation time for it, or get back an estimate of the likelihood of the filter graph manager being able to execute the command on time.

Both presentation time and stream time commands will execute once, and then be removed from the queue. Both the queue and the application will hold a reference count on the object (represented to the application by the IDeferredCommand interface), and the object will not be destroyed until both are released. Similarly, calling IUnknown::Release on the IDeferredCommand interface is not sufficient to cancel the command because the queue also holds a reference count.

Rather than add optional stream time and presentation time constraints to every method and property on every control interface, the application uses IDispatch to provide a single interface where these time parameters can be specified. IQueueCommand provides InvokeAtStreamTime and InvokeAtPresentationTime methods that are similar in style to the IDispatch::Invoke method.

The interface is specified by an IID. The method or property within that interface is specified by a dispid and a method/property flag as for IDispatch, and the parameters and return values are passed in VARIANTs.

Filters can implement IQueueCommand themselves. In this case, they parse the command and queue it for action when the relevant samples arrive or when the reference clock reaches the correct point, as appropriate. For filters that do not support this, the filter graph manager will execute the command when the reference clock reaches the specified time, regardless of the samples being processed at the filter.

OLE Automation access to IQueueCommand will be by the default IDispatch interface on the filter graph manager, which will parse the queued command using the type libraries for the interface specified.

When to Implement

This method is implemented by the filter graph manager to allow queuing of deferred commands.

When to Use

Applications may use this interface, along with the IDeferredCommand interface, to queue commands for deferred processing.

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 or property change for execution at a specified stream time (that is, presentation time relative to the current stream time offset).

InvokeAtPresentationTime 	Queues a method or property change for execution at a specified presentation time.


IQueueCommand::InvokeAtPresentationTime

HRESULT InvokeAtPresentationTime(

    IDeferredCommand * pCmd, REFTIME time, GUID* iid,

    long dispidMember, short wFlags, long cArgs,

    VARIANT *pDispParams, VARIANT *pvarResult,

    short *puArgErr);

Queues a method or property change for execution at a specified presentation time.

•	Returns an HRESULT value.

pCmd

[out] Pointer to the place to return an interface on the deferred command if it is successfully created.

time

[in] Time at which to invoke the command.

iid

[in] Interface to be called.

dispidMember

[in] Method or property to call on the interface.

wFlags

[in] Method or property flag.

cArgs

[in] Number of arguments on pDispParams.

pDispParams

[in] Parameters to this method.

pvarResult

[in,out] Return value.

puArgErr

[out] Index to the arguments in error.


IQueueCommand::InvokeAtStreamTime

HRESULT InvokeAtStreamTime(IDeferredCommand ** pCmd,

    REFTIME time, GUID *iid, long dispidMember,

    short wFlags,    long cArgs, VARIANT *pDispParams,

    VARIANT *pvarResult, short *puArgErr);

Implements deferred execution of OLE Automation methods or property changes at the specified stream time.

•	Returns an HRESULT value.

pCmd

[out] Pointer to the place to return an interface on the deferred command if it is successfully created.

time

[in] Time at which to invoke the command.

iid

[in] Interface to be called.

dispidMember

[in] Method or property to call on the interface.

wFlags

[in] Method or property flag.

cArgs

[in] Number of arguments in pDispParams.

pDispParams

[in] Parameters to this method.

pvarResult

[in, out] Return value of the called method.

puArgErr

[out] Index to the arguments in error.

Execute this command to affect the presentation that occurs after the specified stream time. The interface IID is an interface that can be obtained by calling IUnknown::QueryInterface on this same IQueueCommand interface.


IReferenceClock Interface

The IReferenceClock interface represents a system reference clock to be implemented by a filter in the filter graph and used by other filters.

When to Implement

Implement this interface if you are writing a filter that generates a system reference clock. Typically, this applies to audio renderer filters because audio sound boards usually contain a reference clock. Use the CBaseReferenceClock class to implement this interface.

When to Use

Use this interface on any filter to obtain reference clock notifications for a duration of elapsed time (both singular and repetitive) or to retrieve the current time.

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 	Gets the current time.

AdviseTime 	Requests an asynchronous notification that a duration has elapsed.

AdvisePeriodic 	Requests an asynchronous, periodic notification that a duration has elapsed.

Unadvise 	Cancels a request for notification.


IReferenceClock::AdvisePeriodic

HRESULT AdvisePeriodic(REFERENCE_TIME rtStartTime,

    REFERENCE_TIME rtPeriodTime, HSEMAPHORE hSemaphore,

    DWORD * pdwAdviseCookie);

Requests an asynchronous, periodic notification that a duration has elapsed.

•	Returns an HRESULT value.

rtStartTime

[in] Time the notification should begin.

rtPeriodTime

[in] Duration between notifications.

hSemaphore

[in] Handle of a semaphore through which to advise.

pdwAdviseCookie

[out] Used to identify this call to AdvisePeriodic in the future; for example, to cancel it.

When the time indicated by rtStartTime is reached, the semaphore whose handle is set as hSemaphore will be released. Thereafter, the semaphore will be released repetitively with a period of rtPeriodTime.


IReferenceClock::AdviseTime

HRESULT AdviseTime(REFERENCE_TIME rtBaseTime,

    REFERENCE_TIME rtStreamTime, HEVENT hEvent,

    DWORD * pdwAdviseCookie);

Requests an asynchronous notification that a duration has elapsed.

•	Returns an HRESULT value.

rtBaseTime

[in] Base reference time.

rtStreamTime

[in] Stream offset time.

hEvent

[in] Handle of an event through which to advise.

pdwAdviseCookie

[out] Destination of the token.

When the time rtBaseTime+rtStreamTime is reached, the event whose handle is hEvent will be set. If the time has already passed, the event will be set immediately.


IReferenceClock::GetTime

HRESULT GetTime(REFERENCE_TIME * pTime);

Retrieves the current time.

•	Returns an HRESULT value. If the sample does not have a time set, returns VFW_E_SAMPLE_TIME_NOT_SET.

pTime

[out] Current time.


IReferenceClock::Unadvise

HRESULT Unadvise(DWORD dwAdviseCookie);

Cancels a request for notification. See IReferenceClock::AdviseTime.

•	Returns an HRESULT value.

dwAdviseCookie

[in] Request to cancel.


IRegFilterInfo Interface

The IRegFilterInfo interface provides access to filters in the registry and allows a registered filter to be added to the filter graph.

When to Implement

IRegFilterInfo is implemented by the filter graph manager for use by OLE Automation client applications, such as Microsoft® Visual Basic®.

When to Use

Use this interface when it is exposed by an OLE Automation client to query the names of filters in a collection of registry filters and to add specific filters to the filter graph. A collection of IRegFilterInfo interfaces is returned by the IMediaControl::get_RegFilterCollection method.

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

HRESULT Filter(IDispatch **ppUnk);

Creates an instance of this filter and adds it to the graph.

•	Returns an HRESULT value.

ppUnk

[out] The IFilterInfo interface for the added filter.

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

HRESULT get_Name(BSTR * strName);

Retrieves the name of the filter.

•	Returns an HRESULT value.

strName

[out, retval] The name of the filter.

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

The IResourceConsumer interface implements a resource consumer that requests resources from a resource manager that supports the IResourceManager interface.

When to Implement

Implement this interface on any object that requests resources from a resource manager. (The filter graph manager acts as a resource manager for Microsoft® ActiveMovie™.) After implementing this interface, the object can register resources that it wishes to use. It passes a pointer to this interface when it does this so that the resource manager can call methods on this interface to inform the object that a resource is available or to release a resource that it is using.

When to Use

A resource manager that implements the IResourceManager interface calls methods on 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 may be acquired.

ReleaseResource 	Requests the resource consumer to release the specified resource.


IResourceConsumer::AcquireResource

HRESULT AcquireResource(LONG idResource);

Notifies the resource consumer that a resource may be acquired.

•	Returns one of the following values.

Return value 	Meaning

S_OK 	Consumer has successfully acquired the resource.

S_FALSE 	Consumer has not acquired the resource but will call IResourceManager::NotifyAcquire when it does.

VFW_S_NOT_NEEDED 	Consumer no longer needs the resource.

Error Value 	Consumer tried to acquire the resource but failed.

idResource

[in] Resource identifier of the resource to be acquired.


IResourceConsumer::ReleaseResource

HRESULT ReleaseResource(LONG idResource);

Requests the resource consumer to release the specified resource.

•	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 call IResourceManager::NotifyRelease when it does.

idResource

[in] Resource identifier to be released.


IResourceManager Interface

The IResourceManager interface implements a resource manager to resolve contentions for named resources.

When to Implement

Implement this interface on any object that performs the services of a resource manager. The filter graph manager acts as a resource manager for Microsoft® ActiveMovie™ and delegates to any existing system-wide resource manager. The filter graph manager implements the methods on this interface.

When to Use

Use this interface if your object requires resources that other objects are likely to use. The wave renderer uses this interface to resolve contentions for the wave-output device to enable sound to follow focus.

An object can use the resource manager supporting this interface to resolve possible contention between existing resources. This is carried out by registering the resource with the interface and then requesting it from this interface whenever needed.

Use this interface if your object detects user focus changes that may affect resource usage. Notifying the resource manager of a change of focus will cause the resource manager to switch contended resources to the objects that have the focus of the user.

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

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 is the one specified in this method.


IResourceManager::CancelRequest

HRESULT  CancelRequest(LONG idResource,

    IResourceConsumer* pConsumer);

Cancels the request for a resource.

•	Returns an HRESULT value.

idResource

[in] Resource identifier of a pending request.

pConsumer

[in] IResourceConsumer interface that made the request.

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 call the IResourceManager::NotifyRelease method.


IResourceManager::NotifyAcquire

HRESULT  NotifyAcquire(LONG idResource,

    IResourceConsumer* pConsumer,  HRESULT hr);

Notifies the resource manager that an attempt to acquire a resource has completed.

•	Returns an HRESULT value.

idResource

[in] Token for the registered resource.

pConsumer

[in] IResourceConsumer interface of the object requesting the resource.

hr

[in] Success of the acquisition; S_OK if the resource was acquired, or an error value if not.

Call 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

HRESULT NotifyRelease LONG idResource,

    IResourceConsumer* pConsumer, BOOL bStillWant);

Notifies the resource manager that IResourceConsumer has released a resource.

•	Returns an HRESULT value.

idResource

[in] Resource token.

pConsumer

[in] Object releasing the resource.

bStillWant

[in] Flag specifying whether the resource is still required or not.

Call this method in response to an IResourceConsumer::ReleaseResource method, or when you have finished using the resource. The bStillWant parameter should be set TRUE if you still want the resource when it is next available, or FALSE if you no longer want the resource.


IResourceManager::Register

HRESULT Register(LPCWSTR pName,

    LONG   cResource, LONG* plToken);

Registers a single named resource with the resource manager.

•	Returns an HRESULT value.

pName

[in] Named resource.

cResource

[in] Number of resources.

plToken

[out] Returned token identifying the resource to be used in additional calls.

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

HRESULT  RegisterGroup(LPCWSTR pName,

    LONG cResource,  LONG* palTokens,  LONG* plToken);

Registers a named resource group with the resource manager.

•	Returns an HRESULT value.

pName

[in] Named resource group.

cResource

[in] Number of resources in the group.

palTokens

[in, size_is(cResource)] Array of resources in the group.

plToken

[out] Returned group resource identifier.


IResourceManager::ReleaseFocus

HRESULT ReleaseFocus(IUnknown* pFocusObject);

Sets the focus object to null in the resource manager if the current focus object is the one specified in this method.

•	Returns an HRESULT value.

pFocusObject

[in] Focus object.

Call this method when the object of focus is about to be destroyed to ensure that the focus is not still being referenced.


IResourceManager::RequestResource

HRESULT  RequestResource(LONG idResource,

    IUnknown* pFocusObject, IResourceConsumer* pConsumer);

Requests the use of a given registered resource.

•	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.

idResource

[in] Resource token retrieved when the resource was registered.

pFocusObject

[in] IUnknown interface of a focus object associated with a request (normally the filter's IUnknown interface).

pConsumer

[in] IResourceConsumer interface on the object requesting the resource.

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 call QueryInterface on the focus object for IID_IFilter. If found, the resource manager will call methods on IFilter 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

HRESULT SetFocus(IUnknown* pFocusObject);

Notifies the resource manager that a specified object has been given the focus of the user.

•	Returns an HRESULT value.

pFocusObject

[in] Object that has been given the focus of the user.

In ActiveMovie, 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.

Once 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 call 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 call QueryInterface for the IFilter interface at least and, if found, will call methods on that interface. It calls methods on IFilter 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.


IUnknown Interface

The IUnknown interface lets clients get pointers to other interfaces on a given object through the IUnknown::QueryInterface method, and manage the existence of the object through the IUnknown::AddRef and IUnknown::Release methods. All other Component Object Model (COM) interfaces are inherited, directly or indirectly, from IUnknown. Therefore, the three methods in IUnknown are the first entries in the vtable for every interface.

Note that this interface and its methods are fully documented in the Microsoft® Win32® OLE documentation and are only partially documented here for quick reference.

When to Implement

You must implement IUnknown as part of every interface. If you are using C++ multiple inheritance to implement multiple interfaces, the various interfaces can share one implementation of IUnknown. If you are using nested classes to implement multiple interfaces, you must implement IUnknown once for each interface you implement.

Note that the IUnknown interface is implemented by the CUnknown base class in the ActiveMovie™ class library and so is inherited by most other classes.

When to Use

Use IUnknown methods to switch between interfaces on an object, add references, and release objects.

Methods in Vtable Order

IUnknown methods 	Description

QueryInterface 	Returns pointers to supported interfaces.

AddRef 	Increments the reference count.

Release 	Decrements the reference count.


IUnknown::AddRef

ULONG AddRef(void);

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.

•	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 may be unstable.

Note that this method is fully documented in the Microsoft Win32 OLE documentation and is only partially documented here for quick reference.


IUnknown::QueryInterface

HRESULT QueryInterface(REFIID iid, void ** ppvObject);

Returns a pointer to a specified interface on a component to which a client currently holds an interface pointer. This method must call IUnknown::AddRef on the pointer it returns.

•	Returns S_OK if the interface is supported, S_FALSE if not.

iid

[in] Specifies the IID of the interface being requested.

ppvObject

[out] Receives a pointer to an interface pointer to the object on return. If the interface specified in iid is not supported by the object, ppvObject is set to NULL.

Note that this method is fully documented in the Microsoft Win32 OLE documentation and is only partially documented here for quick reference.


IUnknown::Release

ULONG Release(void);

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.

•	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.

Note that this method is fully documented in the Microsoft Win32 OLE documentation and is only partially documented here for quick reference.


IVideoWindow Interface

The IVideoWindow interface supports the video window properties of a video renderer. It is a dual interface (accessible through Microsoft® Visual Basic® and 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 interface supports both properties and methods. Properties are more easily accessible from many OLE Automation controllers (such as Microsoft Visual Basic). However, some operations require several properties to be changed simultaneously; for this reason, 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 put_[property name] calls or by the single method SetWindowPosition.

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 OLE 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. Secondly, all strings are defined as being of type BSTR. All strings sent to the interface should be allocated through the OLE SysAllocString function, and similarly all strings returned from the interface should be freed by using the OLE SysFreeString function.

When to Implement

The video renderer filter supplied with Microsoft ActiveMovie™ implements this interface. Unlike most other interfaces on filters, it is not implemented by a filter graph manager plug-in distributor to pass method calls from the application. Instead, applications or other filters are required to access the video renderer filter's implementation directly.

Implement this interface if you are writing a replacement video renderer filter. You can use the CBaseVideoWindow class, which handles the IDispatch implementation for OLE Automation, to help implement this interface.

When to Use

This interface is used by applications or other filters that need to control the properties of the video window.

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.

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 playback window style.

put_WindowStyleEx 	Sets the playback window's extended style bits.

get_WindowStyleEx 	Retrieves the playback window's extended style bits.

put_AutoShow 	Specifies if the window will be automatically shown on the first state change.

get_AutoShow 	Returns if the window will be automatically shown on the first state change.

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 	Returns whenever the renderer realizes its palette 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 	Returns 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 	Returns the normal restored window dimensions.

HideCursor 	Hides the cursor.

IsCursorHidden 	Determines if the cursor is hidden or showing.


IVideoWindow::get_AutoShow

HRESULT get_AutoShow(long *AutoShow);

Retrieves information about whether the window will be automatically shown.

•	Returns an HRESULT value.

AutoShow

[out] OATRUE indicates that the window will be made visible when the state is changed to the paused or running state.


IVideoWindow::get_BackgroundPalette

HRESULT get_BackgroundPalette(long *pBackgroundPalette);

Retrieves information about whether any palette required will be realized in the background.

•	Returns an HRESULT value.

pBackgroundPalette

[out] OATRUE indicates that the palette will be realized in the background.


IVideoWindow::get_BorderColor

HRESULT get_BorderColor(long *pColor);

Retrieves the border color for the video window.

•	Returns an HRESULT value.

pColor

[out] The retrieved border color as a COLORREF value.


IVideoWindow::get_Caption

HRESULT get_Caption(BSTR *strCaption);

Retrieves the textual title string for the video window.

•	Returns an HRESULT value.

strCaption

[out] The retrieved window title caption.


IVideoWindow::get_FullScreenMode

HRESULT get_FullScreenMode(long *FullScreenMode);

Returns the full-screen rendering capabilities of the renderer filter supporting this interface.

•	Returns an HRESULT value.

FullScreenMode

[out] OATRUE if supporting full-screen video, or OAFALSE if not.

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

HRESULT get_Height(long *pHeight);

Sets the height of the video window.

•	Returns an HRESULT value.

pHeight

[out] Retrieved vertical dimension of the video window.


IVideoWindow::get_Left

HRESULT get_Left(long *pLeft);

Retrieves the x-axis coordinate for the video window.

•	Returns an HRESULT value.

pLeft

[out] The x-axis coordinate to be retrieved.


IVideoWindow::get_MessageDrain

HRESULT get_MessageDrain(OAHWND *Drain);

Retrieves the window set to receive messages from the video window.

•	Returns an HRESULT value.

Drain

[in] The window currently assigned to receive messages from the video window.

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::get_Owner

HRESULT get_Owner(OAHWND * pOwner);

Retrieves the owning parent for the video window.

•	Returns an HRESULT value.

pOwner

[out] Retrieved window handle.


IVideoWindow::get_Top

HRESULT get_Top(long *pTop);

Retrieves the y-axis coordinate of the video window.

•	Returns an HRESULT value.

pTop

[out] The y-axis origin to be retrieved.


IVideoWindow::get_Visible

HRESULT get_Visible(long *pVisible);

Retrieves the visibility of the video window.

•	Returns an HRESULT value.

pVisible

[out] OATRUE if the window is shown; otherwise, the window is hidden.


IVideoWindow::get_Width

HRESULT get_Width(long *pWidth);

Retrieves the width of the video window.

•	Returns an HRESULT value.

pWidth

[out] Width to be retrieved.


IVideoWindow::get_WindowState

HRESULT get_WindowState(long *WindowState);

Returns the state of the video window.

•	Returns an HRESULT value.

WindowState

[out] Flags indicating the state of the video window.

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 for the Microsoft Win32 ShowWindow function.


IVideoWindow::get_WindowStyle

HRESULT get_WindowStyle(long *pWindowStyle);

Changes the style parameters for the video window.

•	Returns an HRESULT value.

pWindowStyle

[out] A 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.

For a complete list of window styles, see the CreateWindow function in the Microsoft Win32 Software Development Kit (SDK).


IVideoWindow::get_WindowStyleEx

HRESULT get_WindowStyleEx(long * pWindowStyleEx);

Changes the style parameters for the video window.

•	Returns an HRESULT value.

pWindowStyleEx

[out] A 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.

This function uses extended window styles. For a complete list of window styles, see the CreateWindow function in the Microsoft Win32 Software Development Kit (SDK).


IVideoWindow::GetMaxIdealImageSize

HRESULT GetMaxIdealImageSize(long *pWidth, long *pHeight);

Retrieves the ideal maximum image size for the video image playback (client) area.

•	Returns an HRESULT value.

pWidth

[out] The image width.

pHeight

[out] The image height.


IVideoWindow::GetMinIdealImageSize

HRESULT GetMinIdealImageSize(long *pWidth, long *pHeight);

Retrieves the ideal minimum image size for the video image playback (client) area.

•	Returns an HRESULT value.

pWidth

[out] The image width.

pHeight

[out] The image height.


IVideoWindow::GetRestorePosition

HRESULT GetRestorePosition(long *pLeft, long *pTop,

    long *pWidth, long *pHeight);

Returns the normal restored window dimensions.

•	Returns an HRESULT value.

pLeft

[out] The left x-axis coordinate of the window.

pTop

[out] The top y-axis coordinate of the window.

pWidth

[out] The width of the window in pixels.

pHeight

[out] The height of the window in pixels.

When the window is maximized or iconized, 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 iconized.


IVideoWindow::GetWindowPosition

HRESULT GetWindowPosition(long *pLeft, long *pTop,

    long *pWidth, long *pHeight);

Retrieves the current window rectangle (not the client rectangle) in device coordinates.

•	Returns an HRESULT value.

pLeft

[out] The x-axis origin of the window.

pTop

[out] The y-axis origin of the window.

pWidth

[out] The width of the window in pixels.

pHeight

[out] The height of the window in pixels.

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::HideCursor

HRESULT HideCursor(long HideCursor);

Hides the cursor.

•	Returns an HRESULT value.

HideCursor

[in] If OATRUE, do not display the cursor; if OAFALSE, display the cursor.

This method is typically used when the video renderer is in full-screen mode, where cursor display may be unwanted.


IVideoWindow::IsCursorHidden

HRESULT IsCursorHidden(long * CursorHidden);

Determines if the cursor is hidden or showing.

•	Returns an HRESULT value.

CursorHidden

[out] If OATRUE, cursor is hidden; if OAFALSE, cursor is displayed.

This method is typically used when the video renderer is in full-screen mode, where cursor display may be unwanted.


IVideoWindow::NotifyOwnerMessage

HRESULT NotifyOwnerMessage(long hwnd, long uMsg,

    long wParam, long lParam);

Forwards messages that have been received by a parent window to a child window that is owned by a filter.

•	Returns an HRESULT value.

hwnd

[in] The window handle.

uMsg

[in] The message being sent.

wParam

[in] The message's wParam passed in.

lParam

[in] The message's lParam passed in.

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_SYSCOLORCHANGE

WM_PALETTECHANGED

WM_QUERYNEWPALETTE

WM_PALETTEISCHANGING

WM_DEVMODECHANGE

WM_DISPLAYCHANGE

WM_MOVE


IVideoWindow::put_AutoShow

HRESULT put_AutoShow(long AutoShow);

Determines whether the window will be automatically shown.

•	Returns an HRESULT value.

AutoShow

[in] OATRUE means the window will be made visible when the state is changed.

Many simple applications require a displayed window when a filter graph is set to the running state. This method is set to (-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. This can be done by setting the visible property.


IVideoWindow::put_BackgroundPalette

HRESULT put_BackgroundPalette(long BackgroundPalette);

Determines whether any palette required will be realized in the background.

•	Returns an HRESULT value.

BackgroundPalette

[in] OATRUE to realize the palette in the background; otherwise, OAFALSE.

If this is OATRUE (-1), 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

HRESULT put_BorderColor(long Color);

Sets the border color for the video window.

•	Returns an HRESULT value.

Color

[in] The new border color as a COLORREF type.

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

HRESULT put_Caption(BSTR strCaption);

Sets the textual title string for the video window.

•	Returns an HRESULT value.

strCaption

[in] The window title caption.


IVideoWindow::put_FullScreenMode

HRESULT put_FullScreenMode(long FullScreenMode);

Sets the full-screen mode for the video renderer filter supporting this interface.

•	Returns an HRESULT value.

FullScreenMode

[in] OATRUE if supporting full-screen video, or OAFALSE if not.

The normal ActiveMovie video renderer does not support this method and returns E_NOTIMPL. An implemented full-screen video renderer returns NOERROR. This method allows 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 ActiveMovie full-screen renderer. In fact, it also uses the maximum ideal image size property on IVideoWindow to determine if a window can be made a topmost window and resized to the entire display. This is the preferred approach to swapping renderers, because the filter graph may be using DirectDraw™ overlays or a hardware decoder filter.


IVideoWindow::put_Height

HRESULT put_Height(long Height);

Sets the height of the video window.

•	Returns an HRESULT value.

Height

[in] New vertical dimension of the video window.

Calling this method does not affect the y-axis coordinate of the video window.


IVideoWindow::put_Left

HRESULT put_Left(long Left);

Sets the x-axis coordinate for the video window.

•	Returns an HRESULT value.

Left

[in] The x-axis coordinate to be set.

Calling this method does not affect the width of the video window.


IVideoWindow::put_MessageDrain

HRESULT put_MessageDrain(OAHWND Drain);

Specifies a window to which the video window will post messages.

•	Returns an HRESULT value.

Drain

[in] The window to which messages will be posted.

The video renderer passes messages of certain types to a message drain by calling the Microsoft Win32 PostMessage function. These messages should be sufficient to allow simple applications that require some user interaction to be written (such as applications that require mouse clicks on video hot spots). An application may have a close relationship with the video that is being played and know at certain time points to look for certain interaction; this offers one way of implementing that. The parameters to the messages are passed on by the renderer untouched (in particular the client area coordinates), so the renderer does not translate the messages before passing them on, leaving that to be done by the application.

The following messages are posted to the window specified by the Drain parameter:

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

Because this member function does not make the message drain window a child window, it can be used by applications that make use of the full-screen capabilities.


IVideoWindow::put_Owner

HRESULT put_Owner(OAHWND Owner);

Sets an owning parent for the video window.

•	Returns an HRESULT value.

Owner

[in] Handle of the window to set.

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 but does not set the WS_CHILD style for the video window. If the window should become a true child window, the application should change the style by using IVideoWindow::put_WindowStyle.

Note that applications that use full-screen capabilities can use the IVideoWindow::put_MessageDrain method, which posts the same messages but does not make the video window a child window.

Note  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.

The video renderer passes the following messages to the parent window by calling the Microsoft Win32 PostMessage function. These messages should be sufficient to write applications that require simple user interaction.

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


IVideoWindow::put_Top

HRESULT put_Top(long Top);

Sets the y-axis coordinate of the video window.

•	Returns an HRESULT value.

Top

[in] The y-axis origin of the video window.

Calling this method does not affect the height of the video window.


IVideoWindow::put_Visible

HRESULT put_Visible(long Visible);

Changes the visibility of the video window.

•	Returns an HRESULT value.

Visible

[in] Boolean flag that is compatible with OLE Automation.

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

HRESULT put_Width(long Width);

Sets the width of the video window.

•	Returns an HRESULT value.

Width

[in] The width to be set.

Calling this method does not affect the x-axis coordinate of the video window.


IVideoWindow::put_WindowState

HRESULT put_WindowState(long WindowState);

Sets the state of the video window.

•	Returns an HRESULT value.

WindowState

[in] Describes the state of the video window.

This is a fairly thin wrapper on the Microsoft Win32 ShowWindow function. Use this method to change the window state. The WindowState parameter accepts such ShowWindow properties as SW_MINIMIZE, SW_MAXIMIZE, and SW_HIDE.


IVideoWindow::put_WindowStyle

HRESULT put_WindowStyle(long WindowStyle);

Changes the style parameters for the video window.

•	Returns an HRESULT value.

WindowStyle

[in] A 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.

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, make sure 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_ICONIC

WS_MAXIMIZE

WS_MINIMIZE

WS_HSCROLL

WS_VSCROLL


IVideoWindow::put_WindowStyleEx

HRESULT put_WindowStyleEx(long pWindowStyleEx);

Changes the EX style parameters for the video window.

•	Returns an HRESULT value.

pWindowStyleEx

[in] A 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.

This function uses EX window styles. For a complete list of extended window styles, see the CreateWindowEx function in the Microsoft Win32 Software Development Kit (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, make sure that the current styles are first retrieved, and then the necessary bit fields are added or removed.

Any of the following styles return E_INVALIDARG:

WS_DISABLED

WS_ICONIC

WS_MAXIMIZE

WS_MINIMIZE

WS_HSCROLL

WS_VSCROLL

With some exceptions (noted here), the acceptable flags are the same as those allowed by the Win32 CreateWindow function.


IVideoWindow::SetWindowForeground

HRESULT SetWindowForeground(long Focus);

Tells the renderer to grab the window foreground.

•	Returns an HRESULT value.

Focus

The window focus.

The caller can optionally give the window the input focus.


IVideoWindow::SetWindowPosition

HRESULT SetWindowPosition(long Left, long Top,

    long Width, long Height);

Sets the position of the video window (not the client rectangle position) in device coordinates.

•	Returns an HRESULT value.

Left

[in] The x-axis origin of the window.

Top

[in] The y-axis origin of the window.

Width

[in] Width of the window.

Height

[in] Height of the window.

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 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.


Base Classes


Deferred Command Classes


Enumerator Classes


Filter Classes


List and Queue Classes


Media Control and Positioning Classes


Multimedia Data Classes


OLE Interface Classes


Pin Classes


Render Filter Classes


Transport Classes


Win32 Classes


CAggDirectDraw Class

This class aggregates an IDirectDraw interface. Although DirectDraw™ interfaces (IDirectDraw and IDirectDrawSurface) potentially have the ability to be aggregated, this feature is not yet implemented. Various parts of Microsoft® ActiveMovie™ require aggregation of the DirectDraw interfaces. In particular, the video renderer passes out media samples that expose IDirectDraw and IDirectDrawSurface. The filter graph manager also exposes IDirectDraw as a plug-in distributor. 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. For information about any of the implemented IDirectDraw methods, see the Microsoft DirectX™ documentation.

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 	Returns an interface and increments the reference count.

Implemented IDirectDraw Methods

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.

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 	Returns the current display mode.

GetFourCCCodes 	Gets the FourCCCodes supported by the DirectDraw object.

GetGDISurface 	Returns the DirectDrawSurface object that currently represents the surface memory that GDI treats as the primary surface.

GetMonitorFrequency 	Points to a DirectDrawSurface pointer that will be made to point to the DirectDrawSurface object currently controlling GDI's primary surface memory.

GetScanLine 	Returns the scan line that the monitor is currently updating to the display.

GetVerticalBlankStatus 	Returns 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(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT *phr);

Constructs a CAggDirectDraw object.

pName

Name of the object; used for debugging purposes.

pUnk

Pointer to the owner of this object. If non-null, IUnknown calls are delegated to this object.

phr

Pointer to an HRESULT value.

This member function calls the CUnknown::CUnknown base class constructor and sets the m_pDirectDraw member variable to NULL.


CAggDirectDraw::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

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

void SetDirectDraw(LPDIRECTDRAW pDirectDraw);

Sets the DirectDraw object to be aggregated by this class.

pDirectDraw

IDirectDraw object to be aggregated.

This member function sets the m_pDirectDraw data member to the pDirectDraw parameter.


CAggDrawSurface Class

This class aggregates an IDirectDrawSurface interface. Although DirectDraw™ interfaces (IDirectDraw and IDirectDrawSurface) potentially have the ability to be aggregated, this feature is not yet implemented. Various parts of Microsoft® ActiveMovie™ require aggregation of the DirectDraw interfaces. In particular, the video renderer passes out media samples that expose IDirectDraw and IDirectDrawSurface. The filter graph manager also exposes IDirectDraw as a plug-in distributor. 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. For information about any of the implemented IDirectDrawSurface methods, see the DirectX™ documentation.

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 	Returns an interface and increments the reference count.

Implemented IDirectDrawSurface Methods

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 need to be updated the next time the CAggDrawSurface::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 	Returns the status of a bit-block transfer.

GetCaps 	Returns the capabilities of the surface.

GetClipper 	Returns the DirectDrawClipper associated with this surface.

GetColorKey 	Returns 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, it returns DDERR_WASSTILLDRAWING.

GetOverlayPosition 	Returns the display coordinates of the surface, given a visible, active overlay surface (DDSCAPS_OVERLAY set).

GetPalette 	Returns the DirectDrawPalette structure associated with this surface.

GetPixelFormat 	Returns the color and pixel format of the surface.

GetSurfaceDesc 	Returns a DDSURFACEDESC structure describing the surface in its current condition.

Initialize 	Initializes a DirectDrawSurface.

IsLost 	Determines if the surface memory associated with a DirectDrawSurface 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 to a DirectDrawSurface.

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 specified to a Surface.

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 the Z order of an overlay. The Z order determines which overlay should be occluded when multiple overlays are displayed simultaneously.


CAggDrawSurface::CAggDrawSurface

CAggDrawSurface(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT *phr);

Creates a CAggDrawSurface object.

pName

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.

phr

Pointer to an HRESULT value.

This member function calls the CUnknown::CUnknown base class constructor and sets the m_pDirectDrawSurface member variable to NULL.


CAggDrawSurface::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

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

void SetDirectDrawSurface(LPDIRECTDRAWSURFACE

    pDirectDrawSurface);

Called by the owner of this aggregation object to set the actual DirectDraw surface it is aggregating upon.

pDirectDrawSurface

DirectDrawSurface to be set.

This member function must be called before any of the IDirectDrawSurface interface methods can be called.


CAMEvent Class

The CAMEvent class is an event object that can be set and waited on to provide interthread synchronization. This is currently implemented by using the Microsoft® Win32® Event application programming interfaces (APIs).

Events can be created as manual-reset or automatic-reset, and will always be created as not set (non-signaled state). They can also be cast to handles so as to be passed to the Win32 WaitForMultipleObjects function.

Protected Data Members

m_hEvent 	Microsoft Win32 event handle.

Member Functions

CAMEvent 	Constructs a CAMEvent object.

Check 	Returns true if the event is currently set, but does not block.

Reset 	Forces the event into a nonsignaled state.

Set 	Puts the event into a signaled state.

Wait 	Blocks until the event is signaled, or until an optional time-out occurs.

operator HANDLE 	Gets the HANDLE object.


CAMEvent::CAMEvent

CAMEvent(BOOL fManualReset = FALSE);

Constructs a CAMEvent object.

fManualReset

If this value is FALSE, the event is reset when the CAMEvent::Wait member function completes. If this parameter is TRUE, you can set the event by calling the CAMEvent::Set member function and then reset it by calling the CAMEvent::Reset member function.


CAMEvent::Check

BOOL Check(void);

Returns TRUE if the event is currently set, but does not block.

For events that are not manual-reset events, this member function causes the event to enter a nonsignaled state.


CAMEvent::Reset

void Reset(void);

Forces the event into a nonsignaled state.


CAMEvent::Set

void Set(void);

Puts the event into a signaled state.

If the event is not a manual-reset event and there is at least one thread blocked on this event, the thread is released and the event remains in a nonsignaled state. If the event is not a manual-reset event and no threads are blocked on the event, it is set to a signaled state.

If the event is not a manual-reset event, it is set to a signaled state and all the threads blocked on this event are released.


CAMEvent::Wait

BOOL Wait(DWORD dwTimeout = INFINITE);

Blocks until the event is signaled, or until the indicated time-out occurs.

•	Returns TRUE if the event becomes signaled; otherwise, returns FALSE.

dwTimeout

Optional time-out value, represented in milliseconds. The default is INFINITE.

For events that are not manual-reset events, the action completing the CAMEvent::Wait member function causes the event to enter a nonsignaled state until the CAMEvent::Set member function is called.


CAMEvent::operator HANDLE

operator HANDLE () const;

Gets the HANDLE object associated with this CAMEvent object.

•	Returns the Microsoft Win32 event HANDLE.


CAMSchedule Class

The CAMSchedule class relieves clocks of the burden of managing the advise requests. A clock may delegate such management to this class, provided that it calls this class's Advise method when the earliest event should be fired. The time of the earliest event can be fetched by calling GetNextAdviseTime, or it can be tracked by a combination of the times returned by Advise and the event times that the clock adds.

Member Functions

AddAdvisePacket 	Creates a new pending notification.

Advise 	Requests the scheduler to dispatch all events up to and including the time specified.

CAMSchedule 	Constructs a CAMSchedule object.

GetAdviseCount 	Returns the number of outstanding events.

GetNextAdviseTime 	Returns the reference time at which the next advise should be set, or MAX_TIME if there are no events scheduled.

Unadvise 	Removes a previously established advise link.

Overridable Member Functions

Dispatch 	Dispatches the event for a given advise.


CAMSchedule::AddAdvisePacket

DWORD AddAdvisePacket(const REFERENCE_TIME & time1,

    const REFERENCE_TIME & time2, HANDLE hNotify,

    BOOL bPeriodic);

Creates a new pending notification and adds it to the advise notification list.

•	Returns the advise token if successful, or 0 if an error occurred.

time1

Time that the advise should take place.

time2

Period between notifications. (Ignored if bPeriodic is FALSE.)

hNotify

Notification mechanism. Either a semaphore handle (if pPeriodic is FALSE) or an event handle.

bPeriodic

Indicator of whether this is a one-shot timer.


CAMSchedule::Advise

REFERENCE_TIME Advise(const REFERENCE_TIME & rtTime);

Requests the scheduler to dispatch all events up to and including the time specified. This method is expected to be called by a controlling clock specifying the current time, just in time to dispatch the next advise request.

•	Returns the reference time at which the next advise will expire, or MAX_TIME if there are no outstanding events.

rtTime

Current reference time.

Clocks can call this method to advise the scheduler of the time. The scheduler will then set all of the events that have expired, and reschedule the periodic ones.

It is not intended that clocks should call this method all of the time, rather that clocks will call Advise just one time. The time returned will be "useless" if you start adding extra advises.


CAMSchedule::CAMSchedule

CAMSchedule( );

Constructs a CAMSchedule object.


CAMSchedule::Dispatch

virtual void Dispatch(DWORD Token,

    REFERENCE_TIME & time1, REFERENCE_TIME & time2,

    HANDLE & hNotify, BOOL & bPeriodic);

This is the method that CAMSchedule calls internally when it dispatches events. Derived classes may override this method if they wish. Having invoked this method for an expired event, the caller must then reschedule periodic events and delete single-shot events; that is not the responsibility of this method.

Token

Advise token.

time1

Time that the advise should take place.

time2

Period between notifications. (Ignored if bPeriodic is FALSE.)

hNotify

Notification mechanism. Either a semaphore handle (if pPeriodic is FALSE) or an event handle.

bPeriodic

Indicator of whether this is a one-shot timer.

CAMSchedule will be holding a lock during the call to Dispatch. No other threads will be able to schedule events against this scheduler until this method has returned.

Note that the Dispatch method requires that the caller has the Reference Clock critical section locked. This means that no other thread will be able to use Reference Clock methods until this routine returns control.

This method is exposed to permit derived classes to interrupt the normal dispatching mechanism if required. The references passed are references to the actual data in the advise packet.

This member function is protected.


CAMSchedule::GetAdviseCount

DWORD GetAdviseCount();

Returns the number of outstanding events.

•	Returns the number of outstanding events.


CAMSchedule::GetNextAdviseTime

REFERENCE_TIME GetNextAdviseTime();

Checks the time of the next advise.

•	Returns the reference time at which the next advise should be set, or MAX_TIME if there are no events scheduled.


CAMSchedule::Unadvise

HRESULT Unadvise(DWORD dwAdviseToken);

Removes a previously established advise link.

•	Returns an HRESULT value.

dwAdviseToken

Identifier (token) of the link that is being reset. This is the same value that was returned on CAMSchedule::AddAdvisePacket.

This member function is modeled after the IReferenceClock::Unadvise method. Call Unadvise to remove the previously established clock advise links.

Unadvise should be called for unexpired single-shot advise requests. Calling Unadvise with the token of an already expired event causes no problems, so applications may choose to always Unadvise their single-shot events without fear of problems.


CAutoLock Class

The CAutoLock class holds a critical section for the scope of a block or function. The constructor locks the critical section and the destructor unlocks it. The object passed to the CAutoLock constructor must be derived from the CCritSec class. Thus, by declaring a CAutoLock object as a local variable in a function, a critical section can be locked without the danger of forgetting to unlock it in some of the code paths: the destructor ensures that upon exit from the function (or the scope of the declaration), the critical section will be unlocked. Member functions in this class are not designed for overriding.

/* Typical usage ensuring object is always unlocked correctly */

HRESULT MyFunc(IMediaSample *pSample)

{

   CAutoLock cObjectLock(m_pMyLock);

   /* Ignore samples passed when inactive */

   if (!m_bActive) {

      return NOERROR;

   }

   /* Add the sample to the pending queue */

   HRESULT hr = m_PendingList.AddTail(pSample);

   if (FAILED(hr)) {

      pSample->Release();

      return hr;

   }

   return NOERROR;

}

Protected Data Members

m_pLock 	Critical section for this lock.

Member Functions

CAutoLock 	Takes a pointer to a critical section object and locks it.


CAutoLock::CAutoLock

CAutoLock(CCritSec * plock);

Takes a pointer to a critical section object and locks it.

plock

Pointer to a critical section object.

The critical section is unlocked upon the destruction of the CAutoLock object.


CBaseAllocator Class

CBaseAllocator is an abstract base class that implements the basic mechanisms for an allocator with a fixed number of fixed-sized buffers. The number of buffers and their size can be changed using the CBaseAllocator::SetProperties member function when an input pin and an output pin negotiate the allocator between them.

The class provides the basic functionality for a memory allocator by implementing the IMemAllocator interface. It provides support for managing a list of CMediaSample objects (or objects derived from this class), including support for the IMemAllocator::Commit and IMemAllocator::Decommit methods, and blocking the IMemAllocator::GetBuffer method.

Any class derived from this class (such as CMemAllocator) must create CMediaSample objects, which this base class does not.

A signaling mechanism employing a semaphore is used so that if there are no samples, a thread can wait until there are samples or until the allocator is decommitted. The m_lFree and m_hSem member variables are used to implement this simple signaling mechanism as follows.

When a thread calls CBaseAllocator::GetBuffer and there are no samples available, m_lWaiting is incremented and the thread calls the Microsoft® Win32® WaitForSingleObject function on the semaphore indicated by m_hSem.

When a sample is freed (by the IUnknown::Release method returning the reference count to zero) or CBaseAllocator::Decommit is called and m_lWaiting is non-zero, the Win32 ReleaseSemaphore function is called on m_hSem with a release count of m_lWaiting, and m_lWaiting is reset to zero.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Protected Data Members

m_bChanged 	TRUE if the buffers have changed; otherwise, FALSE.

m_lCount 	Established number of buffers to provide.

m_lAlignment 	Agreed alignment of the buffer.

m_lAllocated 	Number of buffers actually allocated.

m_lSize 	Size of each buffer.

m_lFree 	List of CMediaSample objects that are currently free (free list).

m_lPrefix 	Agreed prefix of the buffer (precedes value returned by IMediaSample::GetPointer).

m_bCommitted 	If TRUE, the allocator is in a state in which all IMemAllocator::GetBuffer methods fail. The IMemAllocator::SetProperties method is the only member function permitted to operate in this state.

m_bDecommitInProgress 	If TRUE, the decommit process completes upon the return of all media samples. Until the decommit process has completed, any calls to IMemAllocator::GetBuffer return E_OUTOFMEMORY.

m_hSem 	Semaphore for signaling.

m_lWaiting 	Count of threads waiting for samples.

Member Functions

CBaseAllocator 	Constructs a CBaseAllocator object.

NotifySample 	Notifies a waiting thread that a sample is available on the free list.

SetWaiting 	Increments the m_lWaiting data member to indicate that a thread is waiting for a sample.

Overridable Member Functions

Alloc 	Allocates memory, instantiates CMediaSample objects, and adds them to the m_lAllocated and m_lFree data members.

Free 	Decommits memory when the last buffer is freed.

Implemented IMemAllocator Methods

Commit 	Allocates memory by calling the CBaseAllocator::Alloc member function, which you must override.

Decommit 	Releases any resources and enters the inactive state. Any blocking calls to IMemAllocator::GetBuffer should return with an error value, and all further calls to GetBuffer fail when in the inactive state.

GetBuffer 	Retrieves a container for a sample.

GetProperties 	Determines the size, number, and alignment of blocks.

ReleaseBuffer 	Releases the CMediaSample object.

SetProperties 	Specifies a desired number of blocks, size of the blocks, and block alignment figure. This method returns the actual values for the same.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Passes out pointers to any interfaces added to the derived filter class.


CBaseAllocator::Alloc

HRESULT Alloc(void);

Allocates a media sample object.

•	Returns an HRESULT value.

Override this member function to allocate memory, instantiate CMediaSample objects, and add them to the free list represented by the m_lFree data member. The CMemAllocator::Alloc member function is an example of an override of this member function. It calls this member function first to make sure that allocator properties have been set.

This member function is called from the CBaseAllocator::Commit member function when entering the active state. The default implementation returns an error value if the IMemAllocator::SetProperties method has not been called yet, and checks that there are no outstanding buffers.

This member function is protected.


CBaseAllocator::CBaseAllocator

CBaseAllocator(TCHAR * pName, LPUNKNOWN lpUnk,

    HRESULT * phr, BOOL bListSemaphore = TRUE);

Constructs a CBaseAllocator object.

pName

Name of the allocator object.

lpUnk

Pointer to LPUNKNOWN.

phr

Pointer to an HRESULT for return values. This is not modified unless this member function fails.

bListSemaphore

If TRUE, the free list in the allocator has a semaphore associated with it. If FALSE, no semaphore is created for the list. Setting this to FALSE can be useful for subclassing CBaseAllocator when the semaphore is not required for blocking. The semaphore is used for the waiting and signaling mechanism.


CBaseAllocator::Commit

HRESULT Commit(void);

Commits the memory for the specified buffers.

•	Returns an HRESULT value.

This member function implements the IMemAllocator::Commit method. The IMemAllocator::SetProperties method must be called before calling this member function. This member function sets m_bCommitted to TRUE and overrides any pending decommit operation. It then calls the CBaseAllocator::Alloc member function to allocate memory (which should be overridden in the derived class to call the base class member function and then allocate the memory). The IMemAllocator::GetBuffer method fails if it is called before calling this member function.


CBaseAllocator::Decommit

HRESULT Decommit(void);

Releases the memory for the specified buffers.

•	Returns an HRESULT value.

This member function implements the IMemAllocator::Decommit method. Any threads waiting in the IMemAllocator::GetBuffer method return with an error after this method is called. The IMemAllocator::GetBuffer method fails if it is called before the IMemAllocator::Commit method or after this method.


CBaseAllocator::Free

virtual void Free(void) PURE;

Called to decommit the memory when the last buffer is freed.

This member function is called to decommit memory when the last buffer is freed. It must be implemented in the derived class. It is called from CBaseAllocator::ReleaseBuffer when a decommit is pending and the allocator has put its last buffer on the free list. It is also called from CBaseAllocator::Decommit.

The CMemAllocator::Free member function is an example of how this can be implemented in the derived class. In this case, it simply returns, because the CMemAllocator class releases memory from its destructor.

This member function is protected.


CBaseAllocator::GetBuffer

HRESULT GetBuffer(IMediaSample ** ppBuffer

    REFERENCE_TIME * pStartTime,

    REFERENCE_TIME * pEndTime, dwFlags );

Retrieves a container for a sample.

•	Returns an HRESULT value.

ppBuffer

Pointer to a retrieved media sample buffer.

pStartTime

Either NULL or set to the beginning time of the sample to retrieve.

pEndTime

Either NULL or set to the ending time of the sample to retrieve.

dwFlags

The following flags are supported:

AM_GBF_PREVFRAMESKIPPED 	The buffer returned will not be filled with data contiguous to any previous data sent.

AM_GBF_NOTASYNCPOINT 	Dynamic format changes are not allowed on this buffer because it is not a key frame.

This member function implements the IMemAllocator::GetBuffer method.

This is a blocking, synchronous call to access the next free buffer (as represented by an IMediaSample interface). Upon return, properties (such as the time and so on) are invalid, but the buffer pointer and size are correct.

If there are no buffers available, CBaseAllocator::GetBuffer calls CBaseAllocator::SetWaiting and then calls the Microsoft Win32® WaitForSingleObject function to wait for the list to signal that a sample is available. The list signals by calling CBaseAllocator::ReleaseBuffer, which in turn calls CBaseAllocator::NotifySample, which sets m_lWaiting to zero and calls the Win32 ReleaseSemaphore function.

The member function also takes two time parameters. These parameters are used in certain advanced buffering scenarios when it is necessary to have an idea of the amount of time a buffer is required. The only place this is currently used is in the video renderer when the time stamps are used as a guide to when the primary surfaces of Display Control Interface (DCI) and Microsoft® DirectDraw™ should be returned (this is because filling a primary surface buffer corresponds directly to the actual rendering of the data). In all other cases, these parameters may be safely set to NULL. If one is non-NULL, both should be non-NULL; these times will not be set on the sample when it is subsequently returned.


CBaseAllocator::GetProperties

HRESULT GetProperties(ALLOCATOR_PROPERTIES * pProps);

Retrieves the size, number, and alignment of blocks.

•	Returns an HRESULT value.

pProps

The structure to be filled in with allocator properties.

This member function implements the IMemAllocator::GetProperties method. The default implementation fills the ALLOCATOR_PROPERTIES structure passed in with the values of m_lSize, m_lCount, m_lAlignment, and m_lPrefix.


CBaseAllocator::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IMemAllocator and IUnknown interfaces. Override this member function to return other interfaces on the object in the derived class.


CBaseAllocator::NotifySample

void NotifySample(void);

Notifies a waiting thread that a sample is available on the free list.

If m_lWaiting has been incremented (is not zero), this indicates a thread is waiting. This member function checks for this condition and calls the Microsoft Win32 ReleaseSemaphore function with the semaphore value m_hSem to activate any waiting thread. It also sets m_lWaiting back to zero.

This member function is called from CBaseAllocator::ReleaseBuffer when putting a sample back on the free list and from CBaseAllocator::Decommit when decommiting the allocator (so that waiting threads can be denied).


CBaseAllocator::ReleaseBuffer

HRESULT ReleaseBuffer(IMediaSample * pSample);

Releases the object back to the list of free objects.

pSample

Pointer to the IMediaSample interface of the media sample object.

This member function implements the IMemAllocator::ReleaseBuffer method. It adds the sample to the free list (represented by m_lFree) and calls CBaseAllocator::NotifySample to notify any blocked thread waiting for a free sample. If there is a pending CBaseAllocator::Decommit call (indicated by m_bDecommitInProgress), the pure virtual CBaseAllocator::Free member function is called to decommit memory when the last buffer is placed on the free list.


CBaseAllocator::SetProperties

HRESULT SetProperties(ALLOCATOR_PROPERTIES * pRequest,

    ALLOCATOR_PROPERTIES * pActual);

Determines the size, number, and alignment of blocks.

•	Returns an HRESULT value.

pRequest

Allocator properties requested to be set.

pActual

Allocator properties actually set.

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 method cannot be called unless the allocator has been decommitted using the IMemAllocator::Decommit method.

The values of data members m_lSize, m_lCount, m_lAlignment, and m_lPrefix are set to the corresponding members of the pActual parameter's ALLOCATOR_PROPERTIES structure.


CBaseAllocator::SetWaiting

void SetWaiting();

Increments the m_lWaiting data member to indicate that a thread is waiting for a sample.

This member function is called from CBaseAllocator::GetBuffer if there are no samples available on the free list. After calling this, CBaseAllocator::GetBuffer calls the Microsoft Win32 WaitForSingleObject function to wait for the list to signal that a sample is available. The list signals by calling CBaseAllocator::ReleaseBuffer, which in turn calls CBaseAllocator::NotifySample, which sets m_lWaiting to zero and calls the Win32 ReleaseSemaphore function.


CBaseBasicVideo Class

The CBaseBasicVideo class handles the IDispatch component of the IBasicVideo interface and leaves the properties and methods pure virtual.

The IDispatch::GetTypeInfoCount, IDispatch::GetTypeInfo, IDispatch::GetIDsOfNames, 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(TCHAR * pName, LPUNKNOWN pUnk,

    HRESULT * phr);

Constructs a CBaseBasicVideo object.

pName

Name of the object for debugging purposes.

pUnk

Pointer to the owner of this object.

phr

Pointer to an HRESULT value for resulting information.

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.


CBaseBasicVideo::GetIDsOfNames

HRESULT GetIDsOfNames(REFIID riid,

    OLECHAR  ** rgszNames, UINT cNames,

    LCID lcid, DISPID * rgdispid);

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.

•	Returns one of the following values.

Value 	Meaning

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.

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

The locale context in which to interpret the names.

rgdispid

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.


CBaseBasicVideo::GetTypeInfo

HRESULT GetTypeInfo(UINT itinfo, LCID lcid,

    ITypeInfo ** pptinfo);

Retrieves a type-information object, which can retrieve the type information for an interface.

•	Returns an HRESULT value.

itinfo

The type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

The locale ID for the type information. An object may 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

A pointer to the type-information object requested.


CBaseBasicVideo::GetTypeInfoCount

HRESULT GetTypeInfoCount(UINT * pctinfo);

Retrieves the number of type-information interfaces provided by an object.

•	Returns an HRESULT value.

pctinfo

Points 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.


CBaseBasicVideo::Invoke

HRESULT Invoke(DISPID dispidMember, REFIID riid,

    LCID lcid, WORD wFlags, DISPPARAMS * pdispparams,

    VARIANT * pvarResult, EXCEPINFO * pexcepinfo,

    UINT * puArgErr);

Provides access to properties and methods exposed by an object.

•	Returns an HRESULT value.

dispidMember

Identifies 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

The 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

The index of the first argument, within the rgvarg array, that has an error.


CBaseBasicVideo::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void **ppv);

Returns a specified reference-counted interface.

•	Returns pointers to the IBasicVideo and IUnknown interfaces by default.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this method to publish any additional interfaces implemented by the derived class.


CBaseControlVideo Class

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.

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 VIDEOINFO 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 whenever 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 	Returns an approximate average time per frame.

get_BitErrorRate 	Returns an approximate bit error rate.

get_BitRate 	Returns an approximate bit rate for the video.

GetCurrentImage 	Returns a memory rendering of the current image.

get_DestinationHeight 	Retrieves the current destination rectangle height.

get_DestinationLeft 	Retrieves the current destination rectangle left coordinate.

GetDestinationPosition 	Retrieves the current destination position.

get_DestinationTop 	Retrieves the current destination rectangle top coordinate.

get_DestinationWidth 	Retrieves the current destination rectangle width.

get_SourceHeight 	Retrieves the current source rectangle height.

get_SourceLeft 	Retrieves the current source rectangle left coordinate.

GetSourcePosition 	Retrieves the current source position.

get_SourceTop 	Retrieves the current source rectangle top coordinate.

get_SourceWidth 	Retrieves the current source rectangle 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 height.

put_DestinationLeft 	Sets the destination rectangle left coordinate.

put_DestinationTop 	Sets the destination rectangle top coordinate.

put_DestinationWidth 	Sets the destination rectangle width.

put_SourceHeight 	Sets the source rectangle height.

put_SourceLeft 	Sets the source rectangle left coordinate.

put_SourceTop 	Sets the source rectangle top coordinate.

put_SourceWidth 	Sets the source rectangle width.

SetControlVideoPin 	Sets the pin used by the filter.

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(CBaseFilter *pFilter,

    CCritSec *pInterfaceLock, TCHAR *pName,

    LPUNKNOWN pUnk, HRESULT *phr);

Constructs a CBaseControlVideo object.

pFilter

Owning media filter object.

pInterfaceLock

Critical section to use for locking.

pName

Object description.

pUnk

Typical COM ownership.

phr

OLE return value.

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

virtual HRESULT CheckSourceRect(RECT *pSourceRect);

Determines if a source rectangle is valid.

•	Returns E_INVALIDARG if not valid; otherwise, returns NOERROR (S_OK).

pSourceRect

Source rectangle to check.

This member function determines 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

virtual HRESULT CheckTargetRect(RECT *pTargetRect);

Determines if a target rectangle is valid.

•	Returns E_INVALIDARG if not valid; otherwise, returns NOERROR (S_OK).

pTargetRect

Target rectangle to check.

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 may be negative, although the overall width and height cannot be zero or a negative value.


CBaseControlVideo::CopyImage

HRESULT CopyImage(IMediaSample *pMediaSample,

    VIDEOINFO *pVideoInfo, LONG *pBufferSize,

    BYTE *pDIBImage, RECT *pSourceRect);

Creates a memory copy of an image.

•	If the pDIBImage 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.

pMediaSample

Sample containing the video image.

pVideoInfo

Format representing the video image.

pBufferSize

Size of the output buffer.

pDIBImage

Pointer to the output buffer.

pSourceRect

Source video rectangle.

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

HRESULT get_AvgTimePerFrame(REFTIME *pAvgTimePerFrame);

Retrieves the average time per frame.

•	Returns an HRESULT value.

pAvgTimePerFrame

Average time per frame.

This member function implements the IBasicVideo::get_AvgTimePerFrame method. It calls the pure virtual CBaseControlVideo::GetVideoFormat member function to retrieve the VIDEOINFO structure from the derived class.


CBaseControlVideo::get_BitErrorRate

HRESULT get_BitErrorRate(long *pBitErrorRate);

Returns an approximate bit error rate for the video.

•	Returns an HRESULT value.

pBitErrorRate

Bit error rate (one error for approximately this many bits).

This member function implements the IBasicVideo::get_BitErrorRate method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFO structure from the derived class.


CBaseControlVideo::get_BitRate

HRESULT get_BitRate(long *pBitRate);

Returns an approximate bit rate for the video.

•	Returns an HRESULT value.

pBitRate

Bit rate in bits per second.

This member function implements the IBasicVideo::get_BitErrorRate method. It calls pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFO structure from the derived class.


CBaseControlVideo::get_DestinationHeight

HRESULT get_DestinationHeight(long *pDestinationHeight);

Retrieves the current destination rectangle height.

•	Returns an HRESULT value.

pDestinationHeight

Holds the destination height.

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

HRESULT get_DestinationLeft(long *pDestinationLeft);

Retrieves the left coordinate of the current destination rectangle.

•	Returns an HRESULT value.

pDestinationLeft

Contains the left coordinate of the destination rectangle.

This member function implements the IBasicVideo::get_DestinationLeft method.

An application may 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

HRESULT get_DestinationTop(long *pDestinationTop);

Retrieves the top coordinate of the current destination rectangle.

•	Returns an HRESULT value.

pDestinationTop

Contains the top coordinate of the destination rectangle.

This member function implements the IBasicVideo::get_DestinationTop method.

An application may 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

HRESULT get_DestinationWidth(long *pDestinationWidth);

Retrieves the width of the current destination rectangle.

•	Returns an HRESULT value.

pDestinationWidth

Contains the destination width.

This member function implements the IBasicVideo::get_DestinationWidth method.

An application may 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_SourceHeight

HRESULT get_SourceHeight(long *pSourceHeight);

Retrieves the height of the current source rectangle.

•	Returns an HRESULT value.

pSourceHeight

Contains the the height of the source rectangle.

This member function implements the IBasicVideo::get_SourceHeight method.

An application may 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

HRESULT get_SourceLeft(long *pSourceLeft);

Retrieves the left coordinate of the current source rectangle.

•	Returns an HRESULT value.

pSourceLeft

Holds the left coordinate of the current source rectangle.

An application may 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_SourceTop

HRESULT get_SourceTop(long *pSourceTop);

Retrieves the top coordinate of the current source rectangle.

•	Returns an HRESULT value.

pSourceTop

Contains the top coordinate of the source rectangle.

This member function implements the IBasicVideo::get_SourceTop method.

An application may 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

HRESULT get_SourceWidth(long *pSourceWidth);

Retrieves the width of the current source rectangle.

•	Returns an HRESULT value.

pSourceWidth

Contains the width of the current source rectangle.

This member function implements the IBasicVideo::get_SourceWidth method.

An application may 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_VideoHeight

HRESULT get_VideoHeight(long *pVideoHeight);

Retrieves the height of the native video.

•	Returns an HRESULT value.

pVideoHeight

Contains the height of the native video, in pixels.

This member function implements the IBasicVideo::get_VideoHeight method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFO structure from the derived class.


CBaseControlVideo::get_VideoWidth

HRESULT get_VideoWidth(long *pVideoWidth);

Retrieves the width of the native video.

•	Returns an HRESULT value.

pVideoWidth

Contains the width of the native video, in pixels.

This member function implements the IBasicVideo::get_VideoWidth method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFO structure from the derived class.


CBaseControlVideo::GetCurrentImage

HRESULT GetCurrentImage(long *pBufferSize,

    long *pDIBImage);

Returns a copy of the current image at the renderer.

•	Returns an HRESULT value.

pBufferSize

Size of the output buffer.

pDIBImage

Pointer to the output buffer for the image.

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::GetDestinationPosition

HRESULT GetDestinationPosition(long *pLeft, long *pTop,

    long *pWidth, long *pHeight);

Retrieves the destination rectangle.

•	Returns an HRESULT value.

pLeft

Contains the left coordinate.

pTop

Contains the top coordinate.

pWidth

Contains the width.

pHeight

Contains the height.

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 may 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

HRESULT GetSourcePosition(long *pLeft, long *pTop,

    long *pWidth, long *pHeight);

Retrieves the source rectangle in one atomic operation.

•	Returns an HRESULT value.

pLeft

Contains the left coordinate.

pTop

Contains the top coordinate.

pWidth

Contains the width.

pHeight

Contains the height.

An application may 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

virtual HRESULT GetSourceRect(RECT *pSourceRect) PURE;

Returns the source rectangle. This is an internal method.

•	Returns an HRESULT value.

pSourceRect

Contains the retrieved source rectangle.

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 from the video renderer sample, SampVid, 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::GetStaticImage

virtual HRESULT GetStaticImage(long *pBufferSize,

    long *pDIBImage) PURE;

Pure virtual method that derived classes override.

•	Returns an HRESULT value.

pBufferSize

Size of the output buffer.

pDIBImage

Pointer to output buffer.

Through the IBasicVideo interface, an application may request that it be given a copy of the current image in a memory buffer (some renderers may 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 from the video renderer sample, SampVid, 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

virtual HRESULT GetTargetRect(RECT *pTargetRect) PURE;

Returns the destination rectangle. This is an internal helper member function.

•	Returns an HRESULT value.

pTargetRect

Contains the destination rectangle.

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 from the video renderer sample, SampVid, 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

virtual void GetVideoFormat( VIDEOINFO * pVideoInfo ) PURE;

Returns a VIDEOINFO structure representing the current video format.

pVideoInfo

Returned video format.

To return and check certain information through IBasicVideo, the object needs to 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

The following example from the video renderer sample, SampVid, demonstrates an implementation of this function in a derived class:

VIDEOINFO *CVideoText::GetVideoFormat()

{

    return (VIDEOINFO *) m_pRenderer->m_mtIn.Format();

}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_mtIn data member, defined in the derived class, holds a CMediaType object with the media type of the input pin.


CBaseControlVideo::GetVideoPaletteEntries

HRESULT GetVideoPaletteEntries(long StartIndex,

    long Entries, long *pRetrieved, long *pPalette);

Retrieves a range of palette entries for the video.

•	Returns an HRESULT value.

StartIndex

Zero-based start palette entry.

Entries

Number of entries required.

pRetrieved

Number of colors obtained.

pPalette

Pointer to output buffer for colors.

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

HRESULT GetVideoSize(long *pWidth, long *pHeight);

Retrieves the native video width and height.

•	Returns an HRESULT value.

pWidth

Contains the video width.

pHeight

Contains the video height.


CBaseControlVideo::IsDefaultSourceRect

virtual HRESULT IsDefaultSourceRect(void)PURE;

Determines if the renderer is using the default source rectangle (pure virtual).

•	Returns an HRESULT value.

This member function must be implemented in the derived class. It is called by the CBaseControlVideo::IsUsingDefaultSource member function.

The following example from the video renderer sample, SampVid, 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. m_mtIn, also defined in the derived class, holds a CMediaType object with the media type of the input pin.


CBaseControlVideo::IsDefaultTargetRect

virtual HRESULT IsDefaultTargetRect(void)PURE;

Determines if the renderer is using the default target rectangle (pure virtual).

•	Returns an HRESULT value.

This member function must be implemented in the derived class. It is called by the CBaseControlVideo::IsUsingDefaultDestination member function.

The following example from the video renderer sample, SampVid, 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. m_mtIn, also defined in the derived class, holds a CMediaType object with media type of the the input pin.


CBaseControlVideo::IsUsingDefaultSource

virtual HRESULT IsUsingDefaultSource(void);

Determines if the renderer is using the default source window.

•	Returns an HRESULT value.


CBaseControlVideo::IsUsingDefaultDestination

virtual HRESULT IsUsingDefaultDestination(void);

Determines if the renderer is using the default destination window.

•	Returns an HRESULT value.


CBaseControlVideo::OnUpdateRectangles

virtual HRESULT OnUpdateRectangles();

Called when either the source or destination rectangle changes.

•	Returns an HRESULT value.


CBaseControlVideo::OnVideoSizeChange

virtual HRESULT OnVideoSizeChange();

Passes an EC_VIDEO_SIZE_CHANGED message to the filter graph manager.

•	Returns an HRESULT value.

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 320x240 to 160x120), it should also call it after each change.


CBaseControlVideo::put_DestinationHeight

HRESULT put_DestinationHeight(long DestinationHeight);

Sets the destination rectangle height.

•	Returns an HRESULT value.

DestinationHeight

New destination height.

An application may 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

HRESULT put_DestinationLeft(long DestinationLeft);

Sets the left coordinate of the destination rectangle.

•	Returns an HRESULT value.

DestinationLeft

New left coordinate of destination rectangle.

An application may 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

HRESULT put_DestinationTop(long DestinationTop);

Sets the top coordinate of the destination rectangle.

•	Returns an HRESULT value.

DestinationTop

New top coordinate of the destination rectangle.

An application may 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

HRESULT put_DestinationWidth(long DestinationWidth);

Sets the width of the destination rectangle.

•	Returns an HRESULT value.

DestinationWidth

New destination width.

An application may 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

HRESULT put_SourceHeight(long SourceHeight);

Sets the source rectangle height.

•	Returns an HRESULT value.

SourceHeight

Contains the source height.

An application may 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

HRESULT put_SourceLeft(long SourceLeft);

Sets the source rectangle left coordinate.

•	Returns an HRESULT value.

SourceLeft

New left coordinate of the source rectangle.

An application may 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

HRESULT put_SourceTop(long SourceTop);

Sets the top coordinate of the source rectangle.

•	Returns an HRESULT value.

SourceTop

New top coordinate of the source rectangle.

An application may 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

HRESULT put_SourceWidth(long SourceWidth);

Sets the width of the source rectangle.

•	Returns an HRESULT value.

SourceWidth

New width of the source rectangle.

An application may 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

void SetControlVideoPin(CBasePin *pPin);

Sets the pin used by the filter.

pPin

Pin with which the interface is synchronized.

The interface can only be called 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 whenever it has an interface method called and will return VFW_E_NOT_CONNECTED if it fails.


CBaseControlVideo::SetDefaultDestinationPosition

HRESULT SetDefaultDestinationPosition();

Sets the renderer back to using the default destination position (typically the entire window client area).

•	Returns an HRESULT value.

An application may 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

HRESULT SetDefaultSourcePosition();

Sets the renderer back to using the default source position (typically all the native video).

•	Returns an HRESULT value.

An application may 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

virtual HRESULT SetDefaultSourceRect() PURE;

Sets the default source video rectangle (pure virtual). This in an internal member function that gets called when the source rectangle is reset.

•	Returns an HRESULT value.

Derived classes should override this to reset the source rectangle. It is called from CBaseControlVideo::SetDefaultSourcePosition.

The following example from the video renderer sample, SampVid, demonstrates an implementation of this function in a derived class:

// This is called when we 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. m_mtIn, also defined in the derived class, holds a CMediaType object with media type of the input pin.


CBaseControlVideo::SetDefaultTargetRect

virtual HRESULT SetDefaultTargetRect() PURE;

Sets the default target video rectangle (pure virtual). This is an internal member function that gets called when the source rectangle is reset.

•	Returns an HRESULT value.

Derived classes should override this to reset the destination video rectangle. It is called from the CBaseControlVideo::SetDefaultDestinationPosition member function.

The following example from the video renderer sample, SampVid, demonstrates an implementation of this function in a derived class:

// This is called when we 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. m_mtIn, also defined in the derived class, holds a CMediaType object with the media type of the input pin.


CBaseControlVideo::SetDestinationPosition

HRESULT SetDestinationPosition(long Left, long Top,

    long Width, long Height);

Sets the destination rectangle for the video.

•	Returns an HRESULT value.

Left

New left coordinate.

Top

New top coordinate.

Width

New width.

Height

New height.

An application may 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

HRESULT SetSourcePosition(long Left, long Top,

    long Width, long Height);

Sets a new source position for the video.

•	Returns an HRESULT value.

Left

New left coordinate.

Top

New top coordinate.

Width

New width.

Height

New height.

An application may 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

virtual HRESULT SetSourceRect(RECT *pSourceRect) PURE;

Sets the current source video rectangle (pure virtual). This is an internal member function that gets called when the source rectangle changes.

•	Returns an HRESULT value.

pSourceRect

Contains the source rectangle.

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 from the video renderer sample, SampVid, 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

virtual HRESULT SetTargetRect(RECT *pTargetRect) PURE;

Sets the current target rectangle (pure virtual). This is an internal member function that gets called when the destination rectangle changes.

•	Returns an HRESULT value.

pTargetRect

Contains the destination rectangle.

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 from the video renderer sample, SampVid, 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

Protected Data Members

m_bAutoShow 	Result when the state changes.

m_BorderColour 	Color of the current window border.

m_bCursorHidden 	Determination of whether the cursor is displayed or hidden.

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 either the typical or extended window styles.

GetBorderColour 	Returns the current border color. This is a helper member function.

GetOwnerWindow 	Returns the owning window. This is a helper member function.

IsAutoShowEnabled 	Returns the autoshow property. This is a helper member function.

IsCursorHidden 	Retrieves the current state of the m_bCursorHidden data member without locking the critical section. This is a helper member function.

MessageLoop 	Implements a standard window message procedure.

RerouteIfOwned 	Posts messages to owning windows.

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.

get_MessageDrain 	Returns the current message drain.

get_Owner 	Retrieves the Microsoft® Win32® parent window handle.

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.

get_WindowState 	Retrieves the current state of the window.

get_WindowStyle 	Retrieves the standard window styles.

get_WindowStyleEx 	Retrieves the extended window styles.

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.

GetMaxIdealImageSize 	Retrieves the maximum size of the ideal image.

GetMinIdealImageSize 	Retrieves the minimum size of the ideal image.

GetRestorePosition 	Retrieves the position to which the window will be restored when maximized or iconic.

GetWindowPosition 	Retrieves the current window coordinates.

HideCursor 	Hides or displays the cursor.

IsCursorHidden 	Retrieves the current state of them_bCursorHidden data member.

NotifyOwnerMessage 	Passes on messages that are sent to owning windows.

SetWindowForeground 	Sets the window in the foreground.

SetWindowPosition 	Sets the window position.


CBaseControlWindow::CBaseControlWindow

CBaseControlWindow(CBaseMediaFilter *pFilter,

    CCritSec *pInterfaceLock, TCHAR *pName,

    LPUNKNOWN pUnk, HRESULT *phr);

Constructs a CBaseControlWindow object.

pFilter

Owning media filter object.

pInterfaceLock

Critical section to use for locking.

pName

Object description.

pUnk

Typical Component Object Model (COM) ownership.

phr

OLE return value.

The CBaseControlWindow object implements the IVideoWindow control interface. The CBaseControlWindow object controls the filter that is often affected when methods of the interface are called. For this reason, the CBaseControlWindow object must be synchronized with the filter and therefore requires a critical section. The locking critical section is passed in as the parameter of this constructor. When the IVideoWindow interface methods are called, the object always locks this critical section before proceeding.

Because this class always locks this critical section when called externally, it is difficult for internal filter objects to retrieve property settings from the object. For example, if a filter wants to retrieve the value of the autoshow property, it might try to call CBaseControlWindow::get_AutoShow, which would lock the critical section. The internal object might already have an internal critical section locked, however, and to do this might violate the lock hierarchy for the filter. Therefore, this class provides a number of internal methods to return property settings, such as CBaseControlWindow::IsAutoShowEnabled, and window styles that do not require the critical section to be locked.

All of the IVideoWindow interface methods that this class implements require that the filter be connected correctly with its upstream filter. For this reason, the class is given a pin (using the CBaseControlWindow::SetControlWindowPin member function) with which it should synchronize. Whenever an interface method is called, the CBaseControlWindow object checks that the pin is still connected.


CBaseControlWindow::DoGetWindowStyle

HRESULT DoGetWindowStyle(long *pStyle, long WindowLong);

Retrieves the current normal and extended window styles.

•	Returns an HRESULT value.

pStyle

Contains the appropriate styles.

WindowLong

Either GWL_STYLE or GWL_EXSTYLE.

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

HRESULT DoSetWindowStyle(long Style, long WindowLong);

Changes the typical or extended window styles.

•	Returns an HRESULT value.

Style

Contains the appropriate window styles.

WindowLong

Either GWL_STYLE or GWL_EXSTYLE.

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

HRESULT get_AutoShow(long *AutoShow);

Retrieves the current autoshow state flag.

•	Returns an HRESULT value.

AutoShow

OLE Automation (OA) Boolean flag (0 is off, -1 is on).

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

HRESULT get_BackgroundPalette(long *pBackgroundPalette);

Retrieves the realized palette in the background flag.

•	Returns an HRESULT value.

pBackgroundPalette

OLE Automation Boolean (OA) flag (0 is off, -1 is on).

This member function implements the IVideoWindow::get_BackgroundPalette method. If a video is to be played within another application or document, the application may 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. It should be noted that asking the window to use a different palette will incur very severe performance penalties.


CBaseControlWindow::get_BorderColor

HRESULT get_BorderColor(long *Color);

Retrieves the current border color.

•	Returns an HRESULT value.

Color

Current border color.

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, it is actually a COLORREF which is defined in the Microsoft Win32 Software Development Kit (SDK).

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::get_Caption

HRESULT get_Caption(BSTR *pstrCaption);

Retrieves the current window caption.

•	Returns an HRESULT value.

pstrCaption

Current window caption.

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 may still be set (and retrieved), although it will not be visible to the user.


CBaseControlWindow::get_FullScreenMode

HRESULT get_FullScreenMode(long *FullScreenMode);

Retrieves the current full-screen mode.

•	Returns an HRESULT value.

FullScreenMode

Current full-screen mode.

This member function returns E_NOTIMPL by default. This informs the IVideoWindow plug-in distributor (PID) that this renderer does not implement a full-screen renderer.


CBaseControlWindow::get_Height

HRESULT get_Height(long *pHeight);

Retrieves the current window height.

•	Returns an HRESULT value.

pHeight

Current window height, in pixels.

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 ActiveMovie™. 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::get_Left

HRESULT get_Left(long *pLeft);

Retrieves the current left window coordinate.

•	Returns an HRESULT value.

pLeft

Contains the left coordinate, in pixels.

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 ActiveMovie. 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::get_MessageDrain

HRESULT get_MessageDrain(OAHWND *Drain);

Returns the current message drain.

•	Returns an HRESULT value.

Drain

Current window receiving window messages.

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::get_Owner

HRESULT get_Owner(OAHWND *Owner);

Retrieves the current window owner.

•	Returns an HRESULT value.

Owner

Contains the window owner.

The video window can play back within a document environment. To do this, the window needs to 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::GetRestorePosition

HRESULT GetRestorePosition(long *pLeft, long *pTop,

    long *pWidth, long *pHeight);

Retrieves the position to which the window will be restored when it is not maximized or iconic.

•	Returns an HRESULT value.

pLeft

Value for leftmost coordinate.

pTop

Value for top of the window.

pWidth

Value for width of the window.

pHeight

Value for height of window.

This is the same as the values returned by the Microsoft Win32 GetWindowPosition function when the window is neither maximized nor iconic.


CBaseControlWindow::get_Top

HRESULT get_Top(long *pTop);

Retrieves the top window coordinate.

•	Returns an HRESULT value.

pTop

Contains the top coordinate, in pixels.

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 ActiveMovie. 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::get_Visible

HRESULT get_Visible(long *pVisible);

Retrieves the current window visibility.

•	Returns an HRESULT value.

pVisible

OLE Automation (OA) Boolean flag (0 is off, -1 is on).

This member function returns -1 if the window has the WS_VISIBLE style; 0 otherwise.


CBaseControlWindow::get_Width

HRESULT get_Width(long *pWidth);

Retrieves the current window width.

•	Returns an HRESULT value.

pWidth

Contains the window width, in pixels.

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 ActiveMovie. 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::get_WindowState

HRESULT get_WindowState(long *pWindowState);

Retrieves the window state.

•	Returns an HRESULT value.

pWindowState

Contains the window state.

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

HRESULT get_WindowStyle(long *pWindowStyle);

Retrieves the current window styles.

•	Returns an HRESULT value.

pWindowStyle

Contains the window styles.

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

HRESULT get_WindowStyleEx(long *pWindowStyleEx);

Retrieves the extended window styles.

•	Returns an HRESULT value.

pWindowStyleEx

Contains the extended window styles.

This member function retrieves the extended window styles. It calls the CBaseControlWindow::DoGetWindowStyle member function.


CBaseControlWindow::GetBorderColour

COLORREF GetBorderColour();

Returns the current window border color, m_BorderColour.

•	Returns the color of the border.

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::GetMaxIdealImageSize

HRESULT GetMaxIdealImageSize(long *pWidth, long *pHeight);

Retrieves the maximum ideal image size.

•	Returns an HRESULT value.

pWidth

Maximum ideal width, in pixels.

pHeight

Maximum ideal height, in pixels.

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 only be called 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::GetMinIdealImageSize

HRESULT GetMinIdealImageSize(long *pWidth, long *pHeight);

Retrieves the minimum ideal image size.

•	Returns an HRESULT value.

pWidth

Minimum ideal width, in pixels.

pHeight

Minimum ideal height, in pixels.

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 only be called 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::GetOwnerWindow

HWND GetOwnerWindow() ;

Returns the owning window handle, m_hwndOwner.

•	Returns an internal method to return the owner window.

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::GetWindowPosition

HRESULT GetWindowPosition(long *pLeft, long *pTop,

    long *pWidth, long *pHeight);

Retrieves the coordinates for the window.

•	Returns an HRESULT value.

pLeft

Contains the left coordinate, in screen coordinates.

pTop

Contains the top coordinate, in screen coordinates.

pWidth

Contains the window width, in screen coordinates.

pHeight

Contains the window height, in screen coordinates.


CBaseControlWindow::HideCursor

HRESULT HideCursor(long HideCursor);

Hides or displays the cursor.

•	Returns an HRESULT value.

HideCursor

Set to OATRUE to hide the cursor, or OAFALSE to display the cursor.


CBaseControlWindow::IsCursorHidden

HRESULT IsCursorHidden(long *CursorHidden);

BOOL HideCursor();

Retrieves the current state of the m_bCursorHidden data member.

•	When called without a parameter, returns OATRUE if the cursor is hidden, OAFALSE if the cursor is visible.

When called with a parameter, returns an HRESULT value.

CursorHidden

Value of m_bCursorHidden.

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

BOOL IsAutoShowEnabled();

Returns the autoshow property setting, m_bAutoShow.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Autoshow is enabled.

FALSE 	Autoshow is disabled.

This property helps simple applications function. After the filter is connected, the window will be shown automatically when the filter pauses or runs, if this property is set on the window that is typically hidden. The window should not be hidden when the filter stops, however. If this is set to off, the window is made visible only when the application calls CBaseControlWindow::put_Visible or CBaseControlWindow::put_WindowState with the appropriate parameters.

This internal method allows the property value to be retrieved without calling through the IVideoWindow::get_AutoShow interface method.


CBaseControlWindow::MessageLoop

HRESULT MessageLoop();

Implements a standard Microsoft Win32 message loop procedure.

•	Always returns NOERROR.

The base window class from which this class is derived has a window message procedure; however, when an owning window has been set through the IVideoWindow interface, this object is required to forward certain mouse and keyboard messages to the owner. This class, therefore, has a separate message loop for this purpose; the base class message loop method is never used in this case.


CBaseControlWindow::NotifyOwnerMessage

HRESULT NotifyOwnerMessage(long hwnd, long uMsg,

    long wParam, long lParam);

Called when certain messages are sent to an owning window.

•	Returns an HRESULT value.

hwnd

Window to which the message was sent.

uMsg

Message details.

wParam

Standard WPARAM parameter.

lParam

Standard LPARAM parameter.

When the video window is a child of another window, it will not be sent certain top-level window messages. For example, WM_MOVE, WM_SYSCOLORCHANGE, and WM_DISPLAYCHANGE messages will not be sent. These messages may be of value to a renderer because they could affect its behavior.

The IVideoWindow plug-in distributor (PID) may be requested to make a window become a child of another window. When this occurs, the PID will look for certain messages that may 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 using the Win32 SendMessage function.


CBaseControlWindow::put_AutoShow

HRESULT put_AutoShow(long AutoShow);

Sets the autoshow state flag.

•	Returns an HRESULT value.

AutoShow

OLE Automation (OA) Boolean flag (0 is off, -1 is on).

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

HRESULT put_BackgroundPalette(long BackgroundPalette);

Sets a flag to realize the palette in the background.

•	Returns an HRESULT value.

BackgroundPalette

OLE Automation (OA) Boolean flag (0 is off, -1 is on).

To play a video within another application or document, the application may 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 incur severe performance penalties.


CBaseControlWindow::put_BorderColor

HRESULT put_BorderColor(long Color);

Changes the border color.

•	Returns an HRESULT value.

Color

Contains the new border color.

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, it is actually a COLORREF, as defined in the Microsoft Win32 Software Development Kit (SDK).


CBaseControlWindow::put_Caption

HRESULT put_Caption(BSTR strCaption);

Sets the window title or caption.

•	Returns an HRESULT value.

strCaption

Contains the new window caption.

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 may still be set (and retrieved), although it will not be visible to the user.


CBaseControlWindow::put_FullScreenMode

HRESULT put_FullScreenMode(long FullScreenMode);

Sets the full-screen mode of the renderer.

•	Returns an HRESULT value.

FullScreenMode

Full-screen mode to apply.

The current implementation returns E_NOTIMPL. A video renderer that implements a full-screen mode should override this member function and implement whatever modes it supports.


CBaseControlWindow::put_Height

HRESULT put_Height(long Height);

Sets the window height.

•	Returns an HRESULT value.

Height

New window height, in pixels.

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 ActiveMovie. 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::put_Left

HRESULT put_Left(long Left);

Sets the left coordinate for the window.

•	Returns an HRESULT value.

Left

New left coordinate, in pixels.

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 ActiveMovie. 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::put_MessageDrain

HRESULT put_MessageDrain(OAHWND Drain);

Sets the window to receive window messages sent to the video renderer.

•	Returns an HRESULT value.

Drain

Window to post messages to.

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

HRESULT put_Owner(OAHWND Owner);

Sets the window owner.

•	Returns an HRESULT value.

Owner

New window owner.

The video window can play back within a document environment. To do this, the window needs to 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 to 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.

Note  After setting the owner of video window using this method, you must reset the owner to 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.


CBaseControlWindow::put_Top

HRESULT put_Top(long Top);

Sets the top window coordinate.

•	Returns an HRESULT value.

Top

New top coordinate, in pixels.

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 ActiveMovie. 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::put_Visible

HRESULT put_Visible(long Visible);

Makes the window either visible or hidden.

•	Returns an HRESULT value.

Visible

OLE Automation (OA) Boolean flag (0 is off, -1 is on).

If the Visible parameter is 0, the window will be hidden; otherwise, it will be shown.


CBaseControlWindow::put_Width

HRESULT put_Width(long Width);

Sets the window width.

•	Returns an HRESULT value.

Width

New window width, in pixels.

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 ActiveMovie. 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::put_WindowState

HRESULT put_WindowState(long WindowState);

Sets the window state.

•	Returns an HRESULT value.

WindowState

New window state.

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

HRESULT put_WindowStyle(long WindowStyle);

Sets the standard Windows-based styles.

•	Returns an HRESULT value.

WindowStyle

New window styles.

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

HRESULT put_WindowStyleEx(long WindowStyleEx);

Sets the extended window styles.

•	Returns an HRESULT value.

WindowStyleEx

New extended window styles.

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::RerouteIfOwned

BOOL RerouteIfOwned(PMSG pMessage);

Distributes messages to the owned window.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Message was posted.

FALSE 	Message was not posted.

pMessage

Message details.

When the window is owned, it will pass certain classes of messages to the owning window (such as keyboard and mouse events). This is called by the message loop method to pass the message on, if necessary.


CBaseControlWindow::SetControlWindowPin

void SetControlWindowPin(CBasePin *pPin);

Sets the pin with which to synchronize.

pPin

Pin with which the interface is synchronized.

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

HRESULT SetWindowForeground(long Focus);

Sets the window in the foreground and optionally gives it the focus.

•	Returns an HRESULT value.

Focus

Optional focus.


CBaseControlWindow::SetWindowPosition

HRESULT SetWindowPosition(long Left, long Top,

    long Width, long Height);

Sets the window position on the desktop.

•	Returns an HRESULT value.

Left

New left coordinate.

Top

New top coordinate.

Width

Width of the window.

Height

Height of the window.


CBaseDispatch Class

The CBaseDispatch class is a base class that implements the IDispatch interface for use in a dual interface. A dual interface provides OLE Automation (OA) and custom interface access to an interface.

CMediaControl and CMediaPosition (and other dual-interface support classes) are derived from this class or have members that are instances of this class.

For more information about the IDispatch methods, see the OLE documentation included with the Microsoft® Win32® Software Development Kit (SDK).

Member Functions

CBaseDispatch 	Constructs a CBaseDispatch object.

Implemented IDispatch Methods

GetIDsOfNames 	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 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.


CBaseDispatch::CBaseDispatch

CBaseDispatch();

Constructs a CBaseDispatch object.


CBaseDispatch::GetIDsOfNames

HRESULT GetIDsOfNames(REFIID riid,

    OLECHAR ** rgszNames, UINT cNames,

    LCID lcid, DISPID * rgdispid);

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 IDispatch::Invoke method.

•	Returns one of the following values.

Value 	Meaning

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 class identifier was not recognized.

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

The local context in which to interpret the names.

rgdispid

Caller-allocated array, each element of which contains an identifier that corresponds to one of the names passed in the rgszNames parameter. The first element represents the member name; the subsequent elements represent each of the parameters of the member.


CBaseDispatch::GetTypeInfo

HRESULT GetTypeInfo(UINT itinfo, LCID lcid,

    ITypeInfo ** pptinfo);

Retrieves a type-information object, which can retrieve the type information about an interface.

•	Returns an HRESULT value.

itinfo

The type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

The local identifier for the type information. An object may return different type information for different languages. This capability is important for classes that support localized member names. For classes that do not support localized member names, ignore this parameter.

pptinfo

A pointer to the type-information object requested.


CBaseDispatch::GetTypeInfoCount

HRESULT GetTypeInfoCount(UINT * pctinfo);

Retrieves the number of type-information interfaces provided by an object.

•	Returns an HRESULT value.

pctinfo

Points 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.


CBaseFilter Class

CBaseFilter is an abstract base class from which all filters are derived. It supports the Component Object Model (COM) IFilter interface and is derived from the CUnknown class. This class supports the enumeration of pins by calling the pure virtual member functions CBaseFilter::GetPin and GetPinCount. These member functions must be overridden by any derived class.

The CBaseFilter class assumes that all the filter's pins are derived from the CBasePin class. CBaseFilter::GetPin must return a pointer to CBasePin.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Protected Data Members

m_pName 	Filter name.

m_PinVersion 	Current version of the pins used on the filter.

m_tStart 	Offset from the stream time to the reference time.

m_State 	Current state: running or paused.

m_pClock 	Filter graph's reference clock.

m_pGraph 	Pointer to a graph to which this filter belongs.

m_pLock 	Pointer to the critical section used for locking.

m_pSink 	Pointer to the IMediaEventSink interface on the filter graph manager.

m_clsid 	Class identifier (CLSID) used for serialization using IPersist.

Member Functions

CBaseFilter 	Constructs a CBaseFilter object.

GetFilterGraph 	Returns the filter graph associated with the filter. This is used in the implementation of CEnumPins.

IncrementPinVersion 	Adds 1 to the pin version stored in m_PinVersion.

IsActive 	Determines if the filter is currently active (running or paused) or stopped.

NotifyEvent 	Sends an event notification to the filter graph.

Overridable Member Functions

GetPin 	Returns a pointer to the requested pin.

GetPinCount 	Returns the number of pins currently available on this object.

GetPinVersion 	Returns the current version of the base filter for comparison with the version with which the pin was initialized. This member function can be overridden if pins are being created dynamically.

GetSetupData 	Retrieves the registration data associated with the filter.

StreamTime 	Returns the current stream time.

Implemented IPersist Methods

GetClassID 	Returns the class identifier of this filter.

Implemented IMediaFilter Methods

GetState 	Retrieves the current state of the filter.

GetSyncSource 	Retrieves the current reference clock in use by this filter.

Pause 	Tells the filter to transition to State_Paused state.

Run 	Tells the filter to transition to State_Running state. Passes a time value to synchronize independent streams.

SetSyncSource 	Tells the filter to which reference clock it should synchronize activity.

Stop 	Tells the filter to transition to the State_Stopped state.

Implemented IFilter Methods

EnumPins 	Provides an enumerator for this pin's preferred media types (implemented by this class).

FindPin 	Retrieves the pin with the specified identifier.

JoinFilterGraph 	Notifies a filter that it has joined a filter graph (implemented by this class).

QueryFilterInfo 	Gets information about the specified filter (implemented by this class).

QueryVendorInfo 	Retrieves optional information supplied by a vendor for the specified filter. (Default implementation in this class returns E_NOTIMPL.)

Implemented IAMovieSetup Methods

Register 	Adds the filter to the registry.

Unregister 	Removes the filter from the registry.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Passes out pointers to any interfaces added to the derived filter class.


CBaseFilter::CBaseFilter

CBaseFilter(TCHAR *pName, LPUNKNOWN pUnk,

    CCritSec *pLock, CLSID clsid, HRESULT *phr);

Constructs a CBaseFilter object.

pName

Pointer to an object description.

pUnk

IUnknown interface of the delegating object.

pLock

Pointer to an object that maintains the lock.

clsid

Class identifier to be used to serialize this filter.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.


CBaseFilter::EnumPins

HRESULT EnumPins(IEnumPins ** ppEnum);

Returns an IEnumPins pointer that can be used to enumerate all of the pins available on this filter.

•	Returns an HRESULT value.

ppEnum

Pointer to the IEnumPins interface to retrieve.

This member function implements the IFilter::EnumPins method. It uses the CEnumPins object to construct an enumerator and retrieves the IEnumPins interface from the CEnumPins object. The implementation of CEnumPins::Next calls the CBaseFilter::GetPin member function, which the derived class must provide. The IEnumPins interface is used by the filter graph manager when adding the filter to the filter graph.


CBaseFilter::FindPin

HRESULT FindPin(LPCWSTR Id, IPin **ppPin);

Retrieves the pin with the specified identifier.

•	The default implementation by this member function returns S_OK if the pin name was found or VFW_E_NOT_FOUND otherwise.

Id

Identifier of the pin.

ppPin

Pointer to the IPin interface for this pin after the filter has been restored.

This member function provides a base class definition of the IFilter::FindPin method that, along with the IPin::QueryId method, is used to implement persistent filter graphs. A filter must be able to translate the IPin interface pointers to its pins into identifiers that can be saved along with the configuration of the filter graph. It does this by using the IPin::QueryId method. It must then be able to convert those identifiers back into IPin interface pointers when the filter and its connections are restored as part of a persistent filter graph. This is accomplished using the IFilter::FindPin method.

By default, the base classes use the pin name in the CBasePin::m_pName data member, so implementing this member function in your derived filter class is not normally required.

The ppPin parameter is set to NULL if the identifier cannot be matched.


CBaseFilter::GetClassID

HRESULT GetClassID(CLSID *pClsID);

Fills the pClsID parameter with the class identifier of this filter (from m_clsid).

•	Returns an HRESULT value.

pClsID

Pointer to the class identifier to be filled out.


CBaseFilter::GetFilterGraph

IFilterGraph *GetFilterGraph();

Returns the filter graph associated with the filter.

•	Returns the value of m_pGraph.


CBaseFilter::GetPin

virtual CBasePin *GetPin(int n) PURE;

Returns a CBasePin object on the filter.

•	Returns a pointer to the pin specified by the n parameter.

n

Number of the specified pin.

Override this member function to return a pointer to the nth pin on this filter. CBaseFilter adds a reference to it, when necessary, before passing it to any other object. This member function is called by the base class CEnumPins::Next member function to retrieve pins for the IEnumPins interface, which is used by the filter graph manager.


CBaseFilter::GetPinCount

virtual int GetPinCount() PURE;

Returns the number of supported pins.

•	Returns the pin count.

Override this member function to return the count of pins currently available on this object.


CBaseFilter::GetPinVersion

virtual long GetPinVersion();

Returns the version number of the pin.

•	By default, returns the value of m_PinVersion. If overridden, this member function should return the pin version number.

Returns the current version of the filter that matches the version used to initialize the pin. The enumerator calling this member function performs the matching.

A filter provides an enumerator to gain access to the input and output pins that it keeps. Each time a pin enumerator's method is called, the pin enumerator calls the CBaseFilter::GetPinVersion member function to ensure that the base filter's version matches the version with which the pin enumerator was initialized.

A filter class may override CBaseFilter::GetPinVersion if there is a need to increment the version by changing the pins available dynamically. Or it can more easily call IncrementPinVersion.

GetPinVersion does not lock the filter because the enumerators are designed to be separate objects. The derived class's GetPinVersion will likely have to do some specialized locking with the part of the object responsible for creating and deleting pins.


CBaseFilter::GetSetupData

virtual LPAMOVIESETUP_FILTER GetSetupData();

Retrieves the registration data associated with the filter.

•	Returns a pointer to an AMOVIESETUP_FILTER structure containing registration information for the filter.

You must override this member function and implement it to return an AMOVIESETUP_FILTER structure containing its associated AMOVIESETUP_PIN and AMOVIESETUP_MEDIATYPE structures for pin and media type information. This member function is called from the CBaseFilter::Register member function.


CBaseFilter::GetState

HRESULT GetState(DWORD dwMilliSecsTimeout,

    FILTER_STATE * State);

Retrieves the current state of the filter.

•	Returns S_OK.

dwMilliSecsTimeout

Duration of the time-out, in milliseconds. To block indefinitely, pass INFINITE.

State

Holds the returned state of the filter.

This member function implements the IMediaFilter::GetState method. It returns the value of the m_State data member. Override this member function if the state changes in your filter are not synchronous.


CBaseFilter::GetSyncSource

HRESULT GetSyncSource(IReferenceClock ** pClock);

Retrieves the current reference clock in use by this filter.

•	Returns an HRESULT value.

pClock

Pointer to a reference clock; will be set to the IReferenceClock interface.

This member function implements the IMediaFilter::GetSyncSource method. It returns the value of m_pClock after adding a reference to it. Be sure to release the interface by calling the IUnknown::Release method when finished with the pointer.


CBaseFilter::IncrementPinVersion

void IncrementPinVersion();

Adds 1 to the version number of the pin.

By default, increments the value of m_PinVersion.


CBaseFilter::IsActive

BOOL IsActive(void);

Determines if the filter is currently active (running or paused) or stopped.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Filter is paused or running.

FALSE 	Filter is stopped.


CBaseFilter::JoinFilterGraph

HRESULT JoinFilterGraph(IFilterGraph * pGraph,

    LPCWSTR pName);

Notifies a filter that it has joined a filter graph.

pGraph

Pointer to the filter graph to join.

pName

[in, string] Name of the filter being added.

This member function implements the IFilter::JoinFilterGraph method. It assigns the pGraph filter graph pointer to the m_pGraph data member and also obtains the IMediaEventSink interface from the filter graph manager to allow the filter to post event notifications to the filter graph manager.

The filter should store the IMediaEventSink interface for later use because it may need to notify the interface about events, but it should not increase the reference count on the filter graph manager object. A null pointer indicates that the filter is no longer part of a graph.


CBaseFilter::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IFilter, IMediaFilter, IPersist, IAMovieSetup, and IUnknown interfaces. Override this class to return other interfaces on the object in the derived class.


CBaseFilter::NotifyEvent

HRESULT NotifyEvent(long EventCode, long EventParam1,

    long EventParam2);

Sends an event notification to the filter graph.

•	Returns S_OK if delivered, S_FALSE if the filter graph does not sink events, or an error otherwise.

EventCode

Identifier of the event.

EventParam1

First parameter of the event.

EventParam2

Second parameter of the event.

For a list of notification codes and event parameter values, see ActiveMovie Event Notification Codes.


CBaseFilter::Pause

HRESULT Pause (void);

Transitions the filter to State_Paused state if it is not in this state already.

•	Returns an HRESULT value.

This member function implements the IMediaFilter::Pause method. If the filter is in State_Stopped state, the CBasePin::Active member function is called for each of the filter's pins to which it is connected. If this member function succeeds, the filter's m_State member variable is set to State_Paused. If any pin returns a failure return value from its Active method, the function fails and the state is not changed.

This member function holds the filter's lock.


CBaseFilter::QueryFilterInfo

HRESULT QueryFilterInfo(FILTER_INFO * pInfo);

Returns information about the filter.

•	Returns an HRESULT value.

pInfo

Pointer to a FILTER_INFO structure to fill in.

This member function implements the IFilter::QueryFilterInfo method. It copies the name of the filter from m_pName and the pointer to the filter graph interface from m_pGraph into the FILTER_INFO structure before returning.

Note that the IFilterGraph interface passed out by this member function is reference counted and so must be released when the caller has finished with it.


CBaseFilter::QueryVendorInfo

HRESULT QueryVendorInfo(LPWSTR * pVendorInfo);

Returns a vendor information string.

•	Returns an HRESULT value (E_NOTIMPL by default).

pVendorInfo

Pointer to a string containing vendor information.

This member function implements the IFilter::QueryVendorInfo method but only to return E_NOTIMPL. Filters that want to expose vendor information must override this member function. If implemented in a derived class, callers should free memory when done using it by calling the Microsoft® Win32® CoTaskMemFree function.


CBaseFilter::Register

HRESULT Register();

Adds the filter to the registry.

•	Returns an HRESULT value.

This member function implements the IAMovieSetup::Register method and registers the filter, its pins, and the media type associated with the pins. It does this by first calling GetSetupData to retrieve the setup data and then calling the IFilterMapper::RegisterFilter, IFilterMapper::RegisterPin, and IFilterMapper::RegisterPinType methods.


CBaseFilter::Run

HRESULT Run (void);

Transitions the filter to State_Running state if it is not in this state already.

•	Returns an HRESULT value.

If the filter is in State_Stopped state, the CBaseFilter::Pause method is called first to transition the filter to State_Paused state, which has the effect of activating any of the filter's connected pins. If any pin returns a failure return code from its Active method, the function fails and the state is not changed. If this member function succeeds, the filter's m_State member variable is set to State_Running. This member function holds the filter's lock.


CBaseFilter::SetSyncSource

HRESULT SetSyncSource (IReferenceClock * pClock);

Identifies the reference clock to which the filter should synchronize activity.

•	Returns an HRESULT value.

pClock

Pointer to the IReferenceClock interface.

This member function implements the IMediaFilter::SetSyncSource method. It sets the m_pClock data member to the pClock parameter and increments the reference count on the IReferenceClock interface passed in.

This member function is most important to rendering filters and may not apply to other filters.


CBaseFilter::Stop

HRESULT Stop(void);

Transitions the filter to State_Stopped state if it is not in this state already.

•	Returns an HRESULT value.

This member function implements the IMediaFilter::Stop method. It first calls the CBasePin::Inactive member function on all of its pins that have a connection and then sets the filter's m_State member variable to State_Stopped.

This member function holds the filter's lock.


CBaseFilter::StreamTime

virtual HRESULT StreamTime(CRefTime& rtStream);

Returns the current stream time.

•	Returns an HRESULT value, which can include the following values.

Value 	Meaning

S_OK 	Stream time returned in the rtStream parameter.

VFW_E_NO_CLOCK 	No reference clock is available.

E_FAIL 	Unable to get time from clock.

rtStream

Current stream time.

Current stream time is the reference clock time minus the stream time offset. All samples with time stamps less than or equal to this time should have been presented.


CBaseFilter::Unregister

HRESULT Unregister();

Removes the filter from the registry.

•	Returns an HRESULT value.

This member function implements the IAMovieSetup::Unregister method and calls the IFilterMapper::UnregisterFilter method to remove the filter from the registry. This effectively removes the pins and media types as well.


CBaseInputPin Class

CBaseInputPin is an abstract base class derived from CBasePin that adds support for IMemInputPin in addition to the IPin interface support provided by CBasePin. Its IMemInputPin::GetAllocator method returns a CMemAllocator object. Derive your input pin from this class.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Protected Data Members

m_pAllocator 	Pointer to the default memory allocator.

m_bFlushing 	In the state of flushing; if TRUE, all IMemInputPin::Receive methods are returned with S_FALSE.

m_bReadOnly 	If TRUE, indicates that the allocator being used contains samples that are read-only.

Member Functions

CBaseInputPin 	Constructs a CBaseInputPin object.

IsReadOnly 	Checks the m_bReadOnly data member and returns its value.

IsFlushing 	Checks the m_bFlushing data member and returns its value.

Overridable Member Functions

CheckStreaming 	Verifies conditions for continuing with a streaming operation.

Inactive 	Switches the pin to an inactive state.

Implemented IPin Methods

BeginFlush 	Informs the pin to begin a flush operation.

Disconnect 	Releases the stored allocator.

EndFlush 	Informs the pin to end a flush operation.

Implemented IMemInputPin Methods

GetAllocator 	Returns the allocator interface that this input pin would like the output pin to use.

GetAllocatorRequirements 	Indicates an optional method to use if the filter has specific alignment or prefix requirements but could use an upstream allocator.

NotifyAllocator 	Tells the input pin which allocator the output pin is actually going to use.

Receive 	Returns the next block of data from the stream. (Override this method to process a sample being passed in.)

ReceiveCanBlock 	Determines if sending an IMemInputPin::Receive method might block.

ReceiveMultiple 	Returns the next block of data from the stream. (Override this method to process samples being passed in.)

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Retrieves an interface from the subobject, not the aggregated object.

Implemented IQualityControl Methods

Notify 	Notifies the recipient that a quality-control change is requested. (Override on the output pin only. This implementation returns NOERROR.)


CBaseInputPin::BeginFlush

HRESULT BeginFlush(void);

Informs the pin to begin a flush operation.

•	Returns an HRESULT value.

This member function implements the IPin::BeginFlush method. When this method is called, the pin is entering flush state. You must override this method in your derived class, but you should call this base class first in your implementation because it sets m_bFlushing so that no more IMemInputPin::Receive calls will succeed.

The overriding member function should then carry out the following steps:

1	Discard any queued data.

2	Free any pin blocked by the Receive method.

3	Pass the IPin::BeginFlush method to any downstream pins.

IPin::BeginFlush is not logically part of the media stream and can be optimized in the sense that if a pin has passed no data downstream before this method is called, there is no need to pass this notification on.

An example of an overriding implementation of this member function can be found in the CTransformInputPin::BeginFlush member function, which uses the CBaseOutputPin::DeliverBeginFlush member function to perform the last step.


CBaseInputPin::CBaseInputPin

CBaseInputPin::CBaseInputPin(TCHAR *pObjectName,

    CBaseFilter *pFilter, CCritSec *pLock, HRESULT *phr,

    LPCWSTR pPinName);

Constructs a CBaseInputPin object.

pObjectName

Name of the class object.

pFilter

Pointer to the filter that owns this pin.

pLock

Pointer to the CCritSec critical section object used to lock the pin.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.

pPinName

Name of the pin.


CBaseInputPin::CheckStreaming

virtual HRESULT CheckStreaming();

Verifies conditions for continuing with a streaming operation.

•	Returns one of the following HRESULT values, depending on the state.

Value 	Meaning

S_OK 	Receive or EndOfStream operations can safely proceed.

S_FALSE 	Currently in flushing state.

VFW_E_RUNTIME_ERROR 	Run-time error occurred while processing a previous sample.

VFW_E_WRONG_STATE 	Filter is in the State_Stopped state.

Conditions checked in this member function include whether the filter is connected, if it is in an active state, if it is not currently flushing data, and if it has not just issued a run-time error. If all of these conditions pass, it returns S_OK.

You can override this member function to add restrictions defined by your derived class. The overriding member function should call this base class implementation to check for conditions here as well.

This function member should be called from any override of the CBaseInputPin::Receive or CBasePin::EndOfStream member function (or they should do some equivalent check).


CBaseInputPin::Disconnect

HRESULT Disconnect();

Releases the stored allocator.

•	Returns an HRESULT value.

This member function overrides the CBasePin::Disconnect member function. It calls CBasePin::Disconnect first and then releases the allocator held by m_pAllocator.


CBaseInputPin::EndFlush

HRESULT EndFlush(void);

Informs the pin to end a flush operation and notifies the pin that it can start accepting data again.

•	Returns an HRESULT value.

This member function implements the IPin::EndFlush method. When this method is called, the pin is beginning to end a flush operation. Your derived class must override this member function but should call this member function at the end of your implementation to clear m_bFlushing so that IMemInputPin::Receive calls will succeed.

Before calling this base class implementation, your overriding member function should perform the following steps:

1	Ensure that your filter will not push any additional data. (To do this, synchronize with a thread, stop it pushing, and discard any queued data.)

2	Pass the EndFlush method downstream by calling the method on the downstream filter's input pin.

IPin::EndFlush is not logically part of the media stream. It can be optimized in the sense that if a pin has passed no data downstream before this method is called, there is no need to pass this notification on.

An example of an overriding implementation of this member function can be found in the CTransformInputPin::EndFlush member function, which uses the CBaseOutputPin::DeliverEndFlush member function to perform the last step.


CBaseInputPin::GetAllocator

HRESULT GetAllocator(IMemAllocator ** ppAllocator);

Returns the allocator interface that this input pin identifies as the interface for the output pin to use.

•	Default implementation returns either E_OUTOFMEMORY if an allocator cannot be created or NOERROR upon success.

ppAllocator

Pointer to an obtained IMemAllocator object.

This member function implements the IMemInputPin::GetAllocator method, which is called by the connected output pin to retrieve an allocator to use for transporting media samples. By default, this member function creates a CMemAllocator object and obtains the IMemAllocator interface, to which it adds a reference count for the pin when assigning it to the m_pAllocator data member and adds another reference count before passing it back to the output pin.

Override this member function if your filter has another allocator, such as one from a downstream pin, or a specialized allocator to offer the connected output pin.


CBaseInputPin::GetAllocatorRequirements

HRESULT GetAllocatorRequirements(

    ALLOCATOR_PROPERTIES * pProps);

Optional member function to use if the filter has specific alignment or prefix requirements but could use an upstream allocator.

•	Returns an HRESULT value. Returns E_NOTIMPL by default.

pProps

ALLOCATOR_PROPERTIES structure containing the required size, count, and alignment of the allocator.

Override this member function if you have specific alignment or prefix requirements but could use an upstream allocator.


CBaseInputPin::Inactive

HRESULT Inactive(void);

Releases the allocator's memory.

•	Returns an HRESULT value.

This member function is called through IMediaFilter, which is responsible for locking the object first.


CBaseInputPin::IsFlushing

BOOL IsFlushing(void);

Checks the m_bFlushing data member and returns its value.

•	Returns TRUE if the input pin is flushing data; otherwise, returns FALSE.


CBaseInputPin::IsReadOnly

BOOL IsReadOnly(void);

Checks the m_bReadOnly data member and returns its value.

•	Returns TRUE if the allocator has read-only samples; otherwise, returns FALSE.


CBaseInputPin::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IMemInputPin and IUnknown interfaces. Override this class to return other interfaces on the object in the derived class.


CBaseInputPin::Notify

HRESULT Notify(IFilter * pSelf, Quality q);

Notifies the recipient that a quality change is requested.

•	Returns NOERROR by default.

pSelf

Pointer to the filter that is sending the quality notification.

q

Quality notification structure.

The IQualityControl::Notify method is usually implemented on the output pin, because quality-control messages are passed upstream, and not on the input pin.


CBaseInputPin::NotifyAllocator

HRESULT NotifyAllocator(IMemAllocator * pAllocator,

    BOOL bReadOnly);

Notifies the input pin as to which allocator the output pin is actually going to use.

•	Default implementation returns NOERROR.

pAllocator

Pointer to the IMemAllocator object to use. This may or may not be the same IMemAllocator object that the input pin provided in the IMemInputPin::GetAllocator method (the output pin could provide its own allocator).

bReadOnly

Flag to indicate if the samples from this allocator are read-only.

This member function implements the IMemInputPin::NotifyAllocator method, which is called by the connected output pin to inform the input pin of the chosen allocator for the memory transport. Override this member function if your filter cares about this information. By default, this sets the m_pAllocator data member to the allocator interface passed in after adding a reference count to that interface.


CBaseInputPin::Receive

HRESULT Receive(IMediaSample * pSample);

Returns the next block of data from the stream.

•	Returns an HRESULT value.

pSample

Pointer to a media sample.

This member function implements the IMemInputPin::Receive method. It first checks that it can process the sample by calling CBaseInputPin::CheckStreaming; if that member function does not return S_OK, Receive returns immediately with the value returned by CBaseInputPin::CheckStreaming.

This base class member function checks to see if the format has changed with this media sample; if so, it checks that the filter will accept it, generating a run-time error if not. If a run-time error is raised, the m_bRunTimeError data member is set so that no more samples will be accepted.

The overriding member function does something with the passed-in sample, such as calling a member function to transform it or pass it downstream.

This is a blocking synchronous call. Typically no blocking occurs, but if a filter cannot process the sample immediately, it may use the calling application's thread to wait until it can.

Call the IUnknown::AddRef method if you need to hold the returned data block beyond the completion of the IMemInputPin::Receive method. If you call AddRef, be sure to call IUnknown::Release when done with it.


CBaseInputPin::ReceiveCanBlock

HRESULT ReceiveCanBlock(void);

Determines if the implementation of the IMemInputPin::Receive method might block on the connected output pin.

•	Returns an HRESULT value. The following specific success values can be returned.

Value 	Meaning

S_FALSE 	Input pin will not block on a Receive method.

S_OK 	Input pin may block on a Receive method.

This member function implements the IMemInputPin::ReceiveCanBlock method. The base class implementation calls the IMemInputPin::ReceiveCanBlock method on the input pin connected to each of the filter's output pins.

This member function is useful because an output pin from a filter might require notification if its thread might be blocked when it calls the Receive method on the connected input pin. For example, a source filter might prefer to keep reading and buffering data rather than to be blocked, and may choose to start another thread to wait on the blocking Receive method. See the COutputQueue base class for queuing samples to input pins that potentially block.


CBaseInputPin::ReceiveMultiple

HRESULT ReceiveMultiple(IMediaSample ** pSamples,

    long nSamples, long * nSamplesProcessed);

Returns the next block of data from the stream. This method behaves much like the IMemInputPin::Receive method, but it works with multiple samples. Override this function if you can usefully process samples in batches.

•	Returns an HRESULT value.

pSamples

Pointer to an array of samples.

nSamples

Number of samples to process.

nSamplesProcessed

Number of samples processed.

This member function implements the IMemInputPin::ReceiveMultiple method. It is implemented to call the CBaseInputPin::Receive member function in a loop for nSamples number of iterations.


CBaseList Class

The CBaseList class represents a list of pointers to objects. No storage management or copying is done on the objects that are pointed to.

The implementation allows for objects to be on multiple lists simultaneously and does not require support in the objects themselves; therefore, it is particularly useful for holding variable-length lists of interface pointers.

The implementation is not multithread safe. External locks are required to maintain the integrity of the list when it is accessed from more than one thread simultaneously.

The POSITION type definition represents a position that is actually a void pointer. A position represents a cursor on the list that can be set to identify any element. NULL is a valid value, and several operations regard NULL as the position that is "one step off the end of the list." (In an n element list there are n+1 places to insert, and NULL is that n+1 value.) The position of an element in the list is only invalidated if that element is deleted. Move operations may indicate that what was a valid position in one list is now a valid position in a different list.

Some operations, which at first sight seem illegal, are allowed as harmless no operations (no-ops). For example, the CBaseList::RemoveHeadI member function is legal on an empty list, and it returns NULL. This allows an atomic way to test if there is an element there and, if so, to retrieve it.

Single-element operations return positions, where a non-null value indicates that it worked. Entire list operations return a Boolean value, where TRUE indicates success.

Member Functions

AddAfter 	Inserts a list of nodes after the specified node.

AddAfterI 	Inserts a node after the specified node.

AddBefore 	Inserts a list of nodes before the specified node.

AddBeforeI 	Inserts a node before the specified node.

AddHead 	Inserts a list of nodes at the front of the list.

AddHeadI 	Inserts a node at the front of the list.

AddTail 	Appends a list of nodes to the end of the list.

AddTailI 	Appends a node to the end of the list.

CBaseList 	Constructs a CBaseList object.

FindI 	Returns the first position that holds the specified object.

GetCount 	Returns the number of objects in the list.

GetHeadPosition 	Returns a cursor identifying the first element of the list.

GetI 	Returns the object at the specified position.

GetNextI 	Returns the specified object and updates the position.

GetTailPosition 	Returns a cursor identifying the last element of the list.

MoveToHead 	Moves the node or list of nodes to the beginning of a second list.

MoveToTail 	Moves the node or list of nodes to the end of a second list.

Next 	Returns the next position in the list.

Prev 	Returns the previous position in the list.

RemoveAll 	Removes all nodes from the list.

RemoveHeadI 	Removes the first node in the list.

RemoveI 	Removes the specified node from the list.

RemoveTailI 	Removes the last node in the list.

Reverse 	Reverses the order of the pointers to the objects in the list.


CBaseList::AddAfter

BOOL AddAfter(POSITION pos, CBaseList *pList);

Inserts a list of nodes after the specified node.

•	Returns TRUE if successful; otherwise, returns FALSE.

pos

Position after which to add the list of nodes.

pList

Pointer to the list of objects to add.


CBaseList::AddAfterI

POSITION AddAfterI(POSITION pos, void * pObj);

Inserts a node after the specified node.

•	Returns the position of the inserted object.

pos

Position after which to add the node.

pObj

Pointer to the object to add.

The following member function adds x to the start, which is equivalent to calling the CBaseList::AddHeadI member function:

AddAfterI(NULL,x)

If the list insertion fails, some of the elements may have been added. Existing positions in the list, including the position specified in the pos parameter, remain valid. The following two member functions are equivalent even in cases where pos is NULL or the Next(p) parameter is NULL. (This is similar for the mirror case.)

AddAfterI (p,x)

AddBeforeI(Next(p),x)


CBaseList::AddBefore

BOOL AddBefore(POSITION pos, CBaseList *pList);

Inserts a list of nodes before the specified node.

•	Returns TRUE if successful; otherwise, returns FALSE.

pos

Position before which to add the list of nodes.

pList

Pointer to the list of objects to add.

If the list insertion fails, some of the elements may have been added. Existing positions in the list, including the position specified in the pos parameter, remain valid.


CBaseList::AddBeforeI

POSITION AddBeforeI(POSITION pos, void * pObj);

Inserts a node before the specified node.

•	Returns the position of the inserted object.

pos

Position before which to add the node or list of nodes.

pObj

Pointer to the object to add.

The following member function adds the value specified in the x parameter to the end, which is equivalent to calling the CBaseList::AddTailI member function:

AddBeforeI(NULL,x)

The following two member functions are equivalent even in cases where pos is NULL or the Next(p) parameter is NULL. (This is similar for the mirror case.)

AddAfterI(p,x)

AddBeforeI(Next(p),x)


CBaseList::AddHead

BOOL AddHead(CBaseList *pList);

Inserts a list of nodes at the front of the list.

pList

Pointer to the list of objects to add.

If you are adding Component Object Model (COM) objects, you might want to add references to them (using the IUnknown::AddRef method) first. Other existing positions in the list remain valid.

This member function duplicates all the nodes in the pList parameter (that is, duplicates all its pointers to objects). It does not duplicate the objects.


CBaseList::AddHeadI

POSITION AddHeadI(void * pObj);

Inserts a node at the front of the list.

•	Returns the new head position, or NULL if it fails. For list insertions, returns TRUE if successful; otherwise, returns FALSE.

pObj

Pointer to the object to add.

If you are adding Component Object Model (COM) objects, you might want to add references to them (using the IUnknown::AddRef method) first. Other existing positions in the list remain valid.


CBaseList::AddTail

BOOL AddTail(CBaseList *pList);

Appends a list of nodes to the end of the list.

pList

Pointer to the list of objects to add.

This member function duplicates all the nodes in pList (that is, duplicates all its pointers to objects). It does not duplicate the objects. Existing positions in the list remain valid.


CBaseList::AddTailI

POSITION AddTailI(void * pObj);

Appends a single node to the end of the list.

•	Returns the new tail position, if successful; otherwise, returns NULL.

pObj

Pointer to the object to add.


CBaseList::CBaseList

CBaseList(TCHAR *pName, INT iItems = DEFAULTCACHE);

Constructs a CBaseList object.

pName

Name of the list.

iItems

Number of items in the list.


CBaseList::FindI

POSITION FindI(void * pObj);

Returns the first position that holds the specified object.

•	Returns a position cursor.

pObj

Pointer to the object to find.

A position cursor identifies an element on the list. Use the CBaseList::GetI member function to return the object at this position.


CBaseList::GetCount

int GetCount();

Returns the number of objects (object count) in the list.


CBaseList::GetHeadPosition

POSITION GetHeadPosition();

Returns a cursor identifying the first element of the list.

•	Returns a position cursor.

A position cursor represents an element on the list. It is defined as a pointer to a void.


CBaseList::GetI

void *GetI(POSITION pos);

Returns the object at the specified position.

•	Returns a pointer to the object as position pos.

pos

Position in the list from which to retrieve the object.

Use the CBaseList::Next, CBaseList::Prev, or CBaseList::FindI member function to obtain the position. Asking for the object at NULL position returns NULL harmlessly.


CBaseList::GetNextI

void *GetNextI(POSITION& rp);

Returns the specified object and updates the position.

•	Returns a pointer to an object at the next position.

rp

Returned pointer to the next object.

This member function updates the rp parameter to the next node in the list, but makes it NULL if it was at the end of the list.

This member function is retained only for backward compatibility. (GetPrev is not implemented.)

Use the CBaseList::Next and CBaseList::Prev member functions to access the next or previous object in the list.


CBaseList::GetTailPosition

POSITION GetTailPosition();

Returns a cursor identifying the last element of the list.

•	Returns a position cursor.

A position cursor represents an element on the list. A position is defined as a pointer to a void.


CBaseList::MoveToHead

BOOL MoveToHead(POSITION pos, CBaseList *pList);

Moves the node or list of nodes to the beginning of a second list.

•	Returns TRUE if successful; otherwise, returns FALSE.

pos

Position that marks the split in the list.

pList

List in which to add the section of the list preceding the position passed in the pos parameter.

This member function splits the current list after the position specified in the pos parameter in the list and retains the head portion of the original list. It then adds the tail portion to the head of the second list, identified by the pList parameter.


CBaseList::MoveToTail

BOOL MoveToTail(POSITION pos, CBaseList *pList);

Moves the node or list of nodes to the end of a second list.

•	Returns TRUE if successful; otherwise, returns FALSE.

pos

Position that marks the split in the list.

pList

List in which to add the section of the list specified in the pos parameter.

This member function splits the current list after the position specified in the pos parameter in the list and retains the tail portion of the original list. It then adds the head portion to the tail end of the second list, using the pList parameter.


CBaseList::Next

POSITION Next(POSITION pos);

Returns the next position in the list.

•	Returns a position cursor.

pos

Current position in the list.

This member function returns NULL when going past the beginning of the list. Calling the CBaseList::Next member function with a null value is similar to calling the CBaseList::GetHeadPosition member function.

Use the CBaseList::GetI member function to return the object at the returned position.


CBaseList::Prev

POSITION Prev(POSITION pos);

Returns the previous position in the list.

•	Returns a position cursor.

pos

Current position in the list.

This member function returns NULL when going past the end of the list. Calling the CBaseList::Prev member function with a null value is similar to calling the CBaseList::GetTailPosition member function.

Use the CBaseList::GetI member function to return the object at the returned position.


CBaseList::RemoveAll

void RemoveAll();

Removes all nodes from the list.


CBaseList::RemoveHeadI

void *RemoveHeadI();

Removes the first node in the list.

•	Returns the pointer to the object that was removed.

This member function deletes the pointer to its object from the list, but does not free the object itself.

If the list was already empty, this member function harmlessly returns NULL.


CBaseList::RemoveI

void *RemoveI(POSITION pos);

Removes the specified node from the list.

•	Returns the pointer to the object that was removed.

pos

Position in the list of the node to remove.

This member function deletes the pointer to its object from the list, but does not free the object itself.

If the list was already empty, this member function harmlessly returns NULL.


CBaseList::RemoveTailI

void *RemoveTailI();

Removes the last node in the list.

•	Returns the pointer to the object that was removed.

This member function deletes the pointer to its object from the list, but does not free the object.

If the list was already empty, this member function harmlessly returns NULL.


CBaseList::Reverse

void Reverse();

Reverses the order of the pointers to the objects in the list.


CBaseMediaFilter Class

This is an abstract base class that provides support for the IMediaFilter interface. The CBaseMediaFilter class handles State_Stopped, State_Paused, and State_Running state transitions. Typically, this class is used for plug-in distributors rather than filters with pins. Derive your filter classes from the CBaseFilter class (or base classes derived from this) instead of from this class.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Protected Data Members

m_pClock 	Pointer to a reference clock used for synchronization. The reference count of the clock object must be incremented using AddRef. Pass NULL if no reference clock is available.

m_State 	Current state of the filter, which can be State_Stopped, State_Paused, or State_Running.

m_tStart 	Offset from the stream time to the reference time.

m_clsid 	Class identifier (CLSID) used for serialization using IPersist.

Member Functions

CBaseMediaFilter 	Constructs a CBaseMediaFilter object.

IsActive 	Determines if the filter is currently active (running or paused) or stopped.

Overridable Member Functions

StreamTime 	Returns the current stream time.

Implemented IPersist Methods

GetClassID 	Returns the class identifier of this filter.

Implemented IMediaFilter Methods

GetState 	Retrieves the current state of the filter.

GetSyncSource 	Retrieves the current reference clock in use by this filter.

Pause 	Tells the filter to transition to the new (paused) state.

Run 	Passes a time value to synchronize independent streams.

SetSyncSource 	Tells the filter to which reference clock it should synchronize activity.

Stop 	Tells the filter to transition to the new (stopped) state

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Distributes references to any interfaces added to the derived filter class.


CBaseMediaFilter::CBaseMediaFilter

CBaseMediaFilter(TCHAR *pName, LPUNKNOWN pUnk,

    CCritSec *pLock, CLSID clsid, HRESULT * phr);

Constructs a CBaseMediaFilter object.

pName

Name of the CBaseMediaFilter class.

pUnk

IUnknown interface of the delegating object.

pLock

Pointer to the object that maintains the lock.

clsid

Class identifier used to serialize this filter.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.


CBaseMediaFilter::GetClassID

HRESULT GetClassID(CLSID *pClsID);

Fills the pClsID parameter with the class identifier of this filter (from m_clsid).

•	Returns an HRESULT value.

pClsID

Pointer to the class identifier to be filled out.


CBaseMediaFilter::GetState

HRESULT GetState(DWORD dwMilliSecsTimeout,

    FILTER_STATE * State);

Retrieves the current state of the filter.

•	Returns S_OK.

dwMilliSecsTimeout

Duration of the time-out, in milliseconds. To block indefinitely, pass INFINITE.

State

Returned state of the filter.

This member function implements the IMediaFilter::GetState method. It returns the value of the m_State data member.

Note that filters should derive their filters from CBaseFilter and not from CBaseMediaFilter, so this member function will not likely be used by filters. Use CBaseFilter::GetState instead.


CBaseMediaFilter::GetSyncSource

HRESULT GetSyncSource(IReferenceClock ** pClock);

Retrieves the current reference clock in use by this filter.

•	Returns an HRESULT value

pClock

Pointer to a reference clock; will be set to the IReferenceClock interface.

This member function implements the IMediaFilter::GetSyncSource method. It returns the value of m_pClock after adding a reference to it. Be sure to release the interface by calling the IUnknown::Release method when finished with the pointer.

Note that filters should derive their filters from CBaseFilter and not from CBaseMediaFilter, so this member function will not likely be used by filters. Use CBaseFilter::GetSyncSource instead.


CBaseMediaFilter::IsActive

BOOL IsActive(void);

Determines if the filter is currently active (running or paused) or stopped.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Filter is paused or running.

FALSE 	Filter is stopped.


CBaseMediaFilter::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IMediaFilter, IPersist, and IUnknown interfaces. Override this class to return other interfaces on the object in the derived class.


CBaseMediaFilter::Pause

HRESULT Pause (void);

Transitions the filter to State_Paused state if it is not in this state already.

•	Returns an HRESULT return value (S_OK by default).

This member function implements the IMediaFilter::Pause method. It sets the value of m_State to State_Paused.

Note that filters should derive their filters from CBaseFilter and not from CBaseMediaFilter, so this member function will not likely be used by filters. Use CBaseFilter::Pause instead.


CBaseMediaFilter::Run

HRESULT Run (void);

Transitions the filter to State_Running state if it is not in this state already.

•	Returns an HRESULT value.

If the filter is in State_Stopped state, the CBaseMediaFilter::Pause member function is called first to transition the filter to State_Paused state, which has the effect of activating any of the filter's connected pins. If any pin returns a failure return code from its CBasePin::Active member function, the function fails and the state is not changed. If this member function succeeds, the filter's m_State member variable is set to State_Running. This member function holds the filter's lock.

Note that filters should derive their filters from CBaseFilter and not from CBaseMediaFilter, so this member function will not likely be used by filters. Use CBaseFilter::Run instead.


CBaseMediaFilter::SetSyncSource

HRESULT SetSyncSource(IReferenceClock * pClock);

Identifies the reference clock to which the filter should synchronize activity.

•	Returns an HRESULT value.

pClock

Pointer to the IReferenceClock interface.

This member function implements the IMediaFilter::SetSyncSource method. It sets the m_pClock data member to the pClock parameter and increments the reference count on the IReferenceClock interface passed in.

This member function is most important to rendering filters and may not apply to other filters.

Note that filters should derive their filters from CBaseFilter and not from CBaseMediaFilter, so this member function will not likely be used by filters. Use CBaseFilter::SetSyncSource instead.


CBaseMediaFilter::Stop

HRESULT Stop(void);

Transitions the filter to State_Stopped state if it is not in this state already.

•	Returns an HRESULT value.

This member function implements the IMediaFilter::Stop method. It sets the m_State member variable to State_Stopped.

Note that filters should derive their filters from CBaseFilter and not from CBaseMediaFilter, so this member function will not likely be used by filters. Use CBaseFilter::Stop instead.


CBaseMediaFilter::StreamTime

virtual HRESULT StreamTime(CRefTime& rtStream);

Returns the current stream time.

•	Returns an HRESULT value, which can include the following values.

Value 	Meaning

S_OK 	Stream time returned in the rtStream parameter.

VFW_E_NO_CLOCK 	No reference clock is available.

E_FAIL 	Unable to get time from clock.

rtStream

Current stream time.

Current stream time is the reference clock time minus the stream time offset. All samples with time stamps less than or equal to this time should have been presented.


CBaseObject Class

The CBaseObject class is an abstract base class that is the basis for all component objects. It maintains a process-wide count of active objects that can be queried from the DllCanUnloadNow entry point.

All Component Object Model (COM) objects are derived from the CUnknown class, which is derived from the CBaseObject class. Other objects can be derived from CBaseObject to assist in the detection of memory leaks, because CBaseObject maintains the count of created objects.

The constructor requires a character-string name that describes the object being created. This string can be displayed on the debugging screen to trace the creation of objects; the string will also be displayed upon deletion of the object. The string should be created in static storage rather than in local-function storage. The string may be enclosed by the NAME macro, which compiles to NULL in retail builds so that the static strings are optimized out during compilation.

/* Typical object creation method */

HRESULT CSomeClass::CreateMyObject(void)

{

   HRESULT hr = NOERROR;

   CMyObject *pObject = new CMyObject(NAME("My filter object"),NULL,&hr);

      if (FAILED(hr)) {

         return hr;

   }

   if (pObject == NULL) {

      return E_OUTOFMEMORY;

   }

   m_pObject = pObject;

   return NOERROR;

}

/* Incorrect object creation method */

HRESULT CSomeClass::ThisMayAccessViolate(void)

{

   HRESULT hr = NOERROR;

   TCHAR MyObjectName[] = TEXT("My GP faulting object");

   CMyObject *pObject = new CMyObject(MyObjectName,NULL,&hr);

}

Member Functions

CBaseObject 	Constructs a CBaseObject object.

ObjectsActive 	Retrieves the count of active objects.


CBaseObject::CBaseObject

CBaseObject(TCHAR *pName);

Constructs a CBaseObject object.

pName

Name assigned to the object for debugging purposes.

The pName parameter should be allocated in static memory. This name appears on the debugging screen upon the creation and deletion of the object.


CBaseObject::ObjectsActive

static LONG ObjectsActive();

Retrieves the count of active objects.

•	Returns the current number of active objects.


CBaseOutputPin Class

CBaseOutputPin is an abstract base class derived from the CBasePin class that provides support for the common memory transport. CBaseOutputPin connects only to an input pin that supplies an IMemInputPin interface (such as a pin class derived from the CBaseInputPin class), and provides methods for the filter to access that interface. Derive your output pins from this class for the easiest implementation.

An output pin must provide one or more media types when connected to an input pin. If the media type that returns an index size, for example, is not currently available, the output pin should return S_FALSE in the CBasePin::GetMediaType member function, and the base class will skip it.

Your output pin class methods (represented here with the class name CYourPin) should call CBaseOutputPin. For example, CYourPin::Active should call CBaseOutputPin::Active first, to see if it should proceed. CYourPin::Inactive should call CBaseOutputPin::Inactive first, to decommit the sample allocator and avoid deadlock problems with CBaseOutputPin::GetDeliveryBuffer.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

All IQualityControl method implementations are inherited from the CBasePin class and are not overridden by this class.

Protected Data Members

m_pAllocator 	Pointer to the IMemAllocator interface for this pin.

m_pInputPin 	Pointer to the input pin to which this pin is connected.

Member Functions

CBaseOutputPin 	Constructs a CBaseOutputPin object.

Overridable Member Functions

Active 	Switches the pin to the active (running) mode.

BreakConnect 	Releases the allocator and the IMemInputPin interface.

CheckConnect 	Calls QueryInterface to retrieve an IMemInputPin interface.

CompleteConnect 	Completes the connection.

DecideAllocator 	Negotiates the allocator.

DecideBufferSize 	Retrieves the number and size of buffers required for the transfer.

Deliver 	Delivers an IMediaSample buffer to the connecting pin.

DeliverBeginFlush 	Calls the IPin::EndFlush method on the connected pin.

DeliverEndFlush 	Calls IPin::EndFlush on the connected input pin to pass an end-flushing notification.

DeliverEndOfStream 	Calls IPin::EndOfStream on the connected input pin to pass an end-of-stream notification.

DeliverNewSegment 	Calls IPin::NewSegment on the connected input pin to pass a segment.

GetDeliveryBuffer 	Returns an IMediaSample buffer suitable for passing across the connection.

Inactive 	Switches the pin to the inactive (stopped) mode.

InitAllocator 	Provides an allocator. This member function is typically called by the connecting input pin.

Implemented IPin Methods

BeginFlush 	Informs the pin to begin a flush operation. Implemented to return E_UNEXPECTED because it is an error to call this on an output pin.

EndFlush 	Informs the pin to end a flush operation. Implemented to return E_UNEXPECTED because it is an error to call this on an output pin.

EndOfStream 	Informs the pin that no additional data is expected until a new run command is issued. Implemented to return E_UNEXPECTED because it is an error to call this on an output pin.


CBaseOutputPin::Active

HRESULT Active(void);

Called by the CBaseFilter implementation when the state changes from stopped to either paused or running.

•	Returns VFW_E_NO_ALLOCATOR if there is not an allocator.

This member function calls CMemAllocator::Commit to commit memory required before becoming active.


CBaseOutputPin::BeginFlush

HRESULT BeginFlush(void);

Informs the pin to begin a flush operation.

•	Returns E_UNEXPECTED.

This member function implements the IPin::BeginFlush method. It returns E_UNEXPECTED because this should be called only on input pins.


CBaseOutputPin::BreakConnect

HRESULT BreakConnect(void);

Releases IMemAllocator and IMemInputPin objects acquired by the pin.

•	Returns NOERROR by the default base class implementation.

This member function releases the IMemAllocator and IPin interfaces used during the connection.


CBaseOutputPin::CBaseOutputPin

CBaseOutputPin(TCHAR *pObjectName, CBaseFilter *pFilter,

    CCritSec *pLock, HRESULT * phr, LPCWSTR pName);

Constructs a CBaseOutputPin object.

pObjectName

Name of the object used in the CBaseOutputPin constructor for debugging purposes.

pFilter

Filter to which the pin will be attached.

pLock

Pointer to a CBaseOutputPin object for locking.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.

pName

Pin name.


CBaseOutputPin::CheckConnect

HRESULT CheckConnect(IPin *pPin);

Calls QueryInterface on the connected pin to retrieve an IMemInputPin interface.

•	Returns NOERROR if successful; otherwise, returns an HRESULT error value.

pPin

Pointer to the IPin interface on the connecting pin.


CBaseOutputPin::CompleteConnect

virtual HRESULT CompleteConnect(IPin *pReceivePin);

Completes a connection to another filter.

•	Returns an HRESULT value. The default implementation returns NOERROR.

pReceivePin

Pointer to the connected (receiving) pin.

This member function overrides the CBasePin::CompleteConnect member function and calls the CBaseOutputPin::DecideAllocator member function to finish completing the connection.


CBaseOutputPin::DecideAllocator

virtual HRESULT DecideAllocator(IMemInputPin * pPin,

    IMemAllocator ** pAlloc);

Negotiates the allocator to use.

•	Returns NOERROR if successful; otherwise, returns an HRESULT value.

pPin

Pointer to the IPin interface of the connecting pin.

pAlloc

Pointer to the negotiated IMemAllocator interface.

This member function calls the CBaseOutputPin::DecideBufferSize member function, which is not implemented by this base class. Override DecideBufferSize to call IMemAllocator::SetProperties.

If the connected input pin fails a call to IMemInputPin::GetAllocator, this member function constructs a CMemAllocator object and calls CBaseOutputPin::DecideBufferSize on that object. If the call to DecideBufferSize is successful, this member function notifies the input pin of the selected allocator. This function is called by the base class implementation of the IPin::Connect method, which is responsible for locking the object's critical section.

Override this member function if you want to use your own allocator. The input pin gets the first choice for the allocator, and the output pin agrees or forces it to use another allocator.


CBaseOutputPin::DecideBufferSize

virtual HRESULT DecideBufferSize(IMemAllocator * pAlloc,

    ALLOCATOR_PROPERTIES * ppropInputRequest) PURE;

Retrieves the number and size of buffers required for the transfer.

•	Returns an HRESULT value.

pAlloc

Allocator assigned to the transfer.

ppropInputRequest

Requested allocator properties for count, size, and alignment, as specified by the ALLOCATOR_PROPERTIES structure.

The CBaseOutputPin::DecideAllocator member function calls this member function. You must override this member function in your derived class and call IMemAllocator::SetProperties.


CBaseOutputPin::Deliver

virtual HRESULT Deliver(IMediaSample *pSample);

Delivers the IMediaSample buffer to the connected pin.

•	Returns VFW_E_NOT_CONNECTED if no input pin is found; otherwise, returns an HRESULT value.

pSample

Buffer to deliver.

This member function delivers this buffer to the connected input pin by calling its IMemInputPin::Receive method.


CBaseOutputPin::DeliverBeginFlush

virtual HRESULT DeliverBeginFlush(void);

Calls the IPin::EndFlush method on the connected input pin.

•	Returns VFW_E_NOT_CONNECTED if no input pin is found; otherwise, returns the value that is returned by the IPin::BeginFlush method.

This member function delivers the BeginFlush notification downstream.


CBaseOutputPin::DeliverEndFlush

virtual HRESULT DeliverEndFlush(void);

Calls the IPin::EndFlush method on the connected input pin.

•	Returns VFW_E_NOT_CONNECTED if no input pin is found; otherwise, returns the value that is returned by IPin::EndFlush.

This member function delivers the EndFlush notification downstream.


CBaseOutputPin::DeliverEndOfStream

virtual HRESULT DeliverEndOfStream(void);

Calls the IPin::EndOfStream method on the connected input pin.

•	Returns VFW_E_NOT_CONNECTED if no input pin is found; otherwise, returns the value returned by the IPin::EndOfStream call to the connected pin.

This member function delivers the end-of-stream notification downstream by calling the IPin::EndOfStream method on the connected pin.


CBaseOutputPin::DeliverNewSegment

virtual HRESULT DeliverNewSegment(REFERENCE_TIME tStart,

    REFERENCE_TIME tStop, double dRate);

Calls the IPin::NewSegment method on the connected input pin.

•	Returns an HRESULT value.

tStart

Start time of the segment.

tStop

Stop time of the segment.

dRate

Rate of the segment.

You will need to override this member function in your derived output pin class if your filter queues any data in the output pin.


CBaseOutputPin::EndFlush

HRESULT EndFlush(void);

Informs the pin to end a flush operation.

•	Returns E_UNEXPECTED.

This member function implements the IPin::EndFlush method. It returns E_UNEXPECTED because this should be called only on input pins.


CBaseOutputPin::EndOfStream

HRESULT EndOfStream(void);

Informs the input pin that no additional data is expected until a new run command is issued.

•	Returns E_UNEXPECTED.

This member function implements the IPin::EndOfStream method but is not expected to be called on an output pin.


CBaseOutputPin::GetDeliveryBuffer

virtual HRESULT GetDeliveryBuffer(

    IMediaSample ** ppSample, REFERENCE_TIME * pStartTime,

    REFERENCE_TIME * pEndTime, DWORD dwFlags);

Returns an IMediaSample buffer suitable for passing across the connection.

•	Returns E_NOINTERFACE if an allocator is not found; otherwise, returns the value returned from calling the IMemAllocator::GetBuffer method.

ppSample

IMediaSample buffer to be provided.

pStartTime

Start time of the media sample (optional and can be NULL).

pEndTime

Stop time of the media sample (optional and can be NULL).

dwFlags

The following flags are supported:

AM_GBF_PREVFRAMESKIPPED 	Buffer returned will not be filled with data contiguous with any previous data sent.

AM_GBF_NOTASYNCPOINT 	Dynamic format changes are not allowed on this buffer because it is not a key frame.

The pin object must lock itself before calling this member function; otherwise, the filter graph could disconnect this pin from the input pin midway through the process. If the filter has no worker threads, the lock is best applied on the IMemInputPin::Receive call; otherwise, it should be done when the worker thread is ready to deliver the sample.

This call can block; therefore, to avoid deadlocking with an IMediaFilter::Stop command, a two-tier locking scheme (such as that implemented in CTransformFilter) is required. Only the second-level lock is acquired here. The IFilter base class implementation of IMediaFilter::Stop first gets the first-level lock and then calls IMemAllocator::Decommit on the allocator. This has the effect of making GetDeliveryBuffer return with a failure code. The Stop member function then gets the second-level lock and completes the command by calling Inactive for this pin.

No lock is needed when calling CBaseOutputPin::GetDeliveryBuffer when passing on samples using a worker thread. In this case the Stop base class implementation acquires its filter-level lock and just calls IMemAllocator::Decommit on the allocator, at which point the worker thread is freed up to listen for a command to stop.

You need to release the sample yourself after this function. If the connected input pin needs to hold on to the sample beyond the function, it will add the reference for the sample itself through IUnknown::AddRef. You must release this one and call CBaseOutputPin::GetDeliveryBuffer for the next. (You cannot reuse it directly.)


CBaseOutputPin::Inactive

HRESULT Inactive(void);

Called by the CBaseFilter implementation when the state changes from either paused or running to stopped.

•	Returns VFW_E_NO_ALLOCATOR if there is not an allocator; otherwise, returns the value from calling the IMemAllocator::Decommit method.

This member function calls IMemAllocator::Decommit to decommit memory before becoming inactive.


CBaseOutputPin::InitAllocator

virtual HRESULT InitAllocator(IMemAllocator **ppAlloc);

Creates a default memory allocator. Override this to provide your own allocator or to provide no allocator.

•	Returns an HRESULT value.

ppAlloc

Returned memory allocator.


CBasePin Class

CBasePin is an abstract base class from which all pins are derived. CBasePin supports the IPin interface. You can derive from this if your pin does not supply or use the IMemInputPin interface; otherwise, derive from the CBaseInputPin class or the CBaseOutputPin class.

The connection process is crucial to the success of creating filter graphs. The filter graph finds two filters (and subsequently two pins) to connect. It calls the IPin::Connect method on the output pin (it may also call Connect on the input pin at the same time). The output pin then calls the virtual pin member function CBasePin::CheckConnect. Derived classes should override this member function to use QueryInterface to return any interfaces required. The base class implementation of CheckConnect queries the IMemInputPin interface to establish the default transport protocol.

After calling CheckConnect, the output pin calls CBasePin::AgreeMediaType; this is a worker member function not intended for overriding in derived classes. This gets the input pin's enumerator and calls CBasePin::TryMediaTypes with it. TryMediaTypes is another base pin worker member function that is not intended for derivation. It cycles through each media type provided by an enumerator to determine if a connection can be made with that type.

If that process fails, AgreeMediaType retrieves the output pin's media type enumerator and calls CBasePin::GetMediaType, which cycles through the media types to agree upon a connection type. If there is agreement, a media type with the input and output pins becomes the type used in the connection.

If no media type can be agreed upon, the connection between the pins cannot be made. The base pin calls CBasePin::SetMediaType to broadcast the format. The m_mt base pin variable is set during this process.

The IPin interface provides a method called QueryAccept. This method allows a connected filter to query whether the pin will accept a specified media type. The method is asynchronous so that a filter can call it at any time—even when another filter is calling it. For this reason, its implementation in any override of the base class should not lock the filter. The base class implementation of IPin::QueryAccept calls the overridden CBasePin::CheckMediaType member function on the derived pin class.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Protected Data Members

m_pName 	Name of the pin.

m_Connected 	Pin to which this pin is connected.

m_mt 	Media type that this pin is using. This is established during the connection process.

m_dir 	Direction of this pin.

m_pLock 	Object used for locking.

m_bRunTimeError 	Last run-time error generated.

m_pFilter 	Filter that created the pin.

m_TypeVersion 	Current media type version (see CBasePin::GetMediaTypeVersion).

m_pQSink 	Target for quality messages.

m_tStart 	Start time from the CBasePin::NewSegment call.

m_tStop 	Stop time from the CBasePin::NewSegment call.

m_dRate 	Rate from the CBasePin::NewSegment call.

Member Functions

AttemptConnection 	Attempts to make a connection to another pin using a specified media type.

CBasePin 	Constructs a CBasePin object.

CurrentRate 	Returns the segment rate set by the CBasePin::NewSegment member function.

CurrentStartTime 	Returns the segment start time set by the CBasePin::NewSegment member function.

CurrentStopTime 	Returns the segment stop time set by the CBasePin::NewSegment member function.

DisplayPinInfo 	Displays pin information on the debugging monitor.

DisplayTypeInfo 	Displays media type information on the debugging monitor.

GetConnected 	Returns the pin that is connected to this pin.

IncrementTypeVersion 	Adds 1 to the current media type version.

IsConnected 	Determines whether the pin is connected.

IsStopped 	Determines whether the filter owning this pin is in the State_Stopped state.

Name 	Returns the m_pName name of the pin.

Overridable Member Functions

Active 	Switches the pin to the active (running) mode.

AgreeMediaType 	Agrees on the media type to be used by the pin.

BreakConnect 	Adds custom code when the connection quits. This is also called when a stage in the connection process fails, so this member function should also clean up partial connection states.

CheckConnect 	Adds custom code when the connection is being made. This is called at the start of the connection process.

CheckMediaType 	Checks if the pin can support a specific media type.

CompleteConnect 	Completes the connection.

GetMediaType 	Returns the media type used by the pin.

GetMediaTypeVersion 	Returns the version of the pins that were created dynamically.

Inactive 	Switches the pin to the inactive (stopped) mode.

SetMediaType 	Sets the m_mt data member to the established media type.

TryMediaTypes 	Tries to find an acceptable media type for a connection from the list returned by a media type enumerator.

Implemented IPin Methods

Connect 	Initiates a connection to another pin.

ConnectedTo 	Returns a pointer to the connecting pin.

ConnectionMediaType 	Returns the media type of this pin's connection.

Disconnect 	Breaks a connection.

EndOfStream 	Informs the input pin that no additional data is expected until a new run command is issued. (returns S_FALSE by default).

EnumMediaTypes 	Returns an enumerator for this pin's preferred media types.

NewSegment 	Specifies that samples following this call are grouped as a segment with a given start time, stop time, and rate.

QueryAccept 	Determines whether this pin accepts the media type.

QueryDirection 	Retrieves the pin direction of the pin.

QueryId 	Retrieves an identifier for the pin.

QueryInternalConnections 	Returns an array of the pins to which this pin connects internally.

QueryPinInfo 	Retrieves information about the pin itself (the name, owning filter, or direction).

ReceiveConnection 	Called by a connecting pin to make a connection to this pin. Usually this does not need to be overridden, because the default implementation calls CBasePin::BreakConnect.

Run 	Notifies the pin that the filter has changed state from stopped to paused.

Implemented IQualityControl Methods

Notify 	Notifies the recipient that a quality change is requested.

SetSink 	Sets the IQualityControl object that will receive quality messages.

Implemented INonDelegatingUnknown Methods

NonDelegatingAddRef 	Increments the owning filter's reference count.

NonDelegatingQueryInterface 	Retrieves CBasePin interfaces. Override this member function to pass out pointers to any interfaces added by the derived pin class.

NonDelegatingRelease 	Decrements the owning filter's reference count.


CBasePin::Active

virtual HRESULT Active(void);

Called by the CBaseFilter implementation when the state changes from stopped to either paused or running.

•	Returns an HRESULT value.

Any class that requires notification of a change of state should override this member function. This is called when the filter owning the pin exits the State_Stopped state.


CBasePin::AgreeMediaType

virtual HRESULT AgreeMediaType(IPin *pReceivePin,

    const CMediaType *pmt);

Searches for a media type for the pin connection. This member function is called during the connection process.

•	Returns an HRESULT value, which can include one of the following.

Value 	Meaning

NOERROR 	A media type was found.

VFW_E_NO_ACCEPTABLE_TYPES 	No agreement upon a media type was reached.

pReceivePin

Pointer to the receiving pin.

pmt

Pointer to a media type object to be returned.

This member function calls CBasePin::TryMediaTypes on both the owning pin and the pin connected to the owning pin; it enumerates the preferred data types on the pin. If one is found, TryMediaTypes tries the media type with the pin in a call to the CBasePin::ReceiveConnection member function. If this pin proposes a media type, its support is still verified by calling CBasePin::CheckMediaType. The enumerator can list all of the media types, even if some of them are not currently available.

This member function is protected.


CBasePin::AttemptConnection

virtual HRESULT AttemptConnection(IPin * pReceivePin,

    const CMediaType *pmt);

Attempts to make a connection to another pin using a specified media type.

•	Returns an HRESULT value.

pReceivePin

Pointer to the receiving pin.

pmt

Pointer to a media type object containing the preferred media type for the connection.

This member function is used to attempt to make a connection with a given media type. Its main purpose is to call the IPin::ReceiveConnection method of the pin passed in the pReceivePin parameter. This member function is protected.


CBasePin::BreakConnect

virtual HRESULT BreakConnect();

Called when a connection is broken to allow for customization (intended for overriding).

•	Returns an HRESULT value. The default implementation returns NOERROR.

This member function is called when a connection to the pin cannot be made or when CBasePin::Disconnect is called. In this case, it is necessary to undo anything performed during the connection process. You can override this member function to release any references to interfaces that were made during the connection.


CBasePin::CBasePin

CBasePin(TCHAR *pObjectName, CBaseFilter *pFilter,

    CCritSec *pLock, HRESULT *phr, LPCWSTR pName,

    PIN_DIRECTION dir);

Constructs a CBasePin object.

pObjectName

Description of the object.

pFilter

Owning filter that knows about pins.

pLock

Object that implements the lock.

phr

Pointer to a general OLE return value. Note that this value is changed only if this function fails.

pName

Pin name.

dir

Either PINDIR_INPUT or PINDIR_OUTPUT.

This is a standard class constructor.


CBasePin::CheckConnect

virtual HRESULT CheckConnect(IPin * pPin);

Allows for customization when the connection is first made (intended for overriding, if required).

•	Returns one of the following arguments by default; if overridden, should return standard HRESULT values, including the following values.

Value 	Meaning

NOERROR 	Connection verified successfully.

E_INVALIDARG 	Pin directions do not match between pins.

pPin

Pointer to the connecting pin.

This member function is called during a call to the IPin::Connect method to provide a virtual method that can do any specific check required for a connection, such as calling CBasePin::NonDelegatingQueryInterface. This base class method determines if the pin directions match.


CBasePin::CheckMediaType

virtual HRESULT CheckMediaType(const CMediaType * pmt)

    PURE;

Determines if the pin can support this specific media type.

•	The overriding member function should return S_OK if the proposed media type is accepted; otherwise, it should return an HRESULT failure value, such as S_FALSE.

pmt

Pointer to a media type object containing the proposed media type.

This member function is typically called before calling the CBasePin::SetMediaType member function. It is also called from several other member functions, including CBasePin::ReceiveConnection and CBasePin::QueryAccept.


CBasePin::CompleteConnect

virtual HRESULT CompleteConnect(IPin *pReceivePin);

Completes a connection to another filter (intended for overriding).

•	Returns an HRESULT value. The default implementation returns NOERROR.

pReceivePin

Pointer to the connected (receiving) pin.

Override this member function to check for required connection interfaces on the pReceivePin parameter or its filter. Failing this member function fails the connection and disconnects the other pin. The CBaseOutputPin class overrides this member function to establish a local memory transport.


CBasePin::Connect

HRESULT Connect(IPin * pReceivePin,

    const AM_MEDIA_TYPE *pmt);

Initiates a connection from this pin to the other pin.

•	Returns one of the following arguments by default; if overridden, should return standard HRESULT values.

Value 	Meaning

VFW_E_ALREADY_CONNECTED 	This output pin is already connected to another pin.

VFW_E_NOT_STOPPED 	The filter graph is not in a stopped state and connection cannot be performed.

Other error value 	Returned from CBasePin::AgreeMediaType or CBasePin::CheckConnect or overridden versions of these member functions.

pReceivePin

Input pin to connect to.

pmt

Optional media type parameter.

This member function implements the IPin::Connect method. IPin::Connect is implemented on the output pin and calls the IPin::ReceiveConnection method for the connected input pin (implemented in the base classes as CBasePin::ReceiveConnection). This member function calls the virtual CBasePin::CheckConnect member function, which can be overridden to verify that the connection is possible. CBasePin::CheckConnect then calls CBasePin::AgreeMediaType to negotiate on a common media type with the connected pin.

CBasePin::AgreeMediaType calls CBasePin::TryMediaTypes twice, once for this pin's media type enumerator and once for the receiving pin's media type enumerator. For each media type found, CBasePin::AttemptConnection is called, which in turn calls the receiving pin's IPin::ReceiveConnection method, and finally CBasePin::CompleteConnect if successful.


CBasePin::ConnectedTo

HRESULT ConnectedTo(IPin ** ppPin);

Retrieves a pointer to the connected pin, if there is one.

•	The base class returns S_OK if connected; otherwise, returns VFW_E_NOT_CONNECTED.

ppPin

IPin interface of the other pin (if any) to which this pin is connected.

This member function implements the IPin::ConnectedTo method. It adds a reference to the connected IPin interface by calling the IUnknown::AddRef method because each copy of an interface pointer has its reference incremented. The calling application is responsible for calling IUnknown::Release on this interface when done with it.


CBasePin::ConnectionMediaType

HRESULT ConnectionMediaType(AM_MEDIA_TYPE*pmt);

Retrieves the media type associated with the current connection of the pin. This method fails if the pin is unconnected.

•	Returns an HRESULT value.

pmt

Pointer to an AM_MEDIA_TYPE structure. If the pin is not connected, this structure is initialized to zero. Otherwise, the media type is returned in this parameter.

This member function implements the IPin::ConnectionMediaType method. It returns a copy of the AM_MEDIA_TYPE structure that was negotiated for the pin connection when the pin was connected.

The task allocator allocates the format block of the media type. Use the task allocator to free the format block, for example by calling the Microsoft Win32 CoTaskMemFree function.


CBasePin::CurrentRate

double CurrentRate();

Returns the segment rate set by the CBasePin::NewSegment member function.

•	Returns the value of m_dRate.


CBasePin::CurrentStartTime

REFERENCE_TIME CurrentStartTime();

Returns the segment start time set by the CBasePin::NewSegment member function.

•	Returns the value of m_tStart.


CBasePin::CurrentStopTime

REFERENCE_TIME CurrentStopTime();

Returns the segment stop time set by the CBasePin::NewSegment member function.

•	Returns the value of m_tStart.


CBasePin::Disconnect

HRESULT Disconnect(void);

Breaks a connection.

•	Returns NOERROR if there is no connection.

This member function implements the IPin::Disconnect method. It calls the CBasePin::BreakConnect member function and releases the IPin interface of the connected pin (held by m_Connected). There are no parameters because there is only one possible connection on this pin.


CBasePin::DisplayPinInfo

void DisplayPinInfo(IPin *pReceivePin);

Displays pin information during debugging.

•	Returns an HRESULT value.

pReceivePin

Pointer to the receiving pin.


CBasePin::DisplayTypeInfo

void DisplayTypeInfo(IPin *pPin, const CMediaType *pmt);

Displays media type information during debugging.

pPin

Pointer to the IPin interface of the pin.

pmt

Pointer to the media type object.

This member function displays the major and minor media types of the specified media type object.


CBasePin::EndOfStream

HRESULT EndOfStream(void);

Informs the input pin that no additional data is expected until a new run command is issued.

•	Returns S_FALSE.

This member function implements the IPin::EndOfStream method. This is intended for input pins only.


CBasePin::EnumMediaTypes

HRESULT EnumMediaTypes(IEnumMediaTypes ** ppEnum);

Provides an enumerator for this pin's preferred media types.

•	Returns an HRESULT value.

ppEnum

A pointer to an enumerator for the media types.

This member function implements the IPin::EnumMediaTypes method. It returns an enumerator object implemented by the CEnumMediaTypes class and obtains the IEnumMediaTypes interface, which adds a reference count to this enumerator. If an application receives an enumerator, the application must release this when done with it by calling IUnknown::Release on the enumerator.


CBasePin::GetConnected

IPin * GetConnected();

Returns the pin that is connected to this pin.

•	Returns a pointer to an IPin interface.

The caller should call the CBasePin::IsConnected member function before calling CBasePin::GetConnected.


CBasePin::GetMediaType

virtual HRESULT GetMediaType(int iPosition,

    const CMediaType *pMediaType);

Returns the current type version, which is used by enumerators.

•	Returns E_UNEXPECTED by default implementation; the overriding member function should return one of the following values, or an HRESULT error value if the value could not be set.

Value 	Meaning

S_OK 	Media type was set.

VFW_S_NO_MORE_ITEMS 	End of the list of media types has been reached.

S_FALSE 	Media type exists but is not currently usable.

iPosition

Position in the media type list.

pMediaType

Returned pointer to the media type at this position.

This is a virtual member function that returns a media type corresponding with the position in the list specified by the iPosition parameter. This base class simply returns an error because no media types are supported by default. Derived classes should override this member function.


CBasePin::GetMediaTypeVersion

virtual LONG GetMediaTypeVersion();

Returns the current type version, which is used by enumerators.

•	Returns the value of m_TypeVersion by default. To return new media types, override this member function.

This is a virtual member function that returns the current media type version. The base class initializes the media type enumerators to 1. A derived class can change the list of media types available. Each time it does, it should increment the version in the overriding member function. The media type enumerators call this member function when they are called to determine if they are out of date.


CBasePin::Inactive

virtual HRESULT Inactive(void);

Switches the pin to an inactive state.

•	Returns NOERROR for a base class implementation. The overriding member function returns a standard HRESULT value and should not fail if the pin is already set as inactive.

This member function is called by the IMediaFilter implementation when the state changes to inactive. This member function should be overridden to decommit allocators and free any hardware resources that were obtained in the CBasePin::Active call. The default implementation of the base class member function does nothing.


CBasePin::IncrementTypeVersion

void IncrementTypeVersion(void);

Adds 1 to the current media type version.

The media type version is used to make sure that the filter has not changed the media type. If it changes the media type, the filter should call this member function.


CBasePin::IsConnected

BOOL IsConnected(void)

Determines if the pin is connected to another pin.

•	Returns TRUE if the pin is connected; otherwise, returns FALSE.

This member function checks the value of the m_Connected protected data member.


CBasePin::IsStopped

BOOL IsStopped();

Determines if the filter is stopped.

•	Returns TRUE if the filter is stopped; otherwise, returns FALSE.

Note that this member function must not be used in the constructor of the pin, because the filter that is passed is often not initialized properly at that time (due to the convention of using a this pointer during the construction of data members).


CBasePin::Name

LPWSTR Name();

Returns the name of the pin.

•	Returns the value of the m_pName data member.


CBasePin::NewSegment

HRESULT NewSegment(REFERENCE_TIME tStart,

    REFERENCE_TIME tStop, double dRate);

Specifies that samples following this call are grouped as a segment with a given start time, stop time, and rate.

•	Returns an HRESULT value (S_OK by default).

tStart

Start time of the segment.

tStop

Stop time of the segment.

dRate

Rate of the segment.

This member function implements the IPin::NewSegment method. The default implementation sets the m_tStart, m_tStop, and m_dRate data members to the values passed in as parameters. Overriding member functions should pass this notification downstream.


CBasePin::NonDelegatingAddRef

ULONG NonDelegatingAddRef();

Increments the reference count for an interface.

•	Returns the reference count of the object.

This member function implements the INonDelegatingUnknown::NonDelegatingAddRef method. It increments the reference count of the owning filter.


CBasePin::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IPin, IQualityControl, and IUnknown interfaces. Override this class to return other interfaces on the object in the derived class.


CBasePin::NonDelegatingRelease

ULONG NonDelegatingRelease();

Decrements the reference count for an interface.

•	Returns the reference count.

This member function implements the INonDelegatingUnknown::NonDelegatingRelease method. It releases a reference to the owning filter.


CBasePin::Notify

HRESULT Notify(IFilter * pSelf, Quality q);

Notifies the recipient that a quality change is requested.

•	The default base class implementation returns E_FAIL.

pSelf

Pointer to the filter that is sending the quality notification.

q

Quality notification structure.

This member function must be overridden to accept notifications. It is typically overridden to implement this method on the output pin because quality-control messages are passed upstream. The CTransformOutputPin::Notify member function is one example of how this member function is overridden to pass quality-control messages to the next filter upstream.


CBasePin::QueryAccept

HRESULT QueryAccept(const AM_MEDIA_TYPE* pmt);

Determines whether the pin accepts the format type.

•	Returns S_TRUE if the format is accepted; otherwise, returns S_FALSE.

pmt

Pointer to a proposed media type.

This member function implements the IPin::QueryAccept method. It simply calls the pure virtual CBasePin::CheckMediaType member function, which the derived class must implement, and maps any returned codes from CheckMediaType other than S_OK to S_FALSE.


CBasePin::QueryDirection

HRESULT QueryDirection(PIN_DIRECTION* pPinDir);

Retrieves the direction of the pin.

•	Returns an HRESULT value.

pPinDir

A pointer to a PIN_DIRECTION structure to be filled in with the direction.

This member function implements the IPin::QueryDirection method. pPinDir will contain PINDIR_INPUT or PINDIR_OUTPUT. The same information is available through the CBasePin::QueryPinInfo member function, but this member function is more efficient.


CBasePin::QueryId

HRESULT QueryId(LPWSTR * Id);

Retrieves an identifier for the pin.

•	Returns an HRESULT value.

Id

The pin identifier.

This member function implements the IPin::QueryId method. By default, this member function uses the pin name in the CBasePin::m_pName data member, so implementing this member function in your derived filter class is not normally required.


CBasePin::QueryInternalConnections

HRESULT QueryInternalConnections(IPin ** apPin,

    ULONG * nPin);

Provides an array of pointers to IPin objects. These are the pins to which this pin internally connects.

•	Returns one of the following HRESULT values.

Value 	Meaning

E_FAIL 	Undetermined failure.

S_FALSE 	Insufficient number of channels; returns no pins in apPin.

E_NOTIMPL 	The filter graph manager interprets E_NOTIMPL as meaning all input pins connect to all output pins.

apPin

Array of IPin pointers.

nPin

Upon input, indicates the number of channels; upon output, indicates the number of pins.

This member function implements the IPin::QueryInternalConnections method but only to return E_NOTIMPL. Override this if you want to provide mapping between specific input and output pins.

The default implementation to return E_NOTIMPL implies that the caller can assume that all input pins feed all output pins. Overriding this member function allows a filter to specify when it is a renderer for some of its input pins and not for others.


CBasePin::QueryPinInfo

HRESULT QueryPinInfo(PIN_INFO * pInfo);

Retrieves information about the pin.

•	Returns an HRESULT value.

pInfo

A pointer to a PIN_INFO structure.

This member function implements the IPin::QueryPinInfo method. By default, the member function fills in the PIN_INFO structure with the IFilter interface of its owning filter, the pin name from m_pName, and the pin direction from m_dir.

Note that the IFilter interface passed out by this member function is reference counted and so must be released when the caller has finished with it.


CBasePin::ReceiveConnection

HRESULT ReceiveConnection(IPin * pConnector,

    AM_MEDIA_TYPE*pmt);

Makes a connection to the calling output pin.

•	Returns an HRESULT value.

pConnector

Connecting pin.

pmt

Media type of the samples to be streamed.

This member function implements the IPin::ReceiveConnection method. It calls CheckConnect and, if successful, then calls CheckMediaType to verify if the media type is acceptable. If either of these calls fails, it calls BreakConnect and exits. To finish the connection process, it calls CompleteConnect, which is implemented in CBasePin to return NOERROR but may be overridden in the derived class.


CBasePin::Run

HRESULT Run(REFERENCE_TIME tStart);

Notifies the pin that the filter has changed state from stopped to paused.

•	Returns an HRESULT value (NOERROR_OK by default).

tStart

Start time. Unreferenced by this class; for possible use by the derived class.

This member function can be overridden in the derived class to perform activities such as committing memory or obtaining resources. For an overriding implementation of this member function, see the CRenderedInputPin::Run member function.


CBasePin::SetMediaType

virtual HRESULT SetMediaType(const CMediaType * pmt);

Sets the m_mt data member to the established media type.

•	Returns NOERROR by default implementation. The overriding member functions return an HRESULT value.

pmt

Pointer to a media type object that was previously agreed upon.

This member function is called to establish the format for a pin connection. The CBasePin::CheckMediaType member function will have been called to check the connection format and, if it did not return an error value, this virtual member function will be called. The default implementation sets the m_mt protected data member to the value passed to this member function. Override to inform the derived class when the media type is set.


CBasePin::SetSink

HRESULT SetSink(IQualityControl *piqc);

Sets the object containing the IQualityControl interface that will receive quality-control messages.

•	Base class returns NOERROR by default. The overriding member function should return an HRESULT value.

piqc

Pointer to the IQualityControl interface to which the notifications should be sent.

This member function implements the IQualityControl::SetSink method. The default implementation sets the m_pQSink data member to the piqc parameter passed in.

The IQualityControl::SetSink method tells a filter where to send quality-control messages it receives. When no sink has been explicitly set or if the last call to CBasePin::SetSink set the sink to NULL, the message should go upstream. The derived pin output pin class typically overrides CBasePin::Notify to enable this.


CBasePin::TryMediaTypes

virtual HRESULT TryMediaTypes(IPin *pReceivePin,

    const CMediaType *pmt, IEnumMediaTypes *pEnum);

Determines a media type for a pin connection.

•	Returns an HRESULT value, which can include the following.

Value 	Meaning

NOERROR 	Media type found.

FAILED 	Resetting of the enumerator failed.

VFW_E_NO_ACCEPTABLE_TYPES 	No acceptable media types were found.

pReceivePin

Pointer to the IPin interface of the receiving pin.

pmt

Pointer to a returned media type.

pEnum

Pointer to an IEnumMediaTypes enumerator interface.

Given an enumerator, this member function cycles through all the media types proposed by the enumerator. Each type is suggested to the derived pin class and, if acceptable, is tried with the connected pin in a call to the IPin::ReceiveConnection method. This means that if the owning pin proposes a media type, it is still checked to determine whether it is supported. This is deliberate so that, in simple cases, the enumerator can hold all of the media types, even if some of them are not really currently available.

This member function is protected.


CBasePropertyPage Class

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 the Filter Graph Editor displays these property pages. Also, the Microsoft® ActiveMovie™ ActiveX™ control queries filters in its underlying filter graph for the property pages they support and exposes them to the user. A good example of property page implementation is the video renderer, which exposes the properties of the underlying DirectDraw™ capabilities, among other things.

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 E_NOTIMPL 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 window are received.

Protected Data Members

m_pPageSite 	PROPERTYPAGESITE structure containing details about the filter's property site.

m_hwnd 	Window handle for the property page.

m_Dlg 	Dialog box window handle for the property page.

m_bDirty 	Flag to determine whether anything has changed.

m_TitleId 	Resource identifier for the property page title.

m_DialogId 	Resource identifier for the dialog box.

Member Functions

CBasePropertyPage 	Constructs a CBasePropertyPage object.

Overridable Member Functions

OnActivate 	Called when the property page is activated.

OnApplyChanges 	Called when changes to the property page by the user are applied.

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 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 	Returns 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

Activate(HWND hwndParent, LPCRECT prect, BOOL fModal);

Creates a dialog box window for the property page.

•	Returns an HRESULT value. Returns E_OUTOFMEMORY if it fails to create a dialog box and E_UNEXPECTED if a property page dialog box is already created.

hwndParent

Window handle to use as the parent of the dialog box that is being created.

prect

Pointer to the RECT structure containing the positioning information for the dialog box. This member function creates its dialog box with the placement and dimensions described by this rectangle, that is, origin point at (prect->left, prect->top) and dimensions of (prect->right-prect->left, prect->bottom-prect->top).

fModal

Indicator as to whether the dialog box frame is modal (TRUE) or modeless (FALSE). This parameter is ignored by this implementation, and a modeless dialog is created.

This member function implements the OLE IPropertyPage::Active method, which creates a modeless dialog box for the property page (without a frame, caption, or system menu/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.

For more information about the IPropertyPage::Active method, see the Microsoft Win32® SDK documentation.


CBasePropertyPage::Apply

HRESULT Apply(void);

Applies current property page values to the underlying object.

•	Returns an HRESULT value.

This member function implements the OLE IPropertyPage::Apply method. The object to be changed is provided through a previous call to CBasePropertyPage::SetObjects. This should be the IUnknown interface of the filter. Therefore, this member function should not fail because of non-existent 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.

For more information about the IPropertyPage::Apply method, see the Microsoft Win32 SDK documentation.


CBasePropertyPage::CBasePropertyPage

CBasePropertyPage(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT *phr, int DialogId, int TitleId);

Constructs a CBasePropertyPage object.

•	Returns an HRESULT value.

pName

Name of the property page object for debugging purposes.

pUnk

Pointer to the COM delegating object.

phr

Returned HRESULT value.

DialogId

Resource ID for the dialog.

TitleId

Resource ID for the dialog title.

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

HRESULT Deactivate(void);

Destroys the window created with CBasePropertyPage::Activate.

•	Returns an HRESULT value.

This member function implements the OLE IPropertyPage::Deactivate method. It calls the virtual CBasePropertyPage::OnDeactivate member function and then destroys the property page dialog box.

For more information about the IPropertyPage::Deactivate method, see the Microsoft Win32 SDK documentation.


CBasePropertyPage::GetPageInfo

GetPageInfo(LPPROPPAGEINFO pPageInfo);

Returns information about the property page.

•	Returns an HRESULT value.

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 responsibility of the caller.

This member function implements the OLE IPropertyPage::GetPageInfo method. It calls the Microsoft Win32 GetDialogSize function to obtain the dialog size and sets it to a default value in case this call fails.

For more information about the IPropertyPage::GetPageInfo method, see the Win32 SDK documentation.


CBasePropertyPage::Help

Help(LPCWSTR lpszHelpDir);

Invokes help in response to user request.

•	Returns E_NOTIMPL by default; the overriding member function should return a valid HRESULT value.

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. (Note that LocalServer32 is not checked in the current implementation, because local property pages are not currently supported).

This member function implements the OLE IPropertyPage::Help method, but only as a placeholder.

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.

For more information about the IPropertyPage::Help method, see the Microsoft Win32 SDK documentation.


CBasePropertyPage::IsPageDirty

HRESULT IsPageDirty(void);

Indicates whether the property page has changed since activated or since the most recent call to CBasePropertyPage::Apply.

•	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.

This member function implements the OLE IPropertyPage::IsPageDirty method. It returns the value of the m_bDirty data member.

For more information about the IPropertyPage::IsPageDirty method, see the Microsoft Win32 SDK documentation.


CBasePropertyPage::Move

Move(LPCRECT prect);

Positions and resizes the property page dialog box within the frame.

•	Returns an HRESULT value.

prect

Pointer to the RECT structure containing the positioning information for the page dialog box.

This member function implements the OLE 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.

For more information about the IPropertyPage::Move method, see the Win32 SDK documentation.


CBasePropertyPage::NonDelegatingAddRef

ULONG NonDelegatingAddRef();

Increments the reference count for an interface.

•	Returns the reference count of the object.

This member function implements the INonDelegatingUnknown::NonDelegatingAddRef method. It increments the reference count of the owning filter.


CBasePropertyPage::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

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

ULONG NonDelegatingRelease();

Decrements the reference count for an interface.

•	Returns the reference count.

This member function implements the INonDelegatingUnknown::NonDelegatingRelease method. It releases a reference to the owning filter.


CBasePropertyPage::OnActivate

virtual HRESULT OnActivate(void);

Called when the property page is activated.

•	Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

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 is done by calling the Microsoft Win32 SetDlgItemMessage function with data member values previously initialized when the property page was connected (in the overridden CBasePropertyPage::OnConnect member function).

For example, the vidprop.cpp file in the Sample Video Renderer sample (SAMPVID) does this as follows:

// 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

virtual HRESULT OnApplyChanges(void);

Called when changes to the property page are applied by the user.

•	Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

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

virtual HRESULT OnConnect(IUnknown *pUnknown);

Called when the property page is connected to the filter.

•	Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

pUnknown

IUnknown interface of the filter associated with the property page.

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).

For example, the following excerpt from the Sample Video Renderer (SAMPVID) vidprop.cpp file 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

virtual HRESULT OnDeactivate(void);

Called when the property page is dismissed.

•	Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

This member function is called from the CBasePropertyPage::Deactivate member function when the property page is closed by the user. Override this member function to handle any special requirements at this time.


CBasePropertyPage::OnDisconnect

virtual HRESULT OnDisconnect(void);

Called when the property page is disconnected from the owning filter.

•	Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

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 this time, such as releasing reference counts on underlying property interfaces.

The following example, from the vidprop.cpp file in the Sample Video Renderer sample, demonstrates an implementation of this member function in a derived class.

// Release any IQualProp interface we have

HRESULT CQualityProperties::OnDisconnect()

{

    // Release the interface

    if (m_pQualProp == NULL) {

        return E_UNEXPECTED;

    }

    m_pQualProp->Release();

    m_pQualProp = NULL;

    return NOERROR;

}


CBasePropertyPage::OnReceiveMessage

virtual BOOL OnReceiveMessage(HWND hwnd, UINT uMsg,

    WPARAM wParam, LPARAM lParam);

Called when a message is sent to the property page dialog.

•	By default, returns the value returned by the Microsoft Win32 DefWindowProc function.

hwnd

Window procedure that received the message.

uMsg

Message.

wParam

Additional message information. The content of this parameter depends on the value of the uMsg parameter.

lParam

Additional message information. The content of this parameter depends on the value of the uMsg parameter.

The default implementation of this member function calls the Win32 DefWindowProc function with the supplied parameters. Override this member function for special handling of messages.


CBasePropertyPage::SetObjects

SetObjects(ULONG cObjects, LPUNKNOWN *ppUnk);

Provides the property page with an IUnknown pointer for objects associated with this property page.

•	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.

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

Pointer to a single IUnknown interface pointer 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.

This member function implements the OLE 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.

Note that the caller must provide the property page with this object before calling CBasePropertyPage::Activate, and should call CBasePropertyPage::SetObjects with zero 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

HRESULT SetPageSite(LPPROPERTYPAGESITE pPageSite);

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.

•	Returns an HRESULT value.

pPageSite

Pointer to the IPropertyPageSite interface of the page site that manages and provides services to this property page within the entire property sheet.

This member function implements the OLE IPropertyPage::SetPageSite method. When passed an IPropertyPageSite interface, it reference counts the interface and assigns it to m_pPageSite. When passed a null value, is releases the reference count on the IPropertyPageSite interface.

For more information about the IPropertyPage::SetPageSite method, see the Microsoft Win32 SDK documentation.


CBasePropertyPage::Show

HRESULT Show(UINT nCmdShow);

Makes the property page dialog box visible or invisible. If the page is made visible, the page should set the focus to itself, specifically to the first property on the page.

nCmdShow

Command describing whether to become visible. Only SW_SHOWNORMAL is accepted.

This member function implements the OLE IPropertyPage::Show method. This is called just before exiting the CBasePropertyPage::Activate member function with the nCmdShow SHOW_NORMAL value.

For more information about the IPropertyPage::Show method, see the Microsoft Win32 SDK documentation.


CBasePropertyPage::TranslateAccelerator

HRESULT TranslateAccelerator(LPMSG lpMsg);

Provides a pointer to an MSG structure that specifies a keystroke to process.

•	Returns an HRESULT value. Returns E_NOTIMPL by default.

lpMsg

Pointer to the MSG structure describing the keystroke to process.

This member function implements the OLE 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.

For more information about the IPropertyPage::TranslateAccelerator method, see the Microsoft Win32 SDK documentation.


CBaseReferenceClock Class

This base class implements the IReferenceClock interface.

The CBaseReferenceClock class provides a full implementation of IReferenceClock. It uses CCritSec locking support and CAMSchedule scheduler support.

Each advise call defines a point in time when the caller wants to be notified. A periodic advise is a regular series of such events. A list of these advise requests is maintained by the reference clock. The clock calculates the delay until the first requested advise, and signals an event at the due time.

Clients are not advised through callbacks. One-shot clients have an event set, while periodic clients have a semaphore released for each event notification. A semaphore allows a client to know exactly how many events were actually triggered, because multiple time periods may elapse before the client code executes.

During class construction, a worker thread is created. This thread executes a series of Microsoft® Win32® WaitForSingleObject calls, waking up when a command is given to the thread or the next wake-up point is reached. The wake-up points are determined by clients making advise calls.

Member Functions

AddAdvisePacket 	Creates a new pending notification.

CBaseReferenceClock 	Constructs a CBaseReferenceClock object.

SetTimeDelta 	Adjusts the values returned from CBaseReferenceClock::GetPrivateTime by the amount specified in this member function.

TriggerThread 	Triggers the advise thread's event. If you override CBaseReferenceClock::GetPrivateTime, you should either reimplement or abandon this method.

Implemented IReferenceClock Methods

AdvisePeriodic 	Requests an asynchronous periodic notification that a time has elapsed.

AdviseTime 	Requests an asynchronous notification that a time has elapsed.

GetTime 	Returns a reference time.

Unadvise 	Removes a previously established advise link.

Overridable Member Functions

GetPrivateTime 	Gets the current time from the real clock. Override this member function to implement your own clock.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Returns a pointer to interfaces supported, that is, IReferenceClock.


CBaseReferenceClock::AddAdvisePacket

DWORD AddAdvisePacket(const REFERENCE_TIME & time1,

    const REFERENCE_TIME & time2, HANDLE hNotify,

    BOOL bPeriodic);

Creates a new pending notification and adds it to the advise notification list.

•	Returns the advise token if successful, or 0 if an error occurred.

time1

Time that the advise should take place.

time2

Period between notifications. (Ignored if bPeriodic is FALSE.)

hNotify

Notification mechanism. Either a semaphore (if bPeriodic is TRUE) or an event handle.

bPeriodic

Whether this is a one-shot timer.

This member function overrides CAMSchedule::AddAdvisePacket. It calls CAMSchedule::AddAdvisePacket in order to add the packet. Then, if the next wake-up time needs to be reevaluated, it will trigger the advise thread.

This member function is used internally by both CBaseReferenceClock::AdviseTime and CBaseReferenceClock::AdvisePeriodic. It is unlikely to be needed by either applications or derived classes, which should use CBaseReferenceClock::AdviseTime or CBaseReferenceClock::AdvisePeriodic as appropriate.


CBaseReferenceClock::AdvisePeriodic

HRESULT AdvisePeriodic(REFERENCE_TIME StartTime,

    REFERENCE_TIME PeriodTime, HSEMAPHORE hSemaphore,

    DWORD *pdwAdviseToken);

Sets up a recurring advise with the reference clock.

•	Returns an HRESULT value.

StartTime

Start at this time.

PeriodTime

Time between notifications.

hSemaphore

Advise through a semaphore.

pdwAdviseToken

Advise token that identifies the link with the clock.

This member function implements the IReferenceClock::AdvisePeriodic method. A semaphore is used, rather than an event, to ensure that multiple notifications can be seen by the user. Each time an amount of time specified in the PeriodTime parameter elapses, the semaphore will be released.

When no further notifications are required, call CBaseReferenceClock::Unadvise and pass the pdwAdviseToken value returned from this call.

For example, the following code extract sets up an advise link that fires its first advise five seconds from now and then signals every second until Unadvise is called. By using a semaphore with a count of 10, the clock is effectively able to cache 10 events.

HANDLE hSemaphore = CreateSemaphore(NULL, 0, 10, NULL);

    // assume pRefClock is an IReferenceClock* variable

    REFERENCE_TIME rtPeriodTime = 1000 * (UNITS / MILLISECONDS);

        // a one-second interval

    REFERENCE_TIME rtNow;

    DWORD    dwAdviseToken;

    pRefClock->GetTime(&rtNow);

    pRefClock->AdvisePeriodic(rtNow+(5*rtPeriodTime),

        PeriodTime, hSemaphore, &dwAdviseToken);


CBaseReferenceClock::AdviseTime

HRESULT AdviseTime(REFERENCE_TIME baseTime,

    REFERENCE_TIME streamTime, HEVENT hEvent,

    DWORD *pdwAdviseToken);

Sets up a one-shot notification with the clock.

•	Returns an HRESULT value.

baseTime

Base reference time.

streamTime

Stream offset time.

hEvent

Advise through this event.

pdwAdviseToken

Where the advise token goes.

This member function implements the IReferenceClock::AdviseTime method. At the time specified in the baseTime plus the streamTime parameters, the event specified in hEvent will be set. It is correct to call CBaseReferenceClock::Unadvise to remove the link after the event has occurred, but it is not necessary. One-shot notifications are automatically cleared by the clock once they have signaled.

To cancel a one-shot notification before the time is reached, call Unadvise and pass the pdwAdviseToken value returned from this call.


CBaseReferenceClock::CBaseReferenceClock

CBaseReferenceClock(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT *phr);

Constructs a CBaseReferenceClock object.

pName

Name of the CBaseReferenceClock object.

pUnk

IUnknown interface of the delegating object.

phr

Pointer to an HRESULT value.


CBaseReferenceClock::GetPrivateTime

virtual REFERENCE_TIME GetPrivateTime();

Returns the current reference time.

•	Returns the current reference time, in 100-nanosecond units.

GetPrivateTime represents the actual clock. GetTime is the externally used member function. Derived classes will probably override this method, but not GetTime itself. The important point about GetPrivateTime is that it is allowed to go backward. This class's GetTime member function will keep returning the last time returned by GetTime until GetPrivateTime catches up.


CBaseReferenceClock::GetTime

HRESULT GetTime(REFERENCE_TIME *pTime);

Retrieves the current reference time, in 100-nanosecond units.

•	Returns an HRESULT value.

pTime

Where the current time is returned.

This member function implements the IReferenceClock::GetTime method. It reads the time from the implemented clock and returns the current time.


CBaseReferenceClock::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Accesses supported interfaces.

•	Returns an HRESULT value.

riid

IID of the interface being requested. Only IID_IReferenceClock is supported by the clock interface.

ppv

Where the IReferenceClock pointer is returned.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CBaseReferenceClock::SetTimeDelta

HRESULT SetTimeDelta(const REFERENCE_TIME& TimeDelta);

Sets a delta on the time that CBaseReferenceClock::GetPrivateTime will return.

•	Returns an HRESULT value.

TimeDelta

REFERENCE_TIME delta to be added.

Note that CBaseReferenceClock::GetTime will never return a time earlier than a previously returned time. Thus, if you set the clock to a time in the past, successive calls to CBaseReferenceClock::GetTime will return the current value until this new time is reached, and the clock will start to increment again.


CBaseReferenceClock::TriggerThread

void TriggerThread();

Triggers the advise thread's event.

The clock uses a worker thread that should wake up and call CAMSchedule::Advise at the appropriate time. If the clock adds an event that should be fired earlier than any currently outstanding event, the worker thread needs to be awoken in order to reevaluate its wait time. The TriggerThread member function will wake up the worker thread so this can take place. CBaseReferenceClock::AddAdvisePacket will call TriggerThread if it is required, so derived classes need not normally do so. However, if a derived clock causes time to jump forward for some reason, TriggerThread should be called so that the wait time can be reevaluated; otherwise, the events will fire late.


CBaseReferenceClock::Unadvise

HRESULT Unadvise(DWORD dwAdviseToken);

Removes a previously established advise link.

•	Returns an HRESULT value.

dwAdviseToken

Identifier (token) of the link that is being reset. This is the same value that was returned on CBaseReferenceClock::AdviseTime or CBaseReferenceClock::AdvisePeriodic.

This member function implements the IReferenceClock::Unadvise method. Call Unadvise to remove the previously established clock advise links. It is mandatory to call Unadvise on periodic advises in order to stop further calls. It is recommended to call Unadvise for single-shot advise links.


CBaseRenderer Class

CBaseRenderer is the base renderer class for writing video renderers. This class handles a single input pin, all state changes, and synchronization.

Protected Data Members

m_bRepaintStatus 	Flag to determine if an EC_REPAINT message can be signaled.

m_pPosition 	CRendererPosPassThru object for passing positioning data upstream.

m_RenderEvent 	Used to signal timer events.

m_ThreadSignal 	Event signaled to release a worker thread.

m_evComplete 	Event signaled when the state is complete.

m_bAbort 	Stop rendering data.

m_bStreaming 	Indicator for whether the filter graph is currently streaming.

m_dwAdvise 	Timer advise token.

m_pMediaSample 	Current image media sample.

m_bEOS 	Indicator for whether there are more samples in the stream.

m_bEOSDelivered 	Indicator for whether an EC_COMPLETE event has been delivered.

m_pInputPin 	Renderer input pin object.

m_InterfaceLock 	Critical section for interfaces.

m_RendererLock 	Controller for access to internals.

m_pQSink 	Quality control sink.

Member Functions

Active 	Called when the state is switched to paused or running. Override to add functionality.

CBaseRenderer 	Constructs a CBaseRenderer object.

CheckReady 	Determines if the event is set.

GetRealState 	Retrieves the actual state of the renderer.

GetRenderEvent 	Retrieves the event to render.

IsEndOfStream 	Determines if the end of the stream has been reached.

IsEndOfStreamDelivered 	Determines if the end of the stream has been delivered.

IsStreaming 	Determines if the filter is currently streaming data.

NotReady 	Forces the m_evComplete event into a nonsignaled state.

Ready 	Puts the m_evComplete event into a signaled state.

ScheduleSample 	Sets up an advise link with the clock.

SendRepaint 	Signals an EC_REPAINT message to the filter graph.

SetRepaintStatus 	Resets the repaint status flag.

SetAbortSignal 	Sets the abort signal flag.

SignalTimerFired 	Resets the current advise time to zero after a timer fires.

Overridable Member Functions

BeginFlush 	Signals the start of flushing on the input pin.

BreakConnect 	Breaks the input pin connection and resets the end-of-stream flags.

CancelNotification 	Cancels any currently scheduled notification.

CheckMediaType 	Determines if the renderer will accept a given media type.

ClearPendingSample 	Called to release the pending sample when in a stopped or inactivated state.

CompleteConnect 	Called as part of the connection protocol. Override to add functionality.

CompleteStateChange 	Ensures that a sample is waiting before allowing a pause.

DisplayTimingInfo 	Displays timing information.

DoRenderSample 	Called when a sample is ready to render.

GetCurrentSample 	Retrieves the current sample waiting at the video renderer.

GetPin 	Returns a CBasePin object to the renderer.

GetPinCount 	Returns the number of input pins supported.

EndFlush 	Called when the input pin receives an end-flush notification.

EndOfStream 	Called when the input pin receives an end-of-stream notification.

GetMediaPositionInterface 	Retrieves IMediaPosition and IMediaSelection interfaces for the video renderer.

GetSampleTimes 	Retrieves sample time information for this sample.

HaveCurrentSample 	Determines if a sample is waiting at the renderer.

Inactive 	Called when going into a stopped state. Override to add functionality.

NonDelegatingQueryInterface 	Returns an interface and increments the reference count.

OnReceiveFirstSample 	Provides derived classes with an opportunity to render static data.

OnRenderEnd 	Notifies the derived class that rendering has finished.

OnRenderStart 	Notifies the derived class that rendering is about to start.

OnStartStreaming 	Notifies the derived class that streaming has started.

OnStopStreaming 	Notifies the derived class that streaming has stopped.

OnWaitEnd 	Notifies the derived class that a wait for a rendering time has just ended.

OnWaitStart 	Notifies the derived class that a wait for a rendering time is about to start.

Pause 	Tells the renderer to transition to the new (paused) state.

PrepareReceive 	Ensures that a sample can be rendered.

PrepareRender 	Provides an opportunity for the derived renderer class to realize its palette.

Receive 	Called by the source filter when a sample is available to render.

Render 	Asks the derived class to render the sample.

ResetEndOfStream 	Resets the end-of-stream flag.

Run 	Transitions the renderer to State_Running if it is not already in this state.

SendEndOfStream 	Sets the end-of-stream flag.

SetMediaType 	Informs the derived class of the selected media type.

ShouldDrawSampleNow 	Determines if the sample should be drawn between the start and stop times given.

SourceThreadCanWait 	Sets or resets the thread event.

StartStreaming 	Called to schedule any pending image with the clock and to display any timing information.

Stop 	Tells the renderer to transition to the new (stopped) state.

StopStreaming 	Sets an internal flag to indicate not to schedule arrival of any more samples.

WaitForRenderTime 	Waits for either the time to arrive or for rendering to be stopped.

Implemented IMediaFilter Methods

GetState 	Determines the state of the renderer.

Implemented IFilter Methods

FindPin 	Retrieves a pointer to the pin with the specified identifier. (There is only one pin.)


CBaseRenderer::Active

virtual HRESULT Active(void);

Called when the state is switched to paused or running.

•	Returns an HRESULT value. Returns NOERROR by default.

This member function does nothing by default. Derived classes can optionally override this member function to add functionality.


CBaseRenderer::BeginFlush

virtual HRESULT BeginFlush(void);

Informs the renderer that flushing has started.

•	Returns an HRESULT value.

This member function is called by CRendererInputPin::BeginFlush when informed of a flush from the upstream filter. It releases the source thread and signals the start of flushing on the input pin.


CBaseRenderer::BreakConnect

virtual HRESULT BreakConnect(void);

Called when a connection is broken.

•	Returns an HRESULT value.

This member function resets the end-of-stream flag and also checks for a valid connection or that the filter is in a stopped state. Override to customize.


CBaseRenderer::CancelNotification

virtual HRESULT CancelNotification(void);

Cancels any currently scheduled notification.

•	Returns an HRESULT value.

This member function is called by the owning window object when it is told to stop streaming. If there is no timer link outstanding, calling this member function does nothing; otherwise, this function stops the advise link and resets the renderer event.


CBaseRenderer::CBaseRenderer

CBaseRenderer(CLSID RenderClass, TCHAR *pName,

    LPUNKNOWN pUnk, HRESULT *phr);

Constructs a CBaseRenderer object.

RenderClass

Class identifier for this renderer.

pName

Name used for debugging purposes.

pUnk

Owner object.

phr

Pointer to the HRESULT return code.


CBaseRenderer::CheckMediaType

virtual HRESULT CheckMediaType(

    const CMediaType * pmt) PURE;

Determines if the renderer will accept a given media type.

•	Returns an HRESULT value.

pmt

Pointer to a media type object that contains the proposed media type.

This member function must be overridden and implemented, typically to return the media type of the display. It is called from the CRendererInputPin::CheckMediaType member function during the connection process.


CBaseRenderer::CheckReady

BOOL CheckReady(void);

Determines if the renderer is ready to process the next sample.

•	Returns TRUE if the m_evComplete event is currently set, but does not block.

This member function calls the CAMEvent::Check member function. This is mainly used in transitioning to paused states. When a renderer is paused, it should not complete the state change until it has received some data. So although the call to IMediaFilter::Pause completes immediately, if the application calls IMediaFilter::GetState it will return VFW_S_STATE_INTERMEDIATE. When an image arrives at the renderer, the event that is initially reset during the pause call will be signaled. At this point, an application calling IMediaFilter::GetState will return NOERROR. This process allows an application to pause a filter graph and then wait until data is actually queued and ready to be rendered.


CBaseRenderer::ClearPendingSample

virtual HRESULT ClearPendingSample(void);

Called to clear the pending sample when in a stopped or inactivated state.

•	Returns an HRESULT value.

This member function releases the IMediaSample interface. This allows the allocator to reuse it and allocate it to the upstream filter again. If the state is being changed to inactive, IMemAllocator::GetBuffer will return an error. This function also resets the current media sample to NULL to indicate that an image is not available.


CBaseRenderer::CompleteConnect

virtual HRESULT CompleteConnect(IPin *pReceivePin);

Called as part of the connection protocol.

•	Returns an HRESULT value (NOERROR by default).

pReceivePin

Connecting pin.

This member function calls the SetRepaintStatus member function to set the m_bRepaintStatus data member to TRUE so that EC_REPAINT notifications can be sent in the future. (To prevent unnecessary EC_REPAINT notifications from being sent, m_bRepaintStatus is set to FALSE when an end-of-stream notification arrives.)


CBaseRenderer::CompleteStateChange

virtual HRESULT CompleteStateChange(

    FILTER_STATE OldState);

Ensures that a sample is waiting before allowing a pause.

•	Returns S_OK if the filter can be paused; otherwise, returns S_FALSE.

OldState

State prior to the transition.

This member function is called from the CBaseRenderer::Pause member function. If the filter is being paused and there is no sample waiting, the transition is not completed and the function returns S_FALSE until the first sample arrives. However, if the m_bAbort flag has been set, all samples are rejected so there is no point waiting for one. If a sample is available, this member function returns NOERROR. Currently only State_Intermediate is returned from Pause.


CBaseRenderer::DisplayTimingInfo

virtual HRESULT DisplayTimingInfo(void);

Displays timing information.

•	Returns an HRESULT value.

This member function is called on transition from paused to running states. Transitions from stopped to running must always go through the paused state first. This does nothing on retail builds. On debug builds this function displays the designated start time, the current time from the clock, and the start time for the next available sample. It also determines if a reference clock with which to synchronize is available, and calculates how long it is until the first sample is due for rendering. This assumes the first sample necessarily has a stream time of zero.

The timing information received from the filter graph is critical to the base renderer. The run command is given a time that is used as a base time. The next sample stream time is added to this base time to get a whole reference time to wait for. If the run time is corrupt in some way, the wait may be infinite.


CBaseRenderer::DoRenderSample

virtual HRESULT DoRenderSample(

    IMediaSample *pMediaSample) PURE;

Called when a sample is ready to render.

•	Returns an HRESULT value.

pMediaSample

Media sample.

This member function must be overridden in the derived class. It is called by CBaseRenderer::Render.

The derived class should render the object at this time. For example, the sample video renderer (SAMPVID) calls its drawing object (a CDrawImage object).

// Have the drawing object render the current image

HRESULT CVideoRenderer::DoRenderSample(IMediaSample *pMediaSample)

{

    return m_DrawImage.DrawImage(pMediaSample);

}


CBaseRenderer::EndFlush

virtual HRESULT EndFlush(void);

Called when the input pin receives an end-flush notification.

•	Returns an HRESULT value.

This member function is called from the CRendererInputPin::EndFlush member function. It calls CBaseRenderer::SourceThreadCanWait with a TRUE value to allow the upstream filter's thread to wait in CBaseRenderer::Receive again.


CBaseRenderer::EndOfStream

HRESULT EndOfStream(void);

Called when the input pin receives an end-of-stream notification.

•	Returns an HRESULT value.

If all received samples have been rendered, this member function notifies EC_COMPLETE. If samples have been received and not yet rendered, this function sets m_bEOS and checks for it on completing samples. If the filter is waiting to be paused, this function completes the transition to paused state by setting the state event.


CBaseRenderer::FindPin

HRESULT FindPin(LPCWSTR Id, IPin **ppPin);

Retrieves a pointer to the pin with the specified identifier.

•	Returns NOERROR if successful; otherwise, returns VFW_E_NOT_FOUND.

Id

Identifier of the pin.

ppPin

Pointer to the IPin interface for this pin after the renderer has been restored.

This member function implements the IFilter::FindPin method. It assumes that the default pin name is "In" and checks for this. If the pin is found, its reference count is incremented. The ppPin parameter is set to NULL if the identifier cannot be matched.


CBaseRenderer::GetCurrentSample

virtual IMediaSample *GetCurrentSample(void);

Retrieves the current sample waiting at the video renderer, or NULL if there is not one.

•	Returns a pointer to the sample.

The reference count for the sample is incremented before returning. This is so that if the sample comes due for rendering, it is not added back to the allocator free list until the caller of this member function releases it.


CBaseRenderer::GetMediaPositionInterface

virtual HRESULT GetMediaPositionInterface(

    REFIID riid, void **ppv);

Retrieves IMediaPosition and IMediaSelection interfaces for the video renderer.

•	Returns an HRESULT value.

riid

Reference identifier.

ppv

Pointer to the interface.

A CRendererPosPassThru helper object is created dynamically when this is called to support passing the IMediaPosition or IMediaSelection interface calls from the filter graph manager to the upstream filter.


CBaseRenderer::GetPin

virtual CBasePin *GetPin(int n);

Returns a CBasePin object on the renderer.

•	Returns a pointer to the pin specified by the n parameter.

n

Number of the specified pin, which is always zero in the case of the renderer.

This member function overrides CBaseFilter::GetPin. Only one pin is supported on the renderer; it is numbered zero. A call to this member function with n equal to zero will result in an input pin of type CRendererInputPin being returned. It will be created if it does not yet exist.


CBaseRenderer::GetPinCount

virtual int GetPinCount(void);

Retrieves the number of input pins supported.

•	The default implementation returns 1, since only one pin is supported. Override to support more than one pin.

This member function overrides CBaseFilter::GetPinCount.


CBaseRenderer::GetRealState

FILTER_STATE GetRealState(void);

Retrieves the actual state of the renderer.

•	Returns m_State, the state flag for the renderer.

This member function provides an internal way of getting the real state. Calling through the IFilter interface to get the state could return State_Intermediate, while waiting for an image before completing a paused state transition. Therefore, this method provides a way to call through the main renderer if you have the critical section already locked, thus returning the correct state.


CBaseRenderer::GetRenderEvent

CAMEvent *GetRenderEvent(void);

Retrieves the event to render.

•	Returns the value of m_RenderEvent.


CBaseRenderer::GetSampleTimes

virtual HRESULT GetSampleTimes(

    IMediaSample *pMediaSample,

    REFERENCE_TIME *pStartTime,

    REFERENCE_TIME *pEndTime);

Retrieves sample time information for this sample.

•	Returns S_FALSE if the sample should be scheduled according to the times specified in the sample; returns S_OK to indicate that the sample should be rendered immediately.

pMediaSample

Media sample.

pStartTime

Start time.

pEndTime

End time.

Note that the sample times are passed in by reference, not value.


CBaseRenderer::GetState

HRESULT GetState(DWORD dwMilliSecsTimeout,

    FILTER_STATE * State);

Determines the state of the renderer.

•	Returns an HRESULT value. Returns VFW_S_STATE_INTERMEDIATE if paused and waiting for a sample; otherwise, returns NOERROR.

dwMilliSecsTimeout

Duration of the time-out, in milliseconds. To block indefinitely, pass INFINITE.

State

Returned state of the renderer.

This member function overrides the CBaseFilter::GetState member function. It returns the value of m_State. Because the renderer does not complete the full transition to the paused state until it has a sample to render, if the state is requested while it is waiting for a sample, it will return VFW_S_STATE_INTERMEDIATE along with the state.


CBaseRenderer::HaveCurrentSample

virtual BOOL HaveCurrentSample(void);

Determines if a sample is waiting at the renderer.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Current sample is ready and the renderer is in a stopped state.

FALSE 	Current sample is not ready and the renderer is not in a stopped state.


CBaseRenderer::Inactive

virtual HRESULT Inactive(void);

Called when going into a stopped state.

•	Returns NOERROR by default; overriding member function should return a valid HRESULT value.

This member function is a placeholder that derived classes can optionally override to add functionality when the filter is stopped.


CBaseRenderer::IsEndOfStream

BOOL IsEndOfStream(void);

Determines if the end of the stream has been reached.

•	Returns one of the following values.

Value 	Meaning

TRUE 	End of the stream has been reached.

FALSE 	End of the stream has not been reached.

The default implementation returns m_bEOS.


CBaseRenderer::IsEndOfStreamDelivered

BOOL IsEndOfStreamDelivered(void);

Determines if the end of the stream has been delivered.

•	Returns one of the following values.

Value 	Meaning

TRUE 	End of the stream has been delivered.

FALSE 	End of the stream has not been delivered.

The default implementation returns m_bEOSDelivered.


CBaseRenderer::IsStreaming

BOOL IsStreaming(void)

Determines if the filter is currently streaming data.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Renderer is currently streaming.

FALSE 	Renderer is not currently streaming.

The default implementation returns m_bStreaming.


CBaseRenderer::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(

    REFIID riid, void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function overrides CBaseFilter::NonDelegatingQueryInterface. It exposes the IMediaPosition and IMediaPosition interfaces and then calls CBaseFilter::NonDelegatingQueryInterface for interfaces implemented in the base classes.


CBaseRenderer::NotReady

void NotReady(void);

Forces the m_evComplete event into a nonsignaled state.

This member function calls the CAMEvent::Reset member function of the m_evComplete event object.


CBaseRenderer::OnReceiveFirstSample

virtual void OnReceiveFirstSample(

    IMediaSample *pMediaSample);

Provides derived classes with an opportunity to render static data.

pMediaSample

Media sample.

This member function is unimplemented. It is primarily used by video renderers. When they receive their first sample while paused, they typically draw the frame as a poster image. This virtual method is called by the base classes when the first sample arrives.


CBaseRenderer::OnRenderEnd

virtual void OnRenderEnd(

    IMediaSample *pMediaSample);

Notifies the derived class that rendering has finished.

pMediaSample

Media sample.

This member function is available for quality management and performance measuring. It is called immediately after the sample is rendered.

Quality management implementations typically need to know how long it takes the renderer to render the data.


CBaseRenderer::OnRenderStart

virtual void OnRenderStart(

    IMediaSample *pMediaSample);

Notifies the derived class that rendering is about to start.

pMediaSample

Media sample.

This member function is available for quality management and performance measuring. It is called immediately before the sample is rendered.

Quality management implementations typically need to know how long it takes the renderer to render the data.


CBaseRenderer::OnStartStreaming

virtual HRESULT OnStartStreaming(void);

Notifies the derived class that streaming has started.

•	Returns NOERROR in the default implementation.

This member function is called from CBaseRenderer::StartStreaming. Override this in your derived class to provide special handling when streaming starts.


CBaseRenderer::OnStopStreaming

virtual HRESULT OnStopStreaming(void);

Notifies the derived class that streaming has stopped.

•	Returns NOERROR in the default implementation.

This member function is called from CBaseRenderer::StopStreaming. Override this in your derived class to provide special handling when streaming stops.


CBaseRenderer::OnWaitEnd

virtual void OnWaitEnd(void);

Notifies the derived class that a wait for a rendering time has just ended.

This member function is available for quality control and is called from CBaseRenderer::WaitForRenderTime just after waiting for the presentation time for a sample. Override this member function to obtain performance measurements in a derived class.


CBaseRenderer::OnWaitStart

virtual void OnWaitStart(void);

Notifies the derived class that a wait for a rendering time is about to start.

This member function is available for quality control and is called from CBaseRenderer::WaitForRenderTime just before waiting for the presentation time for a sample. Override this member function to obtain performance measurements in a derived class.


CBaseRenderer::Pause

HRESULT Pause(void);

Transitions the renderer to State_Paused if it is not in this state already.

•	Returns an HRESULT value.

The following activities are performed when pausing the renderer:

1	Commit the allocator used for the connection.

2	Allow the thread for the upstream filter to wait in Receive.

3	Cancel any outstanding clock advise links.

4	Check to see if the renderer is connected and allow a state change.

5	If a sample is available, complete the state change to State_Paused.

This member function holds the renderer's lock. If the member function succeeds, the filter's m_State member variable is set to State_Paused. If the renderer is in the State_Stopped state, the Active member function is called for each of the renderer's connected pins.

This member function overrides CBaseFilter::Pause.


CBaseRenderer::PrepareReceive

virtual HRESULT PrepareReceive(

    IMediaSample *pMediaSample);

Ensures that a sample can be rendered.

•	Returns an HRESULT value.

pMediaSample

Media sample.

This member function is called when the upstream filter delivers a sample. If the upstream filter is running (streaming), the sample is scheduled with the reference clock. If the upstream filter is not streaming, a sample in paused mode has been received, so any state transition can be completed. On leaving this function, everything will be unlocked so an application thread can get in and change the state to stopped. In this case it will also signal the thread event so that the wait call is stopped.


CBaseRenderer::PrepareRender

virtual void PrepareRender(void);

Provides an opportunity for the derived renderer class to realize its palette.

This member function is called from CBaseRenderer::Receive before rendering each frame to ensure that the correct palette is realized in case another application has changed the palette. It has a null implemention in the base class and can be overridden in the derived class.


CBaseRenderer::Ready

void Ready(void);

Puts the m_evComplete event into a signaled state.

This member function calls the m_evComplete CTimeOutEvent object's Set member function.


CBaseRenderer::Receive

virtual HRESULT Receive(

    IMediaSample *pMediaSample);

Called by the upstream filter when a sample is available to render.

•	Returns an HRESULT value.

pMediaSample

Media sample.

When not using DirectDraw™, this member function sets an advise link with the clock, waits for the time to arrive, and then renders the data by calling the pure virtual DoRenderSample member function that the derived class will have overridden. After rendering the sample, the end of stream may also be signaled if it was the last one sent before EndOfStream was called.

In the DirectDraw case, this member function just cleans up because the sample will already have been drawn.


CBaseRenderer::Render

virtual HRESULT Render(

    IMediaSample *pMediaSample);

Asks the derived class to render the sample.

•	Returns an HRESULT value.

pMediaSample

Media sample.

This member function is called when the derived class should render the sample. The action taken is dependent on the nature of the renderer; a video renderer will typically draw the image in a window. This class calls the pure virtual DoRenderSample to be implemented by the derived class.


CBaseRenderer::ResetEndOfStream

virtual HRESULT ResetEndOfStream(void);

Resets the end-of-stream flag.

•	Returns an HRESULT value.

This member function is typically called when changing to stopped states. A renderer must keep track of when it gets told that no more data is going to arrive (this is done when the sourcing filter calls IPin::EndOfStream). At this point the renderer finishes rendering any data it has and then sends an EC_COMPLETE event to the filter graph manager.

However, when the filters are stopped, the whole state is cleared. When the filters are subsequently paused or running, the source filter will signal the end of stream again if it has no data to send. In this case, the renderer should signal another EC_COMPLETE event to the filter graph manager. This member function resets the state so that when next requested it will send an EC_COMPLETE event.


CBaseRenderer::Run

HRESULT Run(void);

Transitions the renderer to State_Running if it is not in this state already.

•	Returns an HRESULT value.

This member function holds the renderer's lock. If the renderer is in the State_Stopped state, the CBaseRenderer::Pause member function is called first to transition the renderer to the State_Paused state, which has the effect of activating any of the filter's connected pins. If this member function succeeds, the renderer's m_State member variable is set to State_Running.

This member function overrides CBaseFilter::Run.


CBaseRenderer::ScheduleSample

virtual BOOL ScheduleSample(

    IMediaSample *pMediaSample);

Schedules the sample for rendering.

pMediaSample

Media sample.

One of the main purposes of the renderer base class is to manage the timing and synchronization of the samples it is sent, that is, the timely presentation of data. It also has to look after quality management, which may involve dropping samples or rendering them earlier than indicated in the time stamps on the sample. This method and its overrides in derived classes manage the setting up of advise links with the clock so that the samples can be rendered at the appropriate time.


CBaseRenderer::SendEndOfStream

virtual HRESULT SendEndOfStream(void);

Signals an EC_COMPLETE event to the filter graph manager.

•	Returns an HRESULT value.

When the renderer receives an end-of-stream notification, it will finish rendering any data it currently has and then send an EC_COMPLETE event to the filter graph manager.


CBaseRenderer::SendRepaint

void SendRepaint(void)

Signals an EC_REPAINT message to the filter graph.

This member function can be used so that other objects in the renderer can signal repaints directly rather than having to generate WM_PAINT messages.


CBaseRenderer::SetAbortSignal

void SetAbortSignal(BOOL bAbort);

Sets the m_bAbort abort signal flag.

•	Returns an HRESULT value.

bAbort

Abort value to be set.


CBaseRenderer::SetMediaType

virtual HRESULT SetMediaType( const CMediaType *pmt);

Informs the derived class of the selected media type.

•	Returns NOERROR by default; the overriding member function should return a valid HRESULT value.

pmt

Media type to be set.

This member function is called by the CRendererInputPin::SetMediaType member function and has no implementation in this class. Derived classes can optionally override to add functionality.


CBaseRenderer::SetRepaintStatus

void SetRepaintStatus(BOOL bRepaint)

Resets the m_bRepaintStatus flag when EC_REPAINT has been signaled to the filter graph.

bRepaint

Boolean value assigned to the m_bRepaintStatus flag.

The DirectDraw object uses this method to control the window repainting.

The m_bRepaintStatus flag ensures that the filter graph is not flooded with redundant calls.


CBaseRenderer::ShouldDrawSampleNow

virtual HRESULT ShouldDrawSampleNow(

    IMediaSample *pMediaSample,

    REFERENCE_TIME *pStartTime,

    REFERENCE_TIME *pEndTime );

Determines if the sample should be drawn between the start and stop times given.

•	Returns S_FALSE by default. The overriding member function can return S_OK to indicate that the sample should be drawn immediately instead of waiting for its scheduled time.

pMediaSample

Media sample.

pStartTime

Start time in question.

pEndTime

End time in question.

This member function is used by the derived class for quality management.


CBaseRenderer::SignalTimerFired

virtual void SignalTimerFired(void);

Resets the current advise time to zero after a timer fires.


CBaseRenderer::SourceThreadCanWait

virtual HRESULT SourceThreadCanWait( BOOL bCanWait);

Sets or resets the thread event.

•	Returns an HRESULT value.

bCanWait

TRUE or FALSE, depending on intent.

In some states, such as paused or running, it is expected that the upstream filter's thread will be blocked in the call to the renderer's input pin Receive method. In other cases, such as when the renderer is stopped, the upstream filter should not be required to wait. This member function represents a manual reset event that sets this TRUE to wait, or FALSE to keep the thread from waiting.


CBaseRenderer::StartStreaming

virtual HRESULT StartStreaming(void);

Called to schedule any pending image with the clock and to display timing information.

•	Returns an HRESULT value.

If no sample is available but an end-of-stream flag is queued, this member function sends the message to the filter graph manager. If a sample is available, the function waits until the sample has been rendered before signaling the filter graph manager. Otherwise, the state may be changed before the sample is done.


CBaseRenderer::Stop

HRESULT Stop(void);

Transitions the renderer to State_Stopped if it is not in this state already.

•	Returns an HRESULT value.

This member function holds the renderer's lock. If the renderer is not in the State_Stopped state, the CRendererInputPin::Inactive member function is called for each of the renderer's connected pins. If this member function succeeds, the filter's m_State member variable is set to State_Stopped.

This member function overrides CBaseFilter::Stop.


CBaseRenderer::StopStreaming

virtual HRESULT StopStreaming(void);

Sets the internal flag to indicate not to schedule arrival of any more samples.

•	Returns an HRESULT value.

Call this member function when streaming stops. The state change methods in the filter implementation take care of canceling any clock advise link that has been set up and clearing any pending sample.


CBaseRenderer::WaitForRenderTime

virtual HRESULT WaitForRenderTime(void);

Waits for either the due time for the current sample to arrive or for rendering to be stopped.

•	Returns an HRESULT value.

The member function is virtual because derived classes may have more events that they also want to wait on, which may interrupt the waiting process. The base class has two events: m_RenderEvent and m_ThreadSignal. The former is signaled by the clock when the sample is due for rendering. The latter is signaled by the filter when it should give up waiting and abort (making the assumption that the filter was stopped).


CBaseVideoRenderer Class

This 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_idDebug 	Spare MSR_id.

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_trFrame 	Most recently recorded time between frames. Used in statistical measurements.

m_trFrameAvg 	Average interframe time in reference time units.

m_trEarliness 	How early a frame is allowed to be played when a frame has just been dropped.

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_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_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_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.

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 code 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(CLSID RenderClass, TCHAR *pName,

    LPUNKNOWN pUnk, HRESULT *phr)

Constructs a CBaseVideoRenderer object.

RenderClass

Class identifier for this renderer.

pName

Description used for debugging purposes.

pUnk

Pointer to the aggregated owner object.

phr

Pointer to an HRESULT value.


CBaseVideoRenderer::get_AvgFrameRate

HRESULT get_AvgFrameRate(int *piAvgFrameRate)

Calculates and retrieves the average frame rate achieved.

•	Returns an HRESULT value.

piAvgFrameRate

Number of frames per second since streaming began.

This member function implements the IQualProp::get_AvgFrameRate method.


CBaseVideoRenderer::get_AvgSyncOffset

HRESULT get_AvgSyncOffset(int *piAvg);

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.

•	Returns an HRESULT value.

piAvg

Pointer to the average of the time as described above.

This member function implements the IQualProp::get_AvgSyncOffset method.


CBaseVideoRenderer::get_DevSyncOffset

HRESULT get_DevSyncOffset(int *piDev);

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.

•	Returns an HRESULT value.

piDev

Pointer to the standard deviation of the time as described above.

This member function implements the IQualProp::get_DevSyncOffset method.


CBaseVideoRenderer::get_FramesDrawn

HRESULT get_FramesDrawn(int *pcFramesDrawn)

Retrieves the m_cFramesDrawn member variable, giving the number of frames drawn since streaming started.

•	Returns an HRESULT value.

pcFramesDrawn

Number of frames drawn.

This member function implements the IQualProp::get_FramesDrawn method.


CBaseVideoRenderer::get_FramesDroppedInRenderer

HRESULT get_FramesDroppedInRenderer(

    int *pcFramesDropped)

Retrieves the number of frames dropped by the renderer.

•	Returns an HRESULT value.

pcFramesDropped

Number of frames dropped.

This member function implements the IQualProp::get_FramesDroppedInRenderer method. This is how the property page retrieves the data from the scheduler. Note that frames can also be dropped upstream without the renderer even seeing them.


CBaseVideoRenderer::get_Jitter

HRESULT get_Jitter(int *piJitter)

Retrieves the standard deviation of time in milliseconds between each frame and the next for all frames since streaming started.

•	Returns an HRESULT value.

piJitter

Standard deviation of the interframe time in milliseconds.

This member function implements the IQualProp::get_Jitter method.


CBaseVideoRenderer::JoinFilterGraph

HRESULT JoinFilterGraph(IFilterGraph * pGraph,

    LPCWSTR pName);

Sends EC_WINDOW_DESTROYED event code when a filter is removed from the filter graph.

pGraph

Pointer to the filter graph to join.

pName

[in, string] Name of the filter being added.

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 message so that the resource manager does not hold on to the renderer as a focus object.


CBaseVideoRenderer::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface( REFIID riid,

    VOID **ppv)

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this member function to publish the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method. It exposes the IQualProp interface and then calls CBaseRenderer::NonDelegatingQueryInterface to expose interfaces implemented in the base classes.


CBaseVideoRenderer::Notify

HRESULT Notify(IFilter * pSelf, Quality q);

Receives a notification that a quality change is requested.

•	Returns an HRESULT value.

pSelf

[in] Pointer to the filter that is sending the quality notification.

q

[in] Quality notification structure.

This member function implements the IQualityControl::Notify method on the video renderer. This is called, typically by the filter graph manager, when the quality needs to 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

virtual void OnDirectRender(

    IMediaSample *pMediaSample)

Collects timing information that controls synchronization and quality control.

•	Returns an HRESULT value.

pMediaSample

Media sample.

Call this member function instead of OnRenderStart and OnRenderEnd in the case of Microsoft® DirectDraw™.


CBaseVideoRenderer::OnRenderEnd

void OnRenderEnd(IMediaSample *pMediaSample)

Performs smoothing for cases where the rendering time varies due to interruptions.

pMediaSample

Media sample.

This member function should be called just after drawing an image.

This member function overrides CBaseRenderer::OnRenderEnd.


CBaseVideoRenderer::OnRenderStart

void OnRenderStart(IMediaSample *pMediaSample)

Sets information for rendering.

pMediaSample

Media sample.

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 completed. The function also performs performance logging. This member function should be called just before drawing starts.

This member function overrides CBaseRenderer::OnRenderStart.


CBaseVideoRenderer::OnStartStreaming

HRESULT OnStartStreaming(void)

Resets all times that control streaming.

•	Returns an HRESULT value.

This member function overrides CBaseRenderer::OnStartStreaming.


CBaseVideoRenderer::OnStopStreaming

HRESULT OnStopStreaming(void)

Called at the end of streaming to fix times for the property page report.

•	Returns an HRESULT value.

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

void OnWaitEnd(void)

Called when a wait time ends.

This member function only does 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

void OnWaitStart(void)

Updates times spent waiting and not waiting.

This member function is called when starting to wait for a rendering event. It is used for performance measurements only.


CBaseVideoRenderer::PreparePerformanceData

void PreparePerformanceData(int trLate, int trFrame)

Sets the m_trLate and m_trFrame values of the current frame.

trLate

How late the sample was beyond its due time, in reference time units.

trFrame

Interframe time, in reference time units.

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

virtual void RecordFrameLateness(int trLate,

    int trFrame)

Records how timely the rendering occurred and gathers statistics for the property page.

trLate

How late the sample was beyond its due time, in reference time units.

trFrame

Interframe time, in reference time units.

Override for special processing.


CBaseVideoRenderer::ResetStreamingTimes

virtual HRESULT ResetStreamingTimes(void)

Resets all times that control the streaming.

•	Returns an HRESULT value.

The times are set so that frames will not be initially dropped and so that the first frame will be drawn.

Override for special processing.


CBaseVideoRenderer::ScheduleSample

BOOL ScheduleSample(IMediaSample *pMediaSample)

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).

•	Returns TRUE if the sample is scheduled; otherwise, returns FALSE.

pMediaSample

Media sample.


CBaseVideoRenderer::SendQuality

virtual HRESULT SendQuality(

    REFERENCE_TIME trLate,

    REFERENCE_TIME trRealStream)

Sends a quality message to indicate what the supplier should do about quality.

•	Returns an HRESULT value.

trLate

Amount of time by which the frame is late.

trRealStream

Current stream time.

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

HRESULT SetSink(IQualityControl *piqc);

Sets the IQualityControl object that will receive quality messages.

•	Returns an HRESULT value.

piqc

Pointer to the IQualityControl object to which the notifications should be sent.

This member function implements the IQualityControl::SetSink method on the video renderer.


CBaseVideoRenderer::ShouldDrawSampleNow

virtual HRESULT ShouldDrawSampleNow(

    IMediaSample *pMediaSample,

    REFERENCE_TIME *ptrStart,

    REFERENCE_TIME *ptrEnd)

Determines if the video should be drawn without setting a timer advise link with the clock.

•	Returns an HRESULT value. Returns S_OK to mean draw at once without waiting, S_FALSE to mean draw at time ptrStart, or error to mean do not draw the sample, that is, skip it to save time.

pMediaSample

IMediaSample interface for the sample.

ptrStart

Time to begin rendering.

ptrEnd

Time to stop rendering.

This member function overrides CBaseRenderer::ShouldDrawSampleNow.


CBaseVideoRenderer::ThrottleWait

void ThrottleWait(void);

Inserts a wait period after each frame.

This member function waits for a time period obtained from the m_trThrottle data member.


CBaseVideoWindow Class

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(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT * phr);

Constructs a CBaseVideoWindow object.

pName

Name of the object used in the CBaseVideoWindow constructor for debugging purposes.

pUnk

Pointer to the owner of this object.

phr

Pointer to an HRESULT value for resulting information.

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of an object.


CBaseVideoWindow::GetIDsOfNames

HRESULT GetIDsOfNames(REFIID riid,

    OLECHAR  ** rgszNames, UINT cNames,

    LCID lcid, DISPID * rgdispid);

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.

•	Returns one of the following values.

Value 	Meaning

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.

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

The locale context in which to interpret the names.

rgdispid

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.


CBaseVideoWindow::GetTypeInfo

HRESULT GetTypeInfo(UINT itinfo, LCID lcid,

    ITypeInfo ** pptinfo);

Retrieves a type-information object, which can retrieve the type information for an interface.

•	Returns an HRESULT value.

itinfo

The type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

The locale ID for the type information. An object may 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

A pointer to the type-information object requested.


CBaseVideoWindow::GetTypeInfoCount

HRESULT GetTypeInfoCount(UINT * pctinfo);

Retrieves the number of type-information interfaces provided by an object.

•	Returns an HRESULT value.

pctinfo

Points 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.


CBaseVideoWindow::Invoke

HRESULT Invoke(DISPID dispidMember, REFIID riid,

    LCID lcid, WORD wFlags, DISPPARAMS * pdispparams,

    VARIANT * pvarResult, EXCEPINFO * pexcepinfo,

    UINT * puArgErr);

Provides access to properties and methods exposed by an object.

•	Returns an HRESULT value.

dispidMember

Identifies 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

The locale context in which to interpret arguments.

wFlags

Flags describing the context of the CBaseVideoWindow::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

The index of the first argument, within the rgvarg array, that has an error.


CBaseVideoWindow::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void **ppv);

Returns a specified reference-counted interface.

•	Returns pointers to the IVideoWindow and IUnknown interfaces by default.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this method to publish any additional interfaces implemented by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CBaseWindow Class

The CBaseWindow class creates a window and a worker thread. The worker thread is responsible for pulling messages from the window's input queue and dispatching them as appropriate. The window and its thread are created by the CBaseWindow::PrepareWindow member function and destroyed by the CBaseWindow::DoneWithWindow member function. The window should also be initialized by the CBaseWindow::InitialiseWindow member function and uninitialized by the CBaseWindow::UninitialiseWindow. Having prepared a window and initialized it, size the window using the CBaseWindow::ActivateWindow member function; hide the window using the CBaseWindow::InactivateWindow member function.

Public Data Members

s_pInitBaseWindow 	The base window.

Protected Data Members

m_bActivated 	Flag to indicate window activation status.

m_bBackground 	Flag to indicate if palettes are to be realized in the background.

m_ClassStyles 	Class styles for the window.

m_GoodByeMessage 	Message sent by the destructor to destroy the window.

m_hdc 	Device context (DC) for the window.

m_Height 	Client window height.

m_hInstance 	Global module instance handle.

m_hPalette 	Handle to a palette belonging to this object.

m_hwnd 	Handle for this object's window.

m_MemoryDC 	Memory DC used for fast bit-block transfer operations.

m_pClassName 	Static string holding class name.

m_ShowStageMessage 	Message sent by IVideoWindow::SetWindowForeground to have the window shown topmost with focus.

m_SyncWorker 	Data member used to signal the constructor for the window class when to create the window.

m_hThread 	Worker thread for the window.

m_ThreadSignal 	Data member used by the thread to signal errors.

m_Width 	Client window width.

m_WindowLock 	Data member used to serialize window object access.

m_WindowStyles 	Data member used to serialize the initial window styles.

m_WindowStylesEx 	Data member used to serialize the initial extended window styles.

Member Functions

CBaseWindow 	Constructs a CBaseWindow object.

DoSetWindowForeground 	Brings the window to the foreground.

DoShowWindow 	Sets the show state of the specified window.

GetMemoryHDC 	Retrieves the default off-screen memory device context (DC).

GetWindowHDC 	Retrieves the default main window DC.

GetWindowHeight 	Retrieves the current window height.

GetWindowHWND 	Retrieves the window handle for the window.

GetWindowWidth 	Retrieves the current window width.

PerformanceAlignWindow 	Aligns the window to a DWORD boundary for maximum performance.

PaintWindow 	Invalidates the window client area.

Overridable Member Functions

ActivateWindow 	Sizes the window according to the requirements of the derived class.

DoneWithWindow 	Closes, deletes, and frees the window resources.

DoRealisePalette 	Selects and realizes the current palette in the window.

GetClassWindowStyles 	Returns class and window information.

GetDefaultRect 	Returns the default size for the window.

InactivateWindow 	Hides the window.

InitialiseWindow 	Creates the default device contexts.

MessageLoop 	Implements a window message loop.

OnClose 	Handles the WM_CLOSE message for the base class.

OnPaletteChange 	Handles WM_PALETTEISCHANGING and WM_PALETTECHANGED messages.

OnSize 	Handles WM_SIZE messages for the base class.

OnReceiveMessage 	Indicates a base class implementation of a window procedure.

PrepareWindow 	Initializes the window along with a worker thread.

SetPalette 	Changes the palette that the window should realize.

UninitialiseWindow 	Destroys the device contexts created for the window.


CBaseWindow::ActivateWindow

virtual HRESULT ActivateWindow();

Sizes the window according to the requirements of the derived class.

•	Returns an HRESULT value.

This member function calls CBaseWindow::GetDefaultRect, which a derived class should override to return the size of the images that will be displayed. ActivateWindow then sizes the window so that the client area matches this size.


CBaseWindow::CBaseWindow

CBaseWindow();

Constructor for the CBaseWindow class.

The window and its worker thread are created by CBaseWindow::PrepareWindow and destroyed by CBaseWindow::DoneWithWindow.


CBaseWindow::DoneWithWindow

virtual HRESULT DoneWithWindow();

Destroys the window and its worker thread.

•	Returns an HRESULT value.

The base window class creates a window and a worker thread. The worker thread is responsible for pulling messages from the window's input queue and dispatching them as appropriate. The window and its thread are created by CBaseWindow::PrepareWindow and destroyed by CBaseWindow::DoneWithWindow. The window should also be initialized using CBaseWindow::InitialiseWindow and uninitialized using CBaseWindow::UninitialiseWindow. Having prepared a window and initialized it, the window can be sized using CBaseWindow::ActivateWindow and subsequently hidden using CBaseWindow::InactivateWindow.


CBaseWindow::DoRealisePalette

virtual HRESULT DoRealisePalette();

Realizes any palette provided to the window.

•	Returns an HRESULT value.

The window class is given a palette handle to use with the CBaseWindow::SetPalette member function. Once a palette has been installed, it can be realized by calling this member function. The class will also call this member function when it gets WM_QUERYNEWPALETTE and WM_PALETTECHANGED messages from the Microsoft® Windows® operating systems.

This is a protected member function.


CBaseWindow::DoSetWindowForeground

void DoSetWindowForeground(BOOL bFocus);

Sets the window in the foreground.

bFocus

Gives the window the foreground focus.

The thread that owns the window provides foreground status. This member function provides this status by sending a private message to the window, which instructs it to set itself in the foreground. If the window is visible, it will be brought to the front but not activated. If the window is not visible, it will be shown using CBaseWindow::DoShowWindow (SW_SHOWNORMAL). If the input parameter is TRUE, the window will always be forced to the foreground.


CBaseWindow::DoShowWindow

HRESULT DoShowWindow(LONG ShowCmd);

Sets the show state of the specified window.

•	Returns an HRESULT value.

ShowCmd

Specifies how the window is to be shown.

This member function simply calls the Microsoft Win32® ShowWindow function.


CBaseWindow::GetClassWindowStyles

virtual LPTSTR GetClassWindowStyles(DWORD *pClassStyles,

    DWORD *pWindowStyles, DWORD *pWindowStylesEx) PURE;

Returns class and window information.

•	Returns a class name that is a static text string.

pClassStyles

Class styles.

pWindowStyles

Window styles.

pWindowStylesEx

Extended window styles.

A derived class must override this pure virtual member function to provide the default class and window styles for the window. The information the derived class returns is used in CBaseWindow::PrepareWindow when the window is first created. The class and window styles take the same parameters as their counterparts in the Microsoft Win32 CreateWindowEx function. The string that is returned should be allocated as a static string and should still be valid after the member function returns.


CBaseWindow::GetDefaultRect

virtual RECT GetDefaultRect();

Retrieves the default size for the window client area.

•	Returns the default rectangle.

When the window is activated, it calls this member function to determine how large it should make the window's client area. A video renderer will typically return the size of the native video image.


CBaseWindow::GetMemoryHDC

virtual HDC GetMemoryHDC();

Retrieves the default memory device context (DC).

•	Returns the default memory DC.

The base window class creates a window with a worker thread when it is prepared (in CBaseWindow::PrepareWindow). It also creates two DCs that can be used for drawing. The first is a normal window HDC; the second is an off-screen HDC that can be used as a source HDC in bit-block transfer functions.


CBaseWindow::GetWindowHDC

HDC GetWindowHDC();

Retrieves the default window device context (DC).

•	Returns the default window DC.

The base window class creates a window with a worker thread when it is prepared (in CBaseWindow::PrepareWindow). It also creates two DCs that can be used for drawing. The first is a normal window HDC; the second is an off-screen HDC that can be used as a source HDC in bit-block transfer functions.


CBaseWindow::GetWindowHeight

LONG GetWindowHeight();

Retrieves the current window height.

•	Returns the window height in pixels.

This member function is updated when the base class receives WM_SIZE messages.


CBaseWindow::GetWindowHWND

HWND GetWindowHWND();

Retrieves the window handle associated with this object.

•	Returns a window handle.

If called before issuing a CBaseWindow::PrepareWindow call, this member function returns NULL.


CBaseWindow::GetWindowWidth

LONG GetWindowWidth();

Retrieves the current window width.

•	Returns the window width in pixels.

This member function is updated when the base class receives WM_SIZE messages.


CBaseWindow::InactivateWindow

virtual HRESULT InactivateWindow();

Effectively hides the window (if it was visible).

•	Returns an HRESULT value.

The base window class creates a window and a worker thread. The worker thread is responsible for pulling messages from the window's input queue and dispatching them as appropriate. The window and its thread are created by CBaseWindow::PrepareWindow and destroyed in CBaseWindow::DoneWithWindow. The window should be initialized through CBaseWindow::InitialiseWindow and uninitialized through CBaseWindow::UninitialiseWindow. Having prepared a window and initialized it, the window can be sized using CBaseWindow::ActivateWindow and subsequently hidden using CBaseWindow::InactivateWindow.


CBaseWindow::InitialiseWindow

virtual InitialiseWindow(HWND hwnd);

Creates default device contexts for the window.

•	Returns an HRESULT value.

hwnd

Window handle.

The base window class creates a window and a worker thread. The worker thread is responsible for pulling messages from the window's input queue and dispatching them as appropriate. The window and its thread are created by CBaseWindow::PrepareWindow and destroyed in CBaseWindow::DoneWithWindow. The window should be initialized through CBaseWindow::InitialiseWindow and uninitialized through CBaseWindow::UninitialiseWindow. Having prepared a window and initialized it, the window can be sized using CBaseWindow::ActivateWindow and subsequently hidden using CBaseWindow::InactivateWindow.

The base class creates two device contexts that can be used for drawing. The first is a standard HDC for the window; the second is an off-screen HDC. The off-screen HDC often is useful for selecting bitmaps before calling the Microsoft Win32 BitBlt or StretchBlt function to copy the bitmap to the main window. This member function also sets the default stretch mode to be COLORONCOLOR. The member function is virtual so that derived classes can change this default if desired.


CBaseWindow::MessageLoop

virtual HRESULT MessageLoop();

Implements a window message loop.

•	Returns an HRESULT value.

Any application that creates a window must have a message loop that retrieves and dispatches messages from the window's input queue. After retrieving a message, this member function calls the CBaseWindow::OnReceiveMessage member function that belongs to the object. The CBaseWindow::MessageLoop member function is a virtual member function so that derived classes can do more complex handling of messages in the loop.


CBaseWindow::OnClose

virtual BOOL OnClose();

Handles the WM_CLOSE message.

The default behavior for this member function is to simply hide the window. A derived class should not destroy the window when it receives a WM_CLOSE message but should send an EC_USERABORT notification to the filter graph manager. This in turn will have the playback stopped and in some cases will also have the filters disconnected and released. It is only when the filter that owns the window is finally released (that is, destroyed) that the derived class should actually destroy the window (using CBaseWindow::DoneWithWindow).


CBaseWindow::OnPaletteChange

virtual LRESULT OnPaletteChange(HWND hwnd,

    UINT Message);

Handles WM_PALETTEISCHANGING and WM_PALETTECHANGED messages.

•	Returns one of the following values.

0 	Message was not handled.

1 	Message was processed.

hwnd

Handle of the window causing the message.

Message

Message details passed on from the window procedure.

When the base class receives a WM_PALETTEISCHANGING message, it realizes its palette again. It must also do this when told, through WM_PALETTECHANGED, that the system palette has changed. In the latter case, however, it must be careful not to realize its palette if it was the window that caused the WM_PALETTECHANGED message (which is why the window that caused the message to be sent is passed into the member function).

This is a protected member function.


CBaseWindow::OnReceiveMessage

virtual LRESULT OnReceiveMessage(HWND hwnd, INT uMsg,

    WPARAM wParam, LPARAM lParam);

Base class implementation of a window procedure.

•	Returns an LRESULT value depending on the message sent. By default, this returns 1 for the WM_SYSCOLORCHANGE message or when sent m_ShowStageMessage. Otherwise, it returns 0, the value returned by DefWinProc, or the value returned by CBaseWindow::OnPaletteChange if sent the WM_QUERYNEWPALETTE message.

hwnd

Window handle.

uMsg

Message identifier.

wParam

The message's wParam parameter.

lParam

The message's lParam parameter.

The base class has default handling for a number of messages. In particular, it looks after palette (for example, WM_PALETTEISCHANGING), size (WM_SIZE), device management (for example, WM_SYSCOLORCHANGE), and termination messages (for example, WM_CLOSE and WM_DESTROY), among others. It calls the Microsoft Win32 DefWinProc function after checking for other messages.


CBaseWindow::OnSize

virtual BOOL OnSize(LONG Width, LONG Height);

Handles the WM_SIZE message.

Width

Window width.

Height

Window height.

This member function stores the window width and height so that they can be returned from the CBaseWindow::GetWindowHeight and CBaseWindow::GetWindowWidth member functions.


CBaseWindow::PaintWindow

void PaintWindow(BOOL bErase);

Invalidates the window client area.

bErase

Determines if the background should be erased.


CBaseWindow::PerformanceAlignWindow

HRESULT PerformanceAlignWindow();

Aligns the window to a DWORD boundary for maximum performance.

•	Returns an HRESULT value.

This member function can be called, if the video is not owned by another window, to align the left edge and the top of the window for best display performance.


CBaseWindow::PrepareWindow

virtual HRESULT PrepareWindow();

Creates a window and a worker thread.

•	Returns an HRESULT value.

The base window class creates a window and a worker thread. The worker thread is responsible for pulling messages from the window's input queue and dispatching them as appropriate. The window and its thread are created by CBaseWindow::PrepareWindow and destroyed in CBaseWindow::DoneWithWindow. The window should also be initialized and uninitialized through CBaseWindow::InitialiseWindow and CBaseWindow::UninitialiseWindow, respectively. Having prepared a window and initialized it, the window can be sized using CBaseWindow::ActivateWindow and subsequently hidden using CBaseWindow::InactivateWindow.


CBaseWindow::SetPalette

virtual HRESULT SetPalette(HPALETTE hPalette);

Sets a palette for the window to use.

•	Returns an HRESULT value.

hPalette

Handle to the new palette.

This member function allows a filter to install a palette in the window object. The palette handle passed in should be non-NULL. The palette is realized when it is installed. The window object does not delete any previous palette that it was using; the client using the window object should make sure it deletes the palette it creates at the appropriate time.


CBaseWindow::UninitialiseWindow

virtual UninitialiseWindow();

Flushes GDI and deletes the default device contexts.

•	Returns an HRESULT value.

The base window class creates a window and a worker thread. The worker thread is responsible for pulling messages from the window's input queue and dispatching them as appropriate. The window and its thread are created by CBaseWindow::PrepareWindow and destroyed in CBaseWindow::DoneWithWindow. The window should also be initialized and uninitialized through CBaseWindow::InitialiseWindow and CBaseWindow::UninitialiseWindow, respectively. Having prepared a window and initialized it, the window can be sized using CBaseWindow::ActivateWindow and subsequently hidden using CBaseWindow::InactivateWindow.


CBasicAudio Class

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::GetTypeInfoCount, CBasicAudio::GetTypeInfo, CBasicAudio::GetIDsOfNames, 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® ActiveMovie™ 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 -10000 is the minimum volume (normally silence). Balance is expressed in the range -10000 to 10000, with 0 being neutral. A negative balance value means that the right channel is attenuated by this dB 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 	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 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(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT * phr);

Constructs a CBasicAudio object.

pName

Name of the object used in the CBasicAudio constructor for debugging purposes.

pUnk

Pointer to the owner of this object.

phr

Pointer to an HRESULT value for the resulting information.

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.


CBasicAudio::GetIDsOfNames

HRESULT GetIDsOfNames(REFIID riid,

    OLECHAR  ** rgszNames, UINT cNames,

    LCID lcid, DISPID * rgdispid);

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.

•	Returns one of the following values.

Value 	Meaning

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.

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

The locale context in which to interpret the names.

rgdispid

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.


CBasicAudio::GetTypeInfo

HRESULT GetTypeInfo(UINT itinfo, LCID lcid,

    ITypeInfo ** pptinfo);

Retrieves a type-information object, which can retrieve the type information for an interface.

•	Returns an HRESULT value.

itinfo

The type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

The locale ID for the type information. An object may 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

A pointer to the type-information object requested.


CBasicAudio::GetTypeInfoCount

HRESULT GetTypeInfoCount(UINT * pctinfo);

Retrieves the number of type-information interfaces provided by an object.

•	Returns an HRESULT value.

pctinfo

Points 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.


CBasicAudio::Invoke

HRESULT Invoke(DISPID dispidMember, REFIID riid,

    LCID lcid, WORD wFlags, DISPPARAMS * pdispparams,

    VARIANT * pvarResult, EXCEPINFO * pexcepinfo,

    UINT * puArgErr);

Provides access to properties and methods exposed by an object.

•	Returns an HRESULT value.

dispidMember

Identifies 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

The locale context in which to interpret arguments.

wFlags

Flags describing the context of the CBasicAudio::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

The index of the first argument, within the rgvarg array, that has an error.


CBasicAudio::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void **ppv);

Returns a specified reference-counted interface.

•	Returns pointers to the IBasicAudio and IUnknown interfaces by default.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this member function to publish any addition 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 needs to 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 only advance 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 CCmdQueue::GetDueCommand member function (probably with a time-out of zero); this may return E_ABORT.

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 need to 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_Lock 	Protects access to lists.

m_listPresentation 	Stores commands queued in presentation time.

m_listStream 	Stores commands queued in stream time.

m_evDue 	Sets the time when any commands are due.

m_dwAdvise 	Advise identifier from the reference clock (zero if no outstanding advise).

m_tCurrentAdvise 	Advise time is for this presentation time.

m_pClock 	The current reference clock.

m_bRunning 	Flag for running state; set TRUE when running.

m_StreamTimeOffset 	Contains the stream time offset when m_bRunning is true.

Member Functions

CCmdQueue 	Constructs a CCmdQueue object.

CheckTime 	Determines if a given time is due.

GetDueHandle 	Returns the event handle that will be signaled.

Overridable Member Functions

EndRun 	Switches to stopped or paused mode.

GetCommandDueFor 	Returns a pointer to a command that will be due for a given time.

GetDueCommand 	Returns a pointer to the next command that is due.

Insert 	Adds the CDeferredCommand object to the queue.

New 	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 	Creates an advise for the earliest time required.


CCmdQueue::CCmdQueue

CCmdQueue();

Constructs a CCmdQueue object.


CCmdQueue::CheckTime

BOOL CheckTime(CRefTime time, BOOL bStream);

Determines if a specified time is due.

•	Returns TRUE if the specified time has not yet passed.

time

The time to check.

bStream

TRUE if the time parameter is a stream-time value; FALSE if time is a presentation-time value.


CCmdQueue::EndRun

virtual HRESULT EndRun();

Switches to the stopped or paused mode.

•	Returns an HRESULT value.

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

virtual HRESULT GetCommandDueFor(REFERENCE_TIME tStream,

    CDeferredCommand**ppCmd);

Returns a deferred command that is scheduled at a specified time.

•	Returns an HRESULT value. Returns VFW_E_NOT_FOUND if no commands are due.

tStream

Time for which the command is scheduled.

ppCmd

Deferred command to be carried out at the time specified in the tStream parameter.

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

virtual HRESULT GetDueCommand(CDeferredCommand ** ppCmd,

    long msTimeout);

Returns a pointer to the next command that is due.

•	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.

ppCmd

Pointer to the deferred command.

msTimeout

The amount of time to wait before carrying out the time-out.

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

HANDLE GetDueHandle();

Returns the event handle to be signaled.

•	Returns an HRESULT value.

Return the event handle whenever there are deferred commands that are due for execution (when CCmdQueue::GetDueCommand will not block).


CCmdQueue::Insert

virtual HRESULT Insert(CDeferredCommand* pCmd);

The CDeferredCommand object calls this member function to add itself to the queue.

•	Returns an HRESULT value.

pCmd

Pointer to the CDeferredCommand object to add to the queue.


CCmdQueue::New

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

    );

Initializes a command to be run and returns a new CDeferredCommand object.

•	Returns S_OK if successful; otherwise, returns an error value and no object has been queued.

ppCmd

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

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 OLE IDispatch::DispInvoke 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 are to be returned, if any.

puArgErr

The index within the pDispParams parameter list where the last error occurred.

bStream

TRUE if the time parameter is a stream-time value; FALSE if time is a presentation-time value.

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 OLE IDispatch::DispInvoke method.

Values for the wFlags parameter include the following.

Value 	Description

DISPATCH_METHOD 	The member is being run as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag may 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

virtual HRESULT Remove(CDeferredCommand* pCmd);

The CDeferredCommand object calls this member function to remove itself from the queue.

•	Returns an HRESULT value.

pCmd

Pointer to the CDeferredCommand object to remove from the queue.


CCmdQueue::Run

virtual HRESULT Run(REFERENCE_TIME tStreamTimeOffset);

Switches to running mode so that commands that are deferred by the stream time can be run.

•	Returns an HRESULT value.

tStreamTimeOffset

Offset time.

During running mode, stream-time-to-presentation-time mapping is known.


CCmdQueue::SetSyncSource

virtual HRESULT SetSyncSource(IReferenceClock* pIrc);

Sets the clock used for timing.

•	Returns an HRESULT value.

pIrc

Pointer to the IReferenceClock interface.


CCmdQueue::SetTimeAdvise

void SetTimeAdvise(void);

Sets up a timer event with the reference clock.

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

The critical section object provides intraprocess synchronization. The current implementation uses the Microsoft® Win32® application programming interfaces (APIs) that use the CRITICAL_SECTION type.

The safest way to use CCritSec objects is to lock them with a CAutoLock object that guarantees to unlock the object when it goes out of scope and compiles to efficient inline code.

Member Functions

CCritSec 	Constructs a CCritSec object.

Lock 	Locks the critical section object.

Unlock 	Unlocks the critical section object.


CCritSec::CCritSec

CCritSec();

Constructs a CCritSec object.

Calls the Microsoft Win32 InitializeCriticalSection function to set the private critical section member variable. The destructor calls the Microsoft Win32 DeleteCriticalSection function.


CCritSec::Lock

void Lock();

Locks the critical section object.

This member function locks the critical section object. You can make multiple lock calls on the same thread, but the CCritSec::Unlock member function must be called a corresponding number of times before the object is unlocked. If the object is locked by another thread, the CCritSec::Lock member function blocks until either the object is released or a "possible deadlock" exception occurs.


CCritSec::Unlock

void Unlock();

Releases the lock on the object acquired by calling the CCritSec::Lock member function.

You must call the CCritSec::Unlock member function once for each call to Lock.


CDeferredCommand Class

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_pQueue 	Pointer to the CCmdQueue object that exposes the IQueueCommand interface.

m_pUnk 	IUnknown pointer to the interface on which the command will be executed.

m_time 	Time at which the command will be run.

m_iid 	Globally unique identifier (GUID) of the interface.

m_dispidMethod 	Method on the interface to run.

m_wFlags 	Flags specifying the context of the invocation.

m_pvarResult 	Resulting information from the invoked method, if any.

m_bStream 	Flag for stream time or presentation time.

m_DispParams 	CDispParams object containing the DISPPARAM parameter list to be passed to the invoked method.

m_Dispatch 	Accesses the ITypeInfo interface.

m_hrResult 	Stores the returned HRESULT value.

Member Functions

CDeferredCommand 	Constructs a CDeferredCommand object.

GetFlags 	Returns the context flags associated with the deferred command.

GetIID 	Returns the interface identifier (IID) of the interface on which the method will be run.

GetMethod 	Returns the dispatch identifier of the method to be run.

GetParams 	Returns the DISPPARAMS argument list to the method.

GetResult 	Returns the resulting argument list, if one exists.

GetTime 	Returns 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 	Returns a confidence value that describes the probability of the deferred command being executed on time.

Postpone 	Specifies a new presentation time for a previously queued command.

GetHResult 	Returns the HRESULT value of the invoked method.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Returns a specified reference-counted interface.


CDeferredCommand::Cancel

HRESULT Cancel();

Cancels a previously queued CDeferredCommand::Invoke request.

•	Returns an HRESULT value.

This member function implements the IDeferredCommand::Cancel method.


CDeferredCommand::CDeferredCommand

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);

Constructs a CDeferredCommand object.

pQ

The object that exposes the IQueueCommand interface.

pUnk

Outer IUnknown interface for aggregation.

phr

Returning HRESULT value.

pUnkExecutor

Object that will carry out this command.

time

Time at which the command will be run.

iid

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

List of argument variant types.

pvarResult

Returned variant type list, if any.

puArgErr

Last argument in the pDispParams parameter list with an error.

bStream

TRUE if the deferred command time is in stream time; FALSE if in presentation time.


CDeferredCommand::Confidence

HRESULT Confidence(LONG *pConfidence);

Retrieves a confidence value on a scale of 0 to 100 that describes the probability that the deferred command will be executed on time.

•	Returns an HRESULT value.

pConfidence

The confidence level.

Higher confidence values indicate a greater probability of timely execution. For example, a command queued at a presentation time that has already passed will return a value of 0. A value of 100 would indicate, with absolute certainty, that the command can be executed on time.

This member function implements the IDeferredCommand::Confidence method.


CDeferredCommand::GetFlags

short GetFlags();

Returns the context flags associated with the deferred command.

•	The value retrieved will be one of the following values.

Value 	Description

DISPATCH_METHOD 	Run the member as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag may 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

HRESULT GetHResult(HRESULT* phrResult)

Returns the HRESULT value from the invoked command.

•	Returns an HRESULT value.

phrResult

The HRESULT value.

This member function implements the IDeferredCommand::GetHResult method.


CDeferredCommand::GetIID

REFIID GetIID();

Returns the interface identifier (IID) of the interface on which the method will be run.


CDeferredCommand::GetMethod

long GetMethod();

Returns the dispatch identifier of the method to be run.


CDeferredCommand::GetParams

DISPPARAMS* GetParams();

Returns the DISPPARAMS argument list to the method.


CDeferredCommand::GetResult

VARIANT* GetResult();

Returns the resulting argument list, if one exists.


CDeferredCommand::GetTime

CRefTime GetTime();

Returns the time at which the method will be run.

•	Returns a CRefTime object containing a reference time.


CDeferredCommand::Invoke

HRESULT Invoke();

Provides access to methods and properties exposed by an object.

•	Returns an HRESULT value.


CDeferredCommand::IsStreamTime

BOOL IsStreamTime();

Specifies whether the command is to be run at stream time or presentation time.

•	Returns TRUE if set to stream time; otherwise, returns FALSE.


CDeferredCommand::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void **ppv);

Returns a specified reference-counted interface.

•	Returns pointers to the IDeferredCommand and IUnknown interfaces by default.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this method to publish any additional interfaces implemented by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CDeferredCommand::Postpone

HRESULT Postpone(REFTIME newtime);

Specifies a new presentation time for a previously queued command.

•	Returns an HRESULT value.

newtime

The new presentation time.

This member function implements the IDeferredCommand::Postpone method.


CDisp Class

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:

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 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 a LPCTSTR for use in a debugging string.


CDisp::CDisp

CDisp(LONGLONG ll, int Format = CDISP_HEX);

CDisp(REFCLSID clsid);

CDisp(double d);

CDisp(CRefTime t);

CDisp(IPin *pPin);

Constructs a CDisp object.

ll

LONGLONG value for display.

Format

Should the value be displayed in decimal (CDISP_DEC) or (by default) hexadecimal (CDISP_HEX).

clsid

Class identifier to display.

d

Double value to display.

t

Reference time to display. Note that passing a REFERENCE_TIME will use the LONGLONG constructor.

pPin

IPin interface to display as FilterName(Pin name).

Various constructors are provided, which allows information to be displayed in the most suitable way.


CDisp::LPCTSTR

operator LPCTSTR();

Casts the CDisp object to an LPCTSTR for use in a debug string.

•	Returns the string representation of the variable used in the constructor.


CDispParams Class

The CDispParams class implements the DISPPARAMS structure used in OLE 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(UINT nArgs, VARIANT* pArgs);

Constructs a CDispParams object.

nArgs

The number of arguments passed to the method or property.

pArgs

A pointer to the list of arguments. In the list, each argument is stored with its variant type.


CDrawImage Class

This 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 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 DIBSECTIONs.

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_perfidRenderNow 	The 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_PaletteVersion 	Current palette version token.

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 as to 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 	Returns 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.

UsingImageAllocator 	Retrieves the type of samples to be drawn.


CDrawImage::CDrawImage

CDrawImage(CBaseWindow *pBaseWindow);

Constructs a CDrawImage object.

pBaseWindow

Window where drawing will occur.

This class handles drawing of images through GDI. It works closely in conjunction with the CImageAllocator and CBaseWindow classes. It needs to 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) via 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 may 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. 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.


CDrawImage::DisplaySampleTimes

void DisplaySampleTimes(IMediaSample *pSample);

Displays time stamps of a sample on top of the image.

pSample

Sample containing time stamps.

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

BOOL DrawImage(IMediaSample *pMediaSample);

Entry point for drawing an image.

pMediaSample

Sample to draw.

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

void FastRender(IMediaSample *pMediaSample);

Draws the sample image using the Microsoft Win32 BitBlt and StretchBlt functions.

pMediaSample

Sample to draw.

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

LONG GetPaletteVersion();

Retrieves the current palette version.

•	Returns the palette version.

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

void GetSourceRect(RECT *pSourceRect);

Retrieves the current source rectangle the draw object is using.

pSourceRect

Holds the source rectangle.


CDrawImage::GetTargetRect

void GetTargetRect(RECT *pTargetRect);

Retrieves the current destination rectangle the draw object is using.

pTargetRect

Holds the target rectangle.


CDrawImage::IncrementPaletteVersion

void IncrementPaletteVersion();

Increments the current palette version.

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

void NotifyAllocator(BOOL bUsingImageAllocator);

Notifies the draw object as to which allocator the output pin is actually going to use.

bUsingImageAllocator

Flag to indicate whether to use a CImageAllocator object allocator or not.

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 ActiveMovie™ 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 StretchDIBitsToDevice.


CDrawImage::NotifyEndDraw

void NotifyEndDraw(void);

Indicates the conclusion of image rendering.

This member function is used for performance measurements and just calls the MSR_STOP macro.


CDrawImage::NotifyMediaType

void NotifyMediaType(CMediaType *pMediaType);

Provides the image format for the draw object.

pMediaType

Media type.

The draw object needs to 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 normally call this just after completing a connection.


CDrawImage::NotifyStartDraw

void NotifyStartDraw(void);

Indicates the beginning of image rendering.

This member function is used for performance measurements and just calls the MSR_START macro.


CDrawImage::ResetPaletteVersion

void ResetPaletteVersion();

Resets the current palette version.

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

virtual RECT ScaleSourceRect(const RECT *pSource);

Returns a scaled version of a provided source rectangle.

•	Returns the scaled source rectangle (returns unscaled pSource by default).

pSource

Unscaled source rectangle.

The base class implementation does not scale the source rectangle. Derived classes may override this to implement scaling if required.


CDrawImage::SetDrawContext

void SetDrawContext();

Sets the device contexts used for drawing.

The draw object always needs a device context for the window to draw images in. It may 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 Win32 SDK documentation). This member function will typically be called by a filter using this class once it has initialized a window.


CDrawImage::SetSourceRect

void SetSourceRect(RECT *pSourceRect);

Sets the source rectangle for the video.

pSourceRect

New source rectangle.

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

void SetStretchMode();

Decides whether the video is to be stretched.

When the object is asked to draw an image, the object needs to 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 whenever 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

void SetTargetRect(RECT *pTargetRect);

Sets the target rectangle for the video.

pTargetRect

New target area.

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

void SlowRender(IMediaSample *pMediaSample);

Draws the sample image using SetDIBitsToDevice and StretchDIBits.

pMediaSample

Sample to draw.

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

void UpdateColourTable(HDC hdc, BITMAPINFOHEADER *pbmi);

Updates the palette associated with a sample.

hdc

Device context containing the sample image.

pbmi

BITMAPINFO structure containing the new palette.

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 be different 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 version. 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

BOOL UsingImageAllocator();

Retrieves the type of samples we expect to draw.

•	Returns one of the following values.

TRUE 	Allocated through CreateDIBSection.

FALSE 	Not allocated through CreateDIBSection.

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.


CEnumMediaTypes Class

This class provides the mechanism for enumerating the preferred media types of a pin. Its constructor must be passed to an object from a class derived from CBasePin. It uses the virtual member function GetMediaType to retrieve each of the media types in turn. It also uses the pin's CBasePin::GetMediaTypeVersion member function to determine if the number or type of media types has changed.

The base pin class does not support dynamic media type changes. CBaseFilter::GetPinVersion always returns the same value, for example.

The media type enumerator must fill in a list of pointers to media type structures. The memory for those media type structures must be released by the callers when they have finished with it. However, the memory must not be allocated from any language-specific heap; otherwise, problems may occur between a filter written in C and another written in C++. For this reason, the base classes provide generic functions (not member functions of a class) to create and delete media types: CreateMediaType and DeleteMediaType. These manage memory allocation from the task allocator.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Member Functions

CEnumMediaTypes 	Constructs a CEnumMediaTypes object.

Implemented IEnumMediaTypes Methods

Clone 	Creates a duplicate CEnumMediaTypes object with the same state.

Next 	Returns the next media type after the current position.

Reset 	Sets the current position back to the beginning.

Skip 	Skips over one or more entries in the enumerator.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Passes out pointers to any interfaces added to the derived filter class.


CEnumMediaTypes::CEnumMediaTypes

CEnumMediaTypes(TCHAR *pName, CBasePin *pPin,

    HRESULT * phr, CEnumMediaTypes *pEnumMediaTypes);

Constructs a CEnumMediaTypes object.

pName

Name of the enumerator.

pPin

Pointer to the pin on which the enumeration is to be performed.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.

pEnumMediaTypes

Pointer to the instantiated CEnumMediaTypes object.

This is a standard class constructor.


CEnumMediaTypes::Clone

HRESULT Clone(IEnumMediaTypes ** ppEnum);

Returns another enumerator containing the same enumeration state as the current one.

•	Returns an HRESULT value.

ppEnum

New copy of the enumerator.

This member function implements the IEnumMediaTypes::Clone method.


CEnumMediaTypes::Next

HRESULT Next(ULONG cMediaTypes, AM_MEDIA_TYPE** ppMediaTypes,

    ULONG * pcFetched);

Retrieves the specified number of items in the enumeration sequence.

•	Returns an HRESULT value.

cMediaTypes

The number of media types to place.

ppMediaTypes

The array in which to place the next media type or types.

pcFetched

Actual count passed.

This member function implements the IEnumMediaTypes::Next method. To call this method, pass the address of a pointer to a media type. The base class implementation relies on the existence of an overridden CBasePin::GetMediaType member function in the derived class that will provide the next media type.

Free each media type acquired by calling DeleteMediaType, which will free the format block and the media type itself.


CEnumMediaTypes::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IEnumMediaTypes and IUnknown interfaces. Override this class to return other interfaces on the object in the derived class.


CEnumMediaTypes::Reset

HRESULT Reset(void);

Resets the enumerator to the beginning so that the next call to the IEnumMediaTypes::Next method will return, at a minimum, the first media type in the enumeration.

•	Returns S_OK if successful; otherwise, returns S_FALSE.

This member function implements the IEnumMediaTypes::Reset method.


CEnumMediaTypes::Skip

HRESULT Skip(ULONG cMediaTypes);

Skips a specified number of elements in the enumeration sequence.

•	Returns an HRESULT value.

cMediaTypes

The number of media type elements to skip.

This member function implements the IEnumMediaTypes::Skip method.


CEnumPins Class

This class supports the IEnumPins enumeration interface by calling CBaseFilter methods. The CBaseFilter class supports the IFilter::EnumPins method. Each time one of this interface's methods is called, it checks to see if the pins that it enumerates have changed; this is done by calling CBaseFilter::GetPinVersion and matching the version the filter is keeping with the version that it stores during construction.

If a pin enumerator becomes stale, there is no mechanism for resynchronizing it with the filter. The user must release the interface and retrieve another one.

Because the enumeration operation is likely to fail if the pin version changes (indicating that the filter might have added or removed pins), all member functions in this class check the version by calling a private member function, which calls the owning filter's CBaseFilter::GetPinVersion member function. These member functions then return VFW_E_ENUM_OUT_OF_SYNC if the version has changed. This should always work unless the filter has overridden CBaseFilter::GetPinVersion to do something unexpected.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Member Functions

CEnumPins 	Constructs a CEnumPins object.

Implemented IEnumPins Methods

Clone 	Creates a duplicate CEnumPins object with the same initial state.

Next 	Returns the next pin after the current position.

Reset 	Sets the current position back to the beginning.

Skip 	Skips over one or more entries in the enumerator.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Passes out pointers to any interfaces added to the derived filter class.


CEnumPins::CEnumPins

CEnumPins( TCHAR *pName, CBaseFilter *pFilter,

    HRESULT * phr, CEnumPins *pEnumPins);

Constructor for the CEnumPins class.

pName

Name of the enumerator.

pFilter

Pointer to the filter on which to enumerate the pins.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.

pEnumPins

Returned pointer to an IEnumPins interface object.


CEnumPins::Clone

HRESULT Clone(IEnumPins ** ppEnum);

Makes a copy of the enumerator. This allows the calling application to retain two positions in the list of pins.

•	Returns an HRESULT value.

ppEnum

New enumerator that is a copy of this enumerator.

This member function implements the IEnumPins::Clone method.


CEnumPins::Next

HRESULT Next(ULONG cPins, IPin ** ppPins,

    ULONG * pcFetched);

Places pointers to IPin interfaces into the specified array.

•	Returns an HRESULT value.

cPins

The number of pins to place.

ppPins

Array in which to place the interface pointers.

pcFetched

Actual number of pins placed in the array.

This member function implements the IEnumPins::Next method. The derived class is responsible for implementing CBaseFilter::GetPin, which this member function calls to retrieve the next pin.

Because this member function returns one or more interfaces that have had their reference counts incremented, the caller of this member function must be sure to release the interfaces by calling IUnknown::Release on the interfaces when done with them.


CEnumPins::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IEnumPins and IUnknown interfaces. Override this class to return other interfaces on the object in the derived class.


CEnumPins::Reset

HRESULT Reset(void);

Resets the enumerator to the beginning so that the next call to the IEnumPins::Next method will return, at a minimum, the first pin of the filter.

•	Returns an HRESULT value.

This member function implements the IEnumPins::Reset method.


CEnumPins::Skip

HRESULT Skip(ULONG cPins);

Skips the next specified number of pins.

•	Returns an HRESULT value.

cPins

The number of pins to skip.

This member function implements the IEnumPins::Skip method. This member function affects the next call to the IEnumPins::Next method.


CFactoryTemplate Class

This class provides a template used by the default class factory code.

Create one CFactoryTemplate object in an array for every object class so that the default class factory code can create new instances.

This class holds the name of the object, the object's CLSID, and a pointer to the creation function for the corresponding object. Initialize one of these in an array called g_Templates for each CLSID the application's dynamic-link library (DLL) supports. The creation function should take an LPUNKNOWN parameter and an HRESULT pointer and return an object derived from the CBaseObject class. Set the HRESULT to a failed value if there is any error in construction. An example declaration (from the Gargle sample filter) is shown below:

// list of class ids and creator functions for class factory

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]);

Note that the name of the object is strictly necessary only if you are using the DllRegisterServer setup routine as implemented by the IAMovieSetup interface to implement self-registering of your filter. If you are not using this feature, you can set the first element of the g_Templates instance (m_Name) to NULL or L"".

Protected Data Members

m_ClsID 	Pointer to the class identifier (CLSID) of the object class.

m_lpfnNew 	Pointer to a function that creates an instance of the object class.

m_lpfnInit 	Pointer to a function that initializes a new instance of the object class.

m_Name 	Name of the filter; required when using filter self-registration services.

Member Functions

CreateInstance 	Calls the object-creation function for the class.

IsClassID 	Determines whether a CLSID matches this class template.


CFactoryTemplate::CreateInstance

CUnknown *CreateInstance(LPUNKNOWN pUnk, HRESULT *phr);

Calls the object creation function for the class.

•	Returns an instance of the class object.

pUnk

Pointer to the IUnknown interface.

phr

Pointer to the HRESULT value into which to place resulting information.

The implementer of the class code registered using this factory template class is responsible for providing the code that creates an instance of the class object and assigning it to the m_lpfnNew data member. This member function simply calls that function and returns a new object of that type.


CFactoryTemplate::IsClassID

BOOL IsClassID(REFCLSID rclsid);

Determines if the class identifier (CLSID) passed matches the CLSID assigned to this class template.

•	Returns TRUE if the CLSIDs are the same; otherwise, returns FALSE.

rclsid

CLSID being tested.


CGenericList Class

CGenericList is a template class that allows for a type-specific implementation of a list. It is derived from CBaseList and uses that class's typeless implementation. The constructor creates a CBaseList object, and all CGenericList member functions call CBaseList member functions but provide type-checking dependent on the template.

Member Functions

AddAfter 	Inserts a node or list of nodes after the specified node.

AddBefore 	Inserts a node or list of nodes before the specified node.

AddHead 	Inserts a node or list of nodes at the front of the list.

AddTail 	Appends a node or list of nodes to the end of the list.

CGenericList 	Constructs a CGenericList object.

Find 	Returns the first position that contains the specified object.

Get 	Returns the object at the specified position.

GetNext 	Returns the specified object and update position.

Remove 	Removes the specified node from the list.

RemoveHead 	Removes the first node in the list.

RemoveTail 	Removes the last node in the list.


CGenericList::AddAfter

POSITION AddAfter(POSITION p, OBJECT * pObj);

BOOL AddAfter(POSITION pos, CGenericList<OBJECT> *pList);

Inserts a node or list of nodes after the specified node.

•	Returns the position of the inserted object in the case of single-object insertion. For list insertion, returns TRUE if successful; otherwise, returns FALSE.

pos

Position after which to add the node or list of nodes.

pObj

Pointer to the object to add.

pList

Pointer to the list of objects to add.

This member function calls the CBaseList::AddAfter member function when passed a list of nodes. CGenericList::AddAfter calls the CBaseList::AddAfterI member function when passed a single node.


CGenericList::AddBefore

POSITION AddBefore(POSITION p, OBJECT * pObj);

BOOL AddBefore(POSITION pos, CGenericList<OBJECT> *pList);

Inserts a node or list of nodes before the specified node.

•	Returns the position of the inserted object in the case of single-object insertion. For list insertion, returns TRUE if successful; otherwise, returns FALSE.

pos

Position before which to add the node or list of nodes.

pObj

Pointer to the object to add.

pList

Pointer to the list of objects to add.

This member function calls the CBaseList::AddBefore member function when passed a list of nodes. CGenericList::AddBefore calls the CBaseList::AddBeforeI member function when passed a single node.


CGenericList::AddHead

POSITION AddHead(OBJECT * pObj);

BOOL AddHead(CGenericList<OBJECT> *pList);

Inserts a node or list of nodes at the front of the list.

•	Returns the new head position, or NULL if unsuccessful in the case of single-node additions. For list insertions, returns TRUE if successful; otherwise, returns FALSE.

pObj

Pointer to the object to add.

pList

Pointer to the list of objects to add.

This member function calls the CBaseList::AddHead member function when passed a list of nodes. CGenericList::AddHead calls the CBaseList::AddHeadI member function when passed a single node.


CGenericList::AddTail

POSITION AddTail(OBJECT * pObj);

BOOL AddTail(CGenericList<OBJECT> *pList);

Appends a node or list of nodes to the end of the list.

•	Returns the new tail position, or NULL if unsuccessful in the case of single-node insertions. For list insertions, returns TRUE if successful; otherwise, returns FALSE.

pObj

Pointer to the object to add.

pList

Pointer to the list of objects to add.

This member function calls the CBaseList::AddTail member function when passed a list of nodes. CGenericList::AddTail calls the CBaseList::AddTailI member function when passed a single node.


CGenericList::CGenericList

CGenericList(TCHAR *pName, INT iItems = DEFAULTCACHE);

Constructs a CGenericList object.

pName

Name of the list.

iItems

Number of items in the list.

This constructor calls the CBaseList constructor.


CGenericList::Find

POSITION Find(OBJECT * pObj);

Returns the first position that contains the specified object.

•	Returns a position cursor.

pObj

Pointer to the object to find.

This member function calls the CBaseList::FindI member function.


CGenericList::Get

OBJECT *Get(POSITION pos);

Returns the object at the specified position.

•	Returns a pointer to an object.

pos

Position in the list from which to retrieve the object.

This member function calls the CBaseList::GetI member function.


CGenericList::GetNext

OBJECT *GetNext(POSITION& rp);

Returns the specified object and update position.

•	Returns a pointer to an object at the next position.

rp

Returned pointer to the next object.

This member function calls the CBaseList::GetNextI member function.


CGenericList::Remove

OBJECT *Remove(POSITION pos);

Removes the specified node from the list.

•	Returns the pointer to the object that was removed.

pos

Position in the list of nodes to remove.

This member function calls the CBaseList::RemoveI member function.


CGenericList::RemoveHead

OBJECT *RemoveHead();

Removes the first node in the list.

•	Returns the pointer to the object that was removed.

This member function calls the CBaseList::RemoveHeadI member function.


CGenericList::RemoveTail

OBJECT *RemoveTail();

Removes the last node in the list.

•	Returns the pointer to the object that was removed.

This member function calls the CBaseList::RemoveTailI member function.


CGuidNameList Class

This class implements an array of globally unique identifier (GUID) names based on the predefined names of GUIDs that come with Microsoft® ActiveMovie™. (This may or may not include any user-defined GUIDs.) To get the name used for a GUID, just look it up in the GuidNames array:

int MyFunc(AM_MEDIA_TYPE mt)

{

    DbgLog((LOG_TRACE, 2, TEXT("MyFunc: Type %s, Subtype %s"),

        GuidNames[mt.majortype],

        GuidNames[mt.subtype]

        ));

...

}

Operators

operator[ ] 	Returns the GUID name for the given entry in a GUID name list.

Global Data

GuidNames 	Array of CGuidNameList objects describing the predefined names of GUIDs that come with ActiveMovie. (This may or may not include any user-defined GUIDs.)


CGuidNameList::operator[]

TCHAR *operator[](const GUID& guid);

Allows access to the GUID name for a given GUID.

•	Returns the GUID name for the given entry in a GUID name list.

guid

Globally unique identifier.


CImageAllocator Class

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

HRESULT Alloc();

Creates image samples based around CreateDIBSection.

•	Returns an HRESULT value.

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

HRESULT CheckSizes(ALLOCATOR_PROPERTIES *pRequest);

Internal member function that checks the required buffering properties.

•	Returns an HRESULT value.

pRequest

Requested allocator properties.

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(CBaseFilter *pFilter, TCHAR *pName,

    HRESULT *phr);

Constructs a CImageAllocator object.

pFilter

Owning filter object.

pName

Debug-only string description.

phr

OLE return code.

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

HRESULT CreateDIB(LONG InSize, DIBDATA &DibData);

Calls the Win32 CreateDIBSection function to create a device-independent bitmap (DIB).

•	Returns an HRESULT value.

InSize

Size of the bitmap required.

DibData

Structure to fill out with details.

This is a protected member function.


CImageAllocator::CreateImageSample

virtual CImageSample *CreateImageSample(LPBYTE pData,

    LONG Length);

Creates a CImageSample object.

•	Returns a new CImageSample sample object.

pData

Pointer to the data buffer the sample looks after.

Length

Associated length of the buffer.

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

void Free();

Deletes the samples and frees their resources.

The base allocator calls this internal virtual member function when it wants to decommit the allocator.

This is a protected member function.


CImageAllocator::NonDelegatingAddRef

HRESULT NonDelegatingAddRef();

Increments the reference count for the owning filter.

•	Returns an HRESULT value.

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

HRESULT NonDelegatingRelease();

Decrements the reference count for the owning filter.

•	Returns an HRESULT value.

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

void NotifyMediaType(CMediaType *pMediaType);

Passes the media type from a filter to the allocator.

pMediaType

Media type the filter established.

The buffers the image allocator creates are based around CreateDIBSection, which needs to 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 normally 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

HRESULT SetProperties(ALLOCATOR_PROPERTIES * pRequest,

    ALLOCATOR_PROPERTIES * pActual);

Determines the size, number, and alignment of blocks.

•	Returns an HRESULT value.

pRequest

Requested allocator properties.

pActual

Allocator properties actually set.

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

This 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 only accept 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 bit masks 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

BOOL CheckBitFields(const VIDEOINFO *pInput);

Checks that the bit fields in the VIDEOINFO structure are correct.

•	Returns one of the following values.

TRUE 	Bit fields are correct.

FALSE 	Bit fields contain an error.

pInput

VIDEOINFO structure to check.

The assumption throughout the object is that any bit masks are allowed no more than eight bits to store a color component. This member function checks that the bit count assumption is enforced and also makes sure that all the bits set are contiguous.

This is a protected member function.


CImageDisplay::CheckHeaderValidity

BOOL CheckHeaderValidity(const VIDEOINFO *pInput);

Determines if a BITMAPINFOHEADER structure is valid.

•	Returns one of the following values.

TRUE 	Format is valid.

FALSE 	Format contains an error.

pInput

VIDEOINFO structure that contains the bitmap details.

The BITMAPINFOHEADER structure may 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

HRESULT CheckMediaType(const CMediaType *pmtIn);

Determines if the filter can support the media type proposed by the output pin.

•	Returns an HRESULT value.

pmtIn

Media type to check.

This helper member function can be used to validate a video media type. It examines the major and minor type GUIDs and verifies that the format GUID defines a VIDEOINFO structure.


CImageDisplay::CheckPaletteHeader

BOOL CheckPaletteHeader(const VIDEOINFO *pInput);

Determines if the palette on a VIDEOINFO structure is correct.

•	Returns one of the following values.

TRUE 	Palette is correct.

FALSE 	No valid palette.

pInput

VIDEOINFO structure to validate.

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

HRESULT CheckVideoType(const VIDEOINFO *pInput);

Compares a video type to determine if it is compatible with the current display mode.

•	Returns an HRESULT value.

pInput

VIDEOINFO structure to validate.

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();

Constructs a CImageDisplay object.

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

DWORD CountPrefixBits(const DWORD Field);

Helper member function to count the number of prefix bits.

Field

Input bit mask field.

Given a bit mask, this 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 DWORDs, 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

DWORD CountSetBits(const DWORD Field);

Counts the number of bit sets in the Field parameter.

•	Returns the number of bit sets.

Field

Field in which to count bit sets.

This is a protected member function.


CImageDisplay::GetBitMasks

const DWORD *GetBitMasks(const VIDEOINFO *pVideoInfo);

Retrieves a set of color element bit masks for the supplied VIDEOINFO structure.

pVideoInfo

Input VIDEOINFO structure format.

This member function should only be called with RGB formats. If the RGB format has a bit depth of 16/32 bits per pixel, it will return the bit masks 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

BOOL GetColourMask(DWORD *pMaskRed,

    DWORD *pMaskGreen, DWORD *pMaskBlue);

Retrieves a set of individual color element masks.

•	Returns one of the following values.

TRUE 	Masks were filled out correctly.

FALSE 	No masks were available for the display.

pMaskRed

Holds red mask.

pMaskGreen

Holds green mask.

pMaskBlue

Holds blue mask.

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

WORD GetDisplayDepth();

Retrieves the bit depth of the current display mode.

•	Returns the number of bits per pixel used on the display.


CImageDisplay::GetDisplayFormat

const VIDEOINFO *GetDisplayFormat();

Retrieves a VIDEOINFO structure representing the current display mode.

•	Returns a VIDEOINFO structure representing the display format.


CImageDisplay::IsPalettized

BOOL IsPalettized();

Determines if the display uses a palette.

•	Returns TRUE if the display uses a palette; otherwise, returns FALSE.


CImageDisplay::RefreshDisplayType

HRESULT RefreshDisplayType();

Updates the CImageDisplay object with the current display type.

•	Returns an HRESULT value.

This member function should be called when a WM_DISPLAYCHANGED message is received.


CImageDisplay::UpdateFormat

HRESULT UpdateFormat(VIDEOINFO *pVideoInfo);

Updates the VIDEOINFO structure to remove implicit assumptions.

•	Returns an HRESULT value.

pVideoInfo

VIDEOINFO structure to update.

This member function is probably only suitable for specific filters to use. The BITMAPINFO structure has certain fields that are not well specified. This member function updates the fields to make them explicit. In particular, the number of colors specified for a palette may 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 have to 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 only changed 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 VIDEOINFO structure into a palettized VIDEOINFO structure.

MakeIdentityPalette 	Ensures the palette entries will become an identity palette.

MakePalette 	Creates a palette based on a VIDEOINFO structure.

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(CBaseFilter *pBaseFilter,

    CBaseWindow *pBaseWindow, CDrawImage *pDrawImage);

Constructs a CImagePalette object.

pBaseFilter

Filter that this class is owned by.

pBaseWindow

Window to realize palette in.

pDrawImage

Object that draws using this palette.

This class looks after the creation, management, and deletion of a window palette. It is passed in a number of other objects that may be interested in palettes. The class is optimized so that requested palette changes will only be acted on 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 may 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 may 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 normally 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 may need their internal color tables updated).


CImagePalette::CopyPalette

HRESULT CopyPalette(const CMediaType *pSrc,

    const CMediaType *pDest);

Copies the palette out of any YUV or true color VIDEOINFO structure into a palettized VIDEOINFO structure.

•	Returns an HRESULT value.

pSrc

Source media type.

pDest

Destination media type.

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 VIDEOINFO 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

HRESULT MakeIdentityPalette(PALETTEENTRY *pEntry,

    INT iColours);

Modifies the PALETTEENTRY structure to create an identity palette.

•	Returns an HRESULT value.

pEntry

Array of prospective palette colors.

iColours

Number of colors in the array.

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

HPALETTE MakePalette(const VIDEOINFO *pVideoInfo);

Creates a palette from a provided VIDEOINFO structure.

•	Returns a handle to the new palette (NULL if it fails).

pVideoInfo

Container for the palette colors required.


CImagePalette::PreparePalette

HRESULT PreparePalette(const CMediaType *pmtNew,

    const CMediaType *pmtOld);

Specifies an entry point for creating and installing palettes.

•	Returns an HRESULT value.

pmtNew

Media type holding new palette information.

pmtOld

Media type holding old palette information.

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 looks after 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 looks after notifying the draw object of palette changes (also optional, depending on whether a draw object was passed in to the constructor).


CImagePalette::RemovePalette

HRESULT RemovePalette();

Removes and deletes any palette previously created.

•	Returns an HRESULT value.


CImagePalette::ShouldUpdate

BOOL ShouldUpdate(const VIDEOINFO *pNewInfo,

    const VIDEOINFO *pOldInfo);

Help member function that checks if two sets of colors match.

•	Returns one of the following values.

TRUE 	A new palette is required.

FALSE 	The existing palette suffices.

pNewInfo

VIDEOINFO containing the new set of colors.

pOldInfo

VIDEOINFO containing the old set of colors.


CImageSample Class

This 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 in order 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 information stored for the sample.

SetDIBData 	Sets the DIBSECTION information stored for the sample.


CImageSample::CImageSample

CImageSample(CBaseAllocator *pAllocator, TCHAR *pName,

    HRESULT *phr, LPBYTE pBuffer, LONG length);

Constructs a CImageSample object.

pAllocator

Base allocator to which the sample belongs.

pName

Debug-only string description.

phr

OLE return code.

pBuffer

Pointer to the image buffer.

length

Length of the image buffer.

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 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 achieves a modest performance improvement.


CImageSample::GetDIBData

DIBDATA *GetDIBData();

Retrieves the DIBDATA structure held by the sample.


CImageSample::SetDIBData

void SetDIBData(DIBDATA *pDibData);

Sets the DIBDATA structure that the sample should hold.

pDibData

New DIBDATA structure.


CLoadDirectDraw Class

ActiveMovie™ 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.

GetDirectDrawVersion 	Retrieves the version of DirectDraw found on the system.

IsDirectDrawLoaded 	Verifies that DirectDraw is loaded.

LoadDirectDraw 	Loads and initializes the DirectDraw library.

ReleaseDirectDraw 	Releases the IDirectDraw interface.


CLoadDirectDraw::CLoadDirectDraw

CLoadDirectDraw(void);

Constructs a CLoadDirectDraw object.


CLoadDirectDraw::GetDirectDraw

LPDIRECTDRAW GetDirectDraw(void);

Retrieves the IDirectDraw interface.

•	Pointer to the IDirectDraw interface.

Call CLoadDirectDraw::LoadLibrary before calling this member function, and call the CLoadDirectDraw::Release member function to release the interface when you are done.


CLoadDirectDraw::GetDirectDrawVersion

DWORD GetDirectDrawVersion(void);

Retrieves the version of DirectDraw found on the system.

•	Returns the version number.

The video renderer needs to know what version of DirectDraw is available to know what capabilities it supports. For example, there are specific enhancements in DirectDraw version 2.0 that enable full-screen rendering. This member function loads the DDRAW.DLL file version data and extracts the product version rather than the more expensive operation of loading the library and creating a DirectDraw instance.


CLoadDirectDraw::IsDirectDrawLoaded

HRESULT IsDirectDrawLoaded(void);

Verifies that DirectDraw has been loaded by this object.

•	Returns S_OK if loaded; otherwise, returns S_FALSE.


CLoadDirectDraw::LoadDirectDraw

HRESULT LoadDirectDraw(void);

Loads and initializes the DirectDraw library.

•	Returns S_OK if DirectDraw is loaded correctly; otherwise, returns E_NOINTERFACE.

DirectDraw is not always available, so applications cannot 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

void ReleaseDirectDraw(void);

Releases the IDirectDraw interface.

This member function is called to release any IDirectDraw interface previously loaded. This should be called only when all reference counts have been released.


CMediaControl Class

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 IFilter, to receive control commands from the filter graph manager.) Therefore, this class library is of limited use to developers of filters.

The CMediaControl::GetTypeInfoCount, CMediaControl::GetTypeInfo, CMediaControl::GetIDsOfNames, 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(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT *phr);

Constructs a CMediaControl object.

pName

Name of the object for debugging purposes.

pUnk

Pointer to the owner of this object.

phr

Pointer to an HRESULT value containing resulting information.

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.


CMediaControl::GetIDsOfNames

HRESULT GetIDsOfNames(REFIID riid,

    OLECHAR ** rgszNames, UINT cNames,

    LCID lcid, DISPID * rgdispid);

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 CMediaControl::Invoke member function.

•	Returns one of the following values.

Value 	Meaning

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.

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

The locale context in which to interpret the names.

rgdispid

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.


CMediaControl::GetTypeInfo

HRESULT GetTypeInfo(UINT itinfo, LCID lcid,

    ITypeInfo ** pptinfo);

Retrieves a type-information object, which can retrieve the type information for an interface.

•	Returns an HRESULT value.

itinfo

The type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

The locale ID for the type information. An object may 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

A pointer to the type-information object requested.


CMediaControl::GetTypeInfoCount

HRESULT GetTypeInfoCount(UINT * pctinfo);

Retrieves the number of type-information interfaces provided by an object.

•	Returns an HRESULT value.

pctinfo

Points 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.


CMediaControl::Invoke

HRESULT Invoke(DISPID dispidMember, REFIID riid,

    LCID lcid, WORD wFlags, DISPPARAMS * pdispparams,

    VARIANT * pvarResult, EXCEPINFO * pexcepinfo,

    UINT * puArgErr);

Provides access to properties and methods exposed by an object.

•	Returns an HRESULT value.

dispidMember

Identifies 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

The 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

The index of the first argument, within the rgvarg array, that has an error.


CMediaControl::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void **ppv);

Returns a specified reference-counted interface.

•	Returns pointers to the IMediaControl and IUnknown interfaces by default.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this member function to publish any additional interfaces implemented by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CMediaEvent Class

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::GetTypeInfoCount, CMediaEvent::GetTypeInfo, CMediaEvent::GetIDsOfNames, 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(TCHAR * pName, LPUNKNOWN pUnk, HRESULT * phr);

Constructs a CMediaEvent object.

pName

Name of the object for debugging purposes.

pUnk

Pointer to the owner of this object.

phr

Pointer to an HRESULT value for resulting information.

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.


CMediaEvent::GetIDsOfNames

HRESULT GetIDsOfNames(REFIID riid, OLECHAR  ** rgszNames,

    UINT cNames, LCID lcid, DISPID * rgdispid);

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.

•	Returns one of the following values.

Value 	Meaning

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.

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

The locale context in which to interpret the names.

rgdispid

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.


CMediaEvent::GetTypeInfo

HRESULT GetTypeInfo(UINT itinfo, LCID lcid,

    ITypeInfo ** pptinfo);

Retrieves a type-information object, which can retrieve the type information for an interface.

•	Returns an HRESULT value.

itinfo

The type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

The locale ID for the type information. An object may 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

A pointer to the type-information object requested.


CMediaEvent::GetTypeInfoCount

HRESULT GetTypeInfoCount(UINT * pctinfo);

Retrieves the number of type-information interfaces provided by an object.

•	Returns an HRESULT value.

pctinfo

Points 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.


CMediaEvent::Invoke

HRESULT Invoke(DISPID dispidMember, REFIID riid,

    LCID lcid, WORD wFlags, DISPPARAMS * pdispparams,

    VARIANT * pvarResult, EXCEPINFO * pexcepinfo,

    UINT * puArgErr);

Provides access to properties and methods exposed by an object.

•	Returns an HRESULT value.

dispidMember

Identifies 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

The 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

The index of the first argument, within the rgvarg array, that has an error.


CMediaEvent::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void **ppv);

Returns a specified reference-counted interface.

•	Returns a pointer to the IMediaEvent and IUnknown interfaces by default.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this member function to publish any additional interfaces added by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CMediaPosition Class

The CMediaPosition class is a base class that handles the IDispatch methods of the dual-interface IMediaPosition. It leaves the properties and methods as pure virtual.

The CMediaPosition::GetTypeInfoCount, CMediaPosition::GetTypeInfo, CMediaPosition::GetIDsOfNames, and CMediaPosition::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 IMediaPosition methods.

Member Functions

CMediaPosition 	Constructs a CMediaPosition 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 CMediaPosition::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.


CMediaPosition::CMediaPosition

CMediaPosition(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT *phr);

Constructs a CMediaPosition object.

pName

Name of the object used in the CMediaPosition constructor for debugging purposes.

pUnk

Pointer to the owner of this object.

phr

Pointer to an HRESULT value for resulting information.

Allocate the pName parameter in static memory. This name appears on the debug terminal upon creation and deletion of the object.


CMediaPosition::GetIDsOfNames

HRESULT GetIDsOfNames(REFIID riid,

    OLECHAR ** rgszNames, UINT cNames,

    LCID lcid, DISPID * rgdispid);

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 CMediaPosition::Invoke member function.

•	Returns one of the following values.

Value 	Meaning

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.

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

The locale context in which to interpret the names.

rgdispid

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.


CMediaPosition::GetTypeInfo

HRESULT GetTypeInfo(UINT itinfo, LCID lcid,

    ITypeInfo ** pptinfo);

Retrieves a type-information object, which can retrieve the type information for an interface.

•	Returns an HRESULT value.

itinfo

The type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

The locale ID for the type information. An object may 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

A pointer to the type-information object requested.


CMediaPosition::GetTypeInfoCount

HRESULT GetTypeInfoCount(UINT * pctinfo);

Retrieves the number of type-information interfaces provided by an object.

•	Returns an HRESULT value.

pctinfo

Points 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.


CMediaPosition::Invoke

HRESULT Invoke(DISPID dispidMember, REFIID riid,

    LCID lcid, WORD wFlags, DISPPARAMS * pdispparams,

    VARIANT * pvarResult, EXCEPINFO * pexcepinfo,

    UINT * puArgErr);

Provides access to properties and methods exposed by an object.

•	Returns an HRESULT value.

dispidMember

Identifies the member. Use CMediaPosition::GetIDsOfNames or the object's documentation to obtain the dispatch identifier.

riid

Reserved for future use. Must be IID_NULL.

lcid

The locale context in which to interpret arguments.

wFlags

Flags describing the context of the CMediaPosition::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

The index of the first argument, within the rgvarg array, that has an error.


CMediaPosition::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void **ppv);

Returns a specified reference-counted interface.

•	Returns a pointer to IMediaPosition and IUnknown interfaces by default.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this member function to publish any additional interfaces implemented by the derived class.


CMediaSample Class

This class represents a buffer object that is derived from CUnknown, supports the IMediaSample interface, and works with memory allocators derived from CBaseAllocator. It represents a buffer in memory, together with some associated properties stored as protected data members.

The constructor is passed as a pointer to the buffer with its length in bytes; other properties are normally set and accessed through implemented IMediaSample interface methods. These properties describe various attributes of the media sample, such as the sample's media type, start and end time, and options. The options can include whether the media sample is a sync point, a preroll sample, or discontinuous with other samples.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Protected Data Members

m_cbBuffer 	Size of the buffer.

m_dwFlags 	Sample property flags as follows:

Sample_SyncPoint: Set if sample is a synchronization point.

Sample_Preroll: Set if sample is a preroll sample.

Sample_Discontinuity: Set if start of a new segment.

Sample_TypeChanged: Set if the type has changed.

Sample_TimeValid: Set if the time is valid.

Sample_MediaTimeValid: Set if the media time is valid.

m_lActual 	Actual length of data in this sample.

m_pAllocator 	Pointer to the IMemAllocator object associated with this object.

m_pMediaType 	Pointer to a structure containing the media type of the sample.

m_pNext 	Pointer to the next CMediaSample object in the free list.

m_pBuffer 	Pointer to the complete buffer.

m_End 	Sample end time.

m_Start 	Sample start time.

m_MediaStart 	Media start position.

m_MediaEnd 	Media end (offset from m_MediaStart).

Member Functions

CMediaSample 	Constructs a CMediaSample object.

SetPointer 	Sets the buffer pointer and length.

Implemented IMediaSample Methods

GetActualDataLength 	Retrieves the data length of the sample.

GetMediaTime 	Retrieves the media time extents of the sample.

GetMediaType 	Retrieves the media type of the CMediaSample object.

GetPointer 	Retrieves a read/write pointer to the memory of this buffer.

GetSize 	Returns the size, in bytes, of the buffer data area.

GetTime 	Sets the media time extents for this sample.

IsDiscontinuity 	Determines if there is discontinuity in the data stream.

IsPreroll 	Indicates a preroll property. If TRUE, this sample is for preroll only and should not be displayed.

IsSyncPoint 	Determines if the beginning of a sample is a synchronization point.

SetActualDataLength 	Sets the data length of the sample.

SetDiscontinuity 	Sets the discontinuity property.

SetMediaTime 	Sets the media time of the CMediaSample object.

SetMediaType 	Sets the media type of the CMediaSample object.

SetPreroll 	Sets preroll property. If TRUE, this sample is for preroll only and should not be displayed.

SetSyncPoint 	Sets sync-point property.

SetTime 	Sets the stream time at which this sample should start and finish.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Passes out pointers to any interfaces added to the derived filter class.


CMediaSample::CMediaSample

CMediaSample(TCHAR *pName, CBaseAllocator *pAllocator,

    HRESULT *phr, LPBYTE pBuffer = NULL, LONG length = 0);

Constructs a CMediaSample object.

pName

Name of the media sample.

pAllocator

Pointer to the CBaseAllocator object used for memory allocation.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.

pBuffer

Pointer to a memory buffer (to be allocated by the pAllocator parameter).

length

Length of the allocated memory buffer.

The constructor creates an object with the buffer and buffer length set to that of the CBaseAllocator object to which it points.


CMediaSample::GetActualDataLength

HRESULT GetActualDataLength(void);

Retrieves the data length of the sample.

•	Returns the value of m_lActual by default.

This member function implements the IMediaSample::GetActualDataLength method.


CMediaSample::GetMediaTime

HRESULT GetMediaTime(LONGLONG * pStart,

    LONGLONG * pEnd);

Retrieves the starting and ending media time.

•	Returns an HRESULT value.

pStart

Retrieved beginning media time.

pEnd

Retrieved ending media time.

This member function implements the IMediaSample::GetMediaTime method. It sets pStart to the current value of m_MediaStart and pEnd to the sum of m_MediaStart and m_MediaEnd. If the sample has not been set, this member function returns VFW_E_MEDIA_TIME_NOT_SET.


CMediaSample::GetMediaType

HRESULT GetMediaType(AM_MEDIA_TYPE ** ppMediaType);

Retrieves the media type of the CMediaSample object.

•	Returns an HRESULT value. When a sample is received and there is no format change, this method returns S_FALSE.

ppMediaType

Pointer to a pointer to the retrieved media type.

This member function implements the IMediaSample::GetMediaType method. The member function makes a copy of the AM_MEDIA_TYPE structure and creates a task memory block to maintain the reference. When you are done with the media type, free the memory block with the FreeMediaType utility function, and then free the entire media type with the Microsoft Win32 CoTaskMemFree function.


CMediaSample::GetPointer

HRESULT GetPointer(BYTE ** ppBuffer);

Retrieves a read/write pointer to the buffer's memory.

•	Returns VFW_E_BUFFER_NOTSET if CMediaSample::SetPointer was not called before calling this function; otherwise, returns NOERROR.

ppBuffer

Retrieved pointer to the buffer.

This member function implements the IMediaSample::GetPointer method. GetPointer returns the value of m_pBuffer, set using CMediaSample::SetPointer.


CMediaSample::GetSize

HRESULT GetSize(void);

Returns the size, in bytes, of the buffer data area.

•	Returns the value of m_cbBuffer by default.

This member function implements the IMediaSample::GetSize method.


CMediaSample::GetTime

HRESULT GetTime(REFERENCE_TIME * pTimeStart,

    REFERENCE_TIME * pTimeEnd);

Retrieves the stream time at which this sample should begin and finish.

•	Returns an HRESULT value.

pTimeStart

Retrieved beginning stream time.

pTimeEnd

Retrieved ending stream time.

This member function implements the IMediaSample::GetTime method. It sets pTimeStart to the current value of m_Start and pTimeEnd to the current value of m_End. If the sample has not been set, this member function returns VFW_E_SAMPLE_TIME_NOT_SET.


CMediaSample::IsDiscontinuity

HRESULT IsDiscontinuity(void);

Determines if there is discontinuity in the data stream.

•	Returns S_OK if the sample is a discontinuous sample and S_FALSE if not; otherwise, returns an HRESULT error value.

This member function implements the IMediaSample::IsDiscontinuity method. It returns the value of the m_dwFlags Sample_Discontinuity property flag. Discontinuity occurs when a source filter seeks to a different place in the stream or when a filter drops samples for quality control.


CMediaSample::IsPreroll

HRESULT IsPreroll(void);

Preroll property. If TRUE, this sample is for preroll only and should not be displayed.

•	Returns S_OK if the sample is a preroll sample and S_FALSE if not; otherwise, returns an HRESULT error value.

This member function implements the IMediaSample::IsPreroll method. It returns the value of the m_dwFlags Sample_Preroll property flag. Preroll samples are not meant to be rendered.


CMediaSample::IsSyncPoint

HRESULT IsSyncPoint(void);

Determines if the beginning of a sample is a synchronization point.

•	Returns S_OK if the sample is a synchronization point and S_FALSE if not; otherwise, returns an HRESULT error value.

This member function implements the IMediaSample::IsSyncPoint method. It returns the value of the m_dwFlags Sample_SyncPoint property flag. If the bTemporalCompression member of the AM_MEDIA_TYPE structure is FALSE, all samples are synchronization points. A filter can begin a stream at any synchronization point.


CMediaSample::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IMediaSample and IUnknown interfaces. Override this class to return other interfaces on the object in the derived class.


CMediaSample::SetActualDataLength

HRESULT SetActualDataLength(long lLen);

Sets the data length of the sample.

•	Returns an HRESULT value.

lLen

Length of the data in the media sample, in bytes.

This member function implements the IMediaSample::SetActualDataLength method. It sets the value of m_lActual to the value of lLen.


CMediaSample::SetDiscontinuity

HRESULT SetDiscontinuity(BOOL bDiscont);

Sets the discontinuity property.

•	Returns an HRESULT value.

bDiscont

Set to TRUE to specify the media sample as discontinuous with the previous sample.

This member function implements the IMediaSample::SetDiscontinuity method. It sets the value of the m_dwFlags Sample_Discontinuity flag to the value of bDiscont. Discontinuous samples occur when a source filter seeks to a different place in the media stream or when a filter drops samples for quality control.


CMediaSample::SetMediaTime

HRESULT SetMediaTime(LONGLONG * pStart,

    LONGLONG * pEnd);

Sets the starting and ending media time.

•	Returns an HRESULT value.

pStart

Beginning media time.

pEnd

Ending media time.

This member function implements the IMediaSample::SetMediaTime method. It sets the m_MediaStart data member to the value of pStart and the m_MediaEnd data member to the value of pEnd minus pStart.


CMediaSample::SetMediaType

HRESULT SetMediaType(AM_MEDIA_TYPE * pMediaType);

Sets the media type for the CMediaSample object.

•	Returns an HRESULT value.

pMediaType

Pointer to a pointer to a media type structure to be set.

This member function implements the IMediaSample::SetMediaType method. It deletes the previous media type if one exists, makes a copy of the media type passed in, sets m_pMediaType to the copy of the media type, and sets the value of the m_dwFlags Sample_TypeChanged flag to TRUE.


CMediaSample::SetPointer

SetPointer(BYTE * ptr, LONG cBytes);

Sets the buffer pointer and length.

ptr

Pointer to a buffer.

cBytes

Length of the buffer, in bytes.

Allocators that require variable-sized pointers or pointers into data that has already been read use this member function. This is available only through a CMediaSample class, not an IMediaSample interface, so only the filter that owns the allocator knows how to access this member function (not any filter or pin that is passed the object's IMediaSample interface pointer).


CMediaSample::SetPreroll

HRESULT SetPreroll(BOOL bIsPreroll);

Sets the preroll property. If TRUE, this sample is for preroll only and should not be displayed.

•	Returns an HRESULT value.

bIsPreroll

Set to TRUE to specify the media sample as a preroll sample, and FALSE otherwise.

This member function implements the IMediaSample::SetPreroll method. It sets the value of the m_dwFlags Sample_Preroll flag to the value of bIsPreroll. Preroll samples are samples that are processed but not displayed and are located in the media stream before the displayable samples.


CMediaSample::SetSyncPoint

HRESULT SetSyncPoint(BOOL bIsSyncPoint);

Property of a synchronization point.

•	Returns S_OK.

bIsSyncPoint

Value specifying whether the synchronization point was set.

This member function implements the IMediaSample::SetSyncPoint method. It sets the value of the m_dwFlags Sample_SyncPoint flag to the value of bIsSyncPoint. A filter can begin a stream at any synchronization point.


CMediaSample::SetTime

HRESULT SetTime(REFERENCE_TIME * pTimeStart,

    REFERENCE_TIME * pTimeEnd);

Sets the media time extents for this sample.

•	Returns an HRESULT value.

pTimeStart

Stream time at which the sample begins.

pTimeEnd

Stream time at which the sample ends.

This member function implements the IMediaSample::SetTime method. It sets the m_Start data member to the value of pTimeStart and the m_End data member to the value of pTimeEnd.


CMediaType Class

When filters are connected, they typically negotiate a type between them. This type describes the format of the data to be exchanged; if the filters do not agree on a media type, they cannot connect. Microsoft® ActiveMovie™ describes types through the media type structure, which contains two conceptual parts. The first is a list of members that describes generic attributes of a data stream. An example of this is a member that declares whether the data will be passed in fixed-size buffers. The second part of the structure is a variable-length block of data. How large the block of data should be and what it will contain depend on the type of the data stream. For example, if the data stream is digital video, the format block is a VIDEOINFO structure. If, on the other hand, it is digital audio, the format block is a Microsoft Win32® WAVEFORMATEX structure.

A data stream type (for example, digital video) is set with a combination of two globally unique identifiers (GUIDs), called a major type and a subtype. The major type describes the overall class of data, examples of which might be digital video, digital audio, MIDI, or text captions. The subtype should supply a more specific description of the data type. In the case of digital video, for example, the subtype could be RGB8, RGB16, or RGB32 (among others). By having these two types in a generic structure (AM_MEDIA_TYPE), a component, such as a filter graph, can connect filters without any knowledge that is type-specific.

The distinction between what goes in the major type and the subtype is somewhat arbitrary. However, as a general rule, transformations between major types (for example, video to audio or video to MIDI) should be relatively rare. Such a rare exception might be a transformation between audio and MIDI. As for the subtype, the more information promoted from the type-specific format block into the subtype, the better the design.

As an example of promoting type-specific information to the subtype, video in ActiveMovie uses a VIDEOINFO structure for the type-specific format block. This contains a Win32 BITMAPINFOHEADER structure that defines the video stream. BITMAPINFOHEADER contains the bit depth of the video, such as 8-bit, 16-bit, or 24-bit. This information is duplicated in the subtype field, because a subtype of RGB8 directly infers a bit count of 8.

As part of the first release of ActiveMovie, a number of major types have been defined. The most important of these are a video type that uses VIDEOINFO for the variable-length format block, and an audio that uses WAVEFORMATEX. However, it is insufficient to have a major type (such as digital video) inferring the contents of the format block (in this case, VIDEOINFO). The principle reason for this is extensibility: the format block type must be able to be updated without changing the less-specific major type. Therefore, what the format block actually contains is inferred by another GUID called the format type. If the format block contains VIDEOINFO, the format type GUID will be FORMAT_VideoInfo.

The principle use of the CMediaType class is to manage a media type structure in a simple way. At the same time, the class provides some extra helper functions (such as format-block copying and allocation). The class can be cast to an AM_MEDIA_TYPE structure when an interface method requires one to be passed to it.

The CMediaType class contains a pointer to a block of memory. When copying a CMediaType object, it is insufficient to simply copy the pointer. In C++, a data copy is required, which actually allocates a new block of memory and copies the data into it. This is the purpose of the copy operator.

Similarly, when comparing two CMediaType objects, you must compare the blocks of variable-length data (actually using memcmp) when producing the final result. To this end, the equivalence operator has also been overridden.

Member Functions

AllocFormatBuffer 	Allocates an uninitialized format block in the object.

CMediaType 	Constructs a CMediaType object.

Format 	Returns the format block for this media type.

FormatLength 	Returns the length of the format block of this object.

FormatType 	Returns a pointer to the format type.

GetSampleSize 	Returns the size of the samples.

InitMediaType 	Initializes the media type.

IsFixedSize 	Queries whether the samples are fixed in length.

IsPartiallySpecified 	Checks if the media type is not completely specified.

IsTemporalCompressed 	Queries whether the data stream is compressed temporally.

IsValid 	Queries whether the media type is currently valid.

MatchesPartial 	Checks whether this media type matches another media type that is only partially specified.

ReallocFormatBuffer 	Reallocates the format block, maintaining its current content where possible.

ResetFormatBuffer 	Deletes any format block that is currently present.

SetFormat 	Sets the format block.

SetFormatType 	Sets the type of the format block in the object.

SetSampleSize 	Sets the size of the samples.

SetSubtype 	Sets the subtype.

SetTemporalCompression 	Marks the media type to indicate that samples will be temporally compressed.

SetType 	Sets the major type.

SetVariableSize 	Marks the media type to indicate that samples will vary in length.

Subtype 	Returns a pointer to the subtype.

Type 	Returns a pointer to the major type.

Operators

operator = 	Performs a copy operation.

operator == 	Tests for equality between CMediaType objects.

operator != 	Tests for inequality between CMediaType objects.

operator new 	Allocates memory for a new CMediaType object.

operator delete 	Releases memory for a CMediaType object.


CMediaType::AllocFormatBuffer

BYTE* AllocFormatBuffer(ULONG length);

Allocates a block of memory for the format block.

•	Returns a pointer to the new block if successful; otherwise, returns NULL.

length

Size required for the format block.

Any previous format block is deleted and a new block is allocated and installed. The size required must be nonzero.


CMediaType::CMediaType

CMediaType();

CMediaType(const GUID * majortype);

CMediaType(const AM_MEDIA_TYPE& mtype);

CMediaType(const CMediaType& cmtype);

Constructs a CMediaType object.

majortype

Used to create and initialize a CMediaType object with the specified major type GUID.

mtype

Used to construct this CMediaType object from the AM_MEDIA_TYPE structure.

cmtype

Used to construct one CMediaType from another CMediaType object.

A CMediaType object can be constructed in a number of different ways. The class provides a default constructor that takes no parameters. It can also be constructed based on an AM_MEDIA_TYPE structure or another CMediaType object. In both cases, it takes a data copy of the format block before returning.


CMediaType::Format

BYTE* Format() const;

Returns a pointer to the variable-length format block of the object.

•	Returns the format block of the object whose content is type-specific.

If no format block has been allocated, it may return NULL.


CMediaType::FormatLength

ULONG FormatLength() const;

Returns the size, in bytes, of the format block that the object contains.

•	Returns the length of the format block, or NULL if no format block is present.


CMediaType::FormatType

const GUID *FormatType()const;

Retrieves the format type.

•	Returns a pointer to the format type.

The format GUID describes the content of the variable-length format block. Examples of format types are FORMAT_VideoInfo and FORMAT_WaveFormatEx.


CMediaType::GetSampleSize

ULONG GetSampleSize() const;

Returns the maximum sample size for the data stream.

•	Returns the maximum size of any sample to be sent, or zero to indicate that the sample size is variable.


CMediaType::InitMediaType

void InitMediaType();

Initializes the sample.

This member function clears memory, sets the fixed sample size property, and sets the sample size to 1.


CMediaType::IsFixedSize

BOOL IsFixedSize() const;

Determines if the samples for the stream will be fixed or variable size.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Samples will be fixed size.

FALSE 	Samples will be variable length.


CMediaType::IsPartiallySpecified

BOOL IsPartiallySpecified() const;

Determines if the media type is only partially defined. This is the case if the type, subtype, or format type is GUID_NULL.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Media type is partially specified.

FALSE 	Media type is completely specified.


CMediaType::IsTemporalCompressed

BOOL IsTemporalCompressed() const;

Asks if the stream will be compressed temporally.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Stream will have temporal compression.

FALSE 	Stream has no temporal compression.

Some data streams, such as compressed video, have temporal dependencies between successive samples. Other data streams do not have temporal dependencies between their samples; that is, each sample can be treated as an independent unit, for example, MIDI.


CMediaType::IsValid

BOOL IsValid() const;

Queries whether the object has a valid major type.

•	Returns one of the following values.

Value 	Meaning

TRUE 	CMediaType object has a valid major type.

FALSE 	CMediaType object does not have a valid major type.

When CMediaType objects are constructed, their GUIDs are initialized with GUID_NULL (unless they are constructed based on another AM_MEDIA_TYPE structure or CMediaType object). This member function is useful for discovering if the object has been correctly initialized.


CMediaType::MatchesPartial

BOOL MatchesPartial(const CMediaType *ppartial) const;

Determines if this media type matches the media type pointed to by the ppartial parameter.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Media types match for the parts that are defined.

FALSE 	Media types do not match.

ppartial

Pointer to the media type to match.

The matching applies only for the parts of ppartial that are defined. That is, this only matches the major type, subtype, or format type of the media type if these are not defined as GUID_NULL.


CMediaType::ReallocFormatBuffer

BYTE* ReallocFormatBuffer(ULONG length);

Reallocates the format block to a new size.

•	Returns a pointer to the new block if successful; otherwise, returns NULL.

length

New size required for the format block.

Any current format block will be copied into the newly allocated block up to its maximum size. Any excess will be lost when the new block is smaller than the old one. When the new block is larger, the excess is not filled with zeros.

The size required must be nonzero.


CMediaType::ResetFormatBuffer

void ResetFormatBuffer();

Deletes any format block currently held, sets it to NULL, and sets the size of the format block to zero.


CMediaType::SetFormat

BOOL SetFormat(BYTE *pFormat, ULONG length);

Sets the variable-length format block.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Format block was set.

FALSE 	An error occurred; most likely there was no memory available.

pFormat

Block of memory containing type-specific information.

length

Overall length of the format block.

The function takes a copy of the format block and stores that internally.


CMediaType::SetFormatType

void SetFormatType(const GUID * pformattype);

Sets the GUID that describes the content of the format block.

pformattype

GUID describing the format type.

The format GUID describes what can be expected to be found in the variable-length format block. For example, if the format type is FORMAT_VideoInfo, the format block should contain a VIDEOINFO structure. The creator of this object is responsible for making them consistent.


CMediaType::SetSampleSize

void SetSampleSize(ULONG sz);

Sets the maximum sample size for the data stream.

sz

Size of the sample.

If the sample size passed is zero, the object is set so that the data stream will send variable-length samples (the CMediaType::GetSampleSize member function will return zero). Otherwise, it will set the maximum size of the sample to the size specified in the sz parameter.


CMediaType::SetSubtype

void SetSubtype(const GUID * psubtype);

Sets the subtype for the object.

psubtype

GUID defining the subtype for the object.


CMediaType::SetTemporalCompression

void SetTemporalCompression(BOOL bCompressed);

Marks the media type so that the data stream it describes may or may not contain temporal compression (according to the input Boolean flag).

bCompressed

TRUE to indicate that the stream will contain temporal compression; otherwise, FALSE.


CMediaType::SetType

void SetType(const GUID * ptype);

Sets the major type for the object.

ptype

GUID defining the major type for the object.


CMediaType::SetVariableSize

void SetVariableSize();

Sets the media type to indicate that the data stream will send variable-length samples. Subsequent calls to CMediaType::GetSampleSize will return zero.


CMediaType::Subtype

const GUID *Type()const;

Retrieves the subtype.

•	Returns a pointer to the subtype.

The subtype GUID gives finer detail within the major type of data represented by this media type.


CMediaType::Type

const GUID *Type()const;

Retrieves the major type.

•	Returns a pointer to the major type.

The major type GUID describes the class of data represented by this media type.


CMediaType::operator delete

void operator delete(void *p)

Releases memory for a CMediaType object.

p

Pointer to the memory allocated for a CMediaType object.


CMediaType::operator new

void *operator new(size_t size)

Allocates memory for a new CMediaType object.

•	Returns a pointer to the memory allocated.

size

Number of bytes to allocate.


CMediaType::operator =

CMediaType& operator=(const CMediaType& rt)

CMediaType& operator=(const AM_MEDIA_TYPE& mrt)

The CMediaType variation of this operator is the copy constructor for a CMediaType object.

The AM_MEDIA_TYPE variation of this operator is the copy constructor for an AM_MEDIA_TYPE object.

•	Returns a reference to this object after the operation.

rt

Used to copy an existing CMediaType object.

mrt

Used to copy an existing AM_MEDIA_TYPE object.

Because the CMediaType class inherits publicly from AM_MEDIA_TYPE, the compiler could generate the copy constructor for the AM_MEDIA_TYPE object itself. However, this could introduce some memory conflicts and leaks in the process because the structure contains a dynamically allocated block (which the AM_MEDIA_TYPE pbFormat member points to), which the compiler's copy constructor will not copy correctly.


CMediaType::operator ==

inline BOOL operator==(const CMediaType& rt) const

Tests for equality between CMediaType objects.

•	Returns TRUE if the CMediaType object tested is equal to this object; otherwise, returns FALSE.

rt

CMediaType object corresponding to the right side of the operator.

This object is on the left side of the operator.


CMediaType::operator !=

BOOL operator!=(const CMediaType& rt) const;

Tests for inequality between CMediaType objects.

•	Returns TRUE if the CMediaType object tested is not equal to this object; otherwise, returns FALSE.

rt

CMediaType object corresponding to the right side of the operator.

This object is on the left side of the operator.


CMemAllocator Class

This class provides support for IMemAllocator by using the new operator to allocate memory. Derived from CBaseAllocator, it overrides the CBaseAllocator::Alloc member function to allocate a single block of memory large enough to hold all the requested data areas, and then allocates (using the new operator) a CMediaSample object for each requested buffer pointing into the data area.

The CBaseInputPin and CBaseOutputPin classes instantiate CMemAllocator objects as the default allocator if no other suitable allocator is provided.

All member functions in this class that return HRESULT and accept a pointer as a parameter return E_POINTER when passed a null pointer.

Member Functions

Alloc 	Allocates memory for a media sample (overrides CBaseAllocator::Alloc).

CMemAllocator 	Constructs a CMemAllocator object.

ReallyFree 	Frees memory when called from the destructor (or from Alloc when reallocating for new size or count).

Overridable Member Functions

Free 	Indicates an overridden CBaseAllocator::Free member function called when a decommit operation is complete to free memory.

Implemented IMemAllocator Methods

SetProperties 	Sets the number of media samples and the size of each.


CMemAllocator::Alloc

HRESULT Alloc(void);

Allocates a media sample object.

•	Returns an HRESULT value.

This member function instantiates CMediaSample objects and adds them to the m_lFree data members and updates the m_lAllocated count. This member function is called from IMemAllocator::Commit when becoming active.


CMemAllocator::CMemAllocator

CMemAllocator(TCHAR * pName, LPUNKNOWN lpUnk,

    HRESULT * phr );

Constructs a CMemAllocator object.

pName

Name of the allocator object.

lpUnk

Pointer to LPUNKNOWN.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.

This constructor is passed to CBaseAllocator::CBaseAllocator, which initializes the data members.


CMemAllocator::Free

HRESULT Free(void);

Frees memory for a media sample object.

This member function overrides the pure virtual CBaseAllocator::Free member function called when a decommit operation has completed. Memory is actually freed in ReallyFree, which is called from the destructor, so this function is not used in this class.


CMemAllocator::ReallyFree

void ReallyFree (void);

Releases all media samples in the free list.

The CMemAllocator class holds memory until the object is actually deleted. This member function can be overridden to handle freeing media samples when a decommit occurs.

This member function is protected.


CMemAllocator::SetProperties

HRESULT SetProperties(ALLOCATOR_PROPERTIES * pRequest,

    ALLOCATOR_PROPERTIES * pActual);

Determines the size, number, and alignment of blocks.

•	Returns an HRESULT value.

pRequest

Requested allocator properties.

pActual

Allocator properties actually set.

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 using the IMemAllocator::Decommit method.

This member function is protected.

This member function replaces SetCountAndSize in previous releases.


CMsg Class

The CMsgThread class provides support for a worker thread to which requests can be posted asynchronously instead of sent directly. The CThread 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(UINT u, DWORD dw, LPVOID lp, CAMEvent *pEvent);

Constructs a CMsg object.

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

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.

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

This 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_ThreadQueue 	Overrides the CMsgThread::GetThreadMsg member function and blocks on things other than this queue.

m_Lock 	Protects access to lists.

m_hSem 	Indicates a handle used for signaling.

m_lWaiting 	Indicates waiting for a free thread.

Member Functions

CMsgThread 	Constructs a CMsgThread object.

CreateThread 	Creates a thread.

GetThreadHandle 	Returns the thread handle.

GetThreadID 	Returns 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 	Initializes the thread.

ThreadMessageProc 	Processes requests. This is a pure virtual member function.


CMsgThread::CMsgThread

CMsgThread();

Constructs a CMsgThread object.

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

BOOL CreateThread();

Creates a thread.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Thread was successfully created.

FALSE 	Thread was not successfully created.

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

HANDLE GetThreadHandle();

Retrieves the handle to the thread in the CMsgThread object.

•	Returns the thread handle.

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

DWORD GetThreadID();

Returns the identifier of the thread.

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

void virtual GetThreadMsg(CMsg *msg);

Retrieves a queued CMsg object containing a request.

msg

Pointer to an allocated CMsg object.

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

int GetThreadPriority();

Uses the Microsoft Win32 GetThreadPriority function to retrieve the priority of the current worker thread.

•	Returns the thread priority as an integer.


CMsgThread::OnThreadInit

virtual void OnThreadInit();

Initializes this thread. Override this if you want to do something on thread startup.


CMsgThread::PutThreadMsg

void PutThreadMsg(UINT uMsg, DWORD dwMsgFlags,

    LPVOID lpMsgParam, CAMEvent *pEvent = NULL);

Queues a request for execution by the worker thread.

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.

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

DWORD ResumeThread();

Uses the Microsoft Win32 ResumeThread function to continue the operation of the worker thread after a previous call to the CMsgThread::SuspendThread member function.

•	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

BOOL SetThreadPriority(int nPriority);

Uses the Microsoft Win32 SetThreadPriority function to set the priority of the thread to a new value.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Priority was successfully set.

FALSE 	Priority was not set.

nPriority

Priority of the thread.

The client and the worker thread can call this member function.


CMsgThread::SuspendThread

DWORD SuspendThread();

Uses the Microsoft Win32 SuspendThread function to suspend the operation of a running thread.

•	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.

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

virtual LRESULT ThreadMessageProc(UINT uMsg,

    DWORD dwFlags, LPVOID lpParam, CAMEvent *pEvent);

Processes requests. This is a pure virtual member function.

•	Any nonzero return causes the thread to exit. Returns zero unless an exit request has been processed recently.

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.

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

BOOL WaitForThreadExit(LPDWORD lpdwExitCode);

Blocks until the thread exits.

•	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.

lpdwExitCode

Exit code returned by the thread.

Ensure that the worker thread has exited completely before completing the destruction of your derived class; otherwise, the thread may 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.


CMultiPinPosPassThru Class

The CMultiPinPosPassThru class implements a pass-through of IMediaPosition methods from an upstream filter. Commands to start and stop the media at specific times or to change the rate are issued by the filter graph manager to the renderer by calling methods on its IMediaPosition interface.

The renderer filter then passes these commands upstream by calling IMediaPosition interface methods on the output pin of the upstream filter, which passes it to its upstream filter's output pin, and so on. The CPosPassThru class handles this duty for transform filters with single input pins. This class is used by filters such as CBaseVideoMixer, which has multiple input pins that are connected to output pins. It maintains an array of pointers to the IMediaPosition interfaces of the output pins connected to its input pins. Then, for every put_ command, it iterates through the array setting the property.

Protected Data Members

m_iPinCount 	Number of pins.

m_apMP 	Array of pointers to the IMediaPosition interfaces on the output pins connected to the input pins on this filter.

m_apOffsets 	Array of reference time offsets.

m_rtStartTime 	Start reference time.

m_rtStopTime 	Stop reference time.

m_rtPrerollTime 	Preroll reference time.

m_dRate 	Rate.

Member Functions

CMultiPinPosPassThru 	Constructs a CMultiPinPosPassThru object.

ResetPins 	Discards current pointers and resets the pins.

SetPins 	Sets pointers to pins and pin count.

Implemented IMediaPosition Methods

get_Duration 	Retrieves the total duration of the media.

get_CurrentPosition 	Retrieves the position within the media at which playback will start.

put_CurrentPosition 	Sets the position within the media at which playback should start on each pin.

get_StopTime 	Retrieves the position within the media at which playback should stop.

put_StopTime 	Sets the position within the media at which playback should stop on each pin.

get_PrerollTime 	Retrieves the time before the start position that the filter graph will start any nonrandom access device rolling.

put_PrerollTime 	Sets the time before the start position that the filter graph will start any nonrandom access device rolling on each pin.

get_Rate 	Retrieves the playback rate, relative to normal playback of the media.

put_Rate 	Sets the playback rate, relative to normal playback of the media on each pin.


CMultiPinPosPassThru::CMultiPinPosPassThru

CMultiPinPosPassThru(TCHAR *pName,

    LPUNKNOWN pUnk, HRESULT *phr );

Constructs a CMultiPinPosPassThru object.

pName

Pointer to the CMultiPinPosPassThru object name for debugging purposes.

pUnk

Pointer to the owning object.

phr

The returned HRESULT value. This will be set only if a failure occurs.


CMultiPinPosPassThru::ResetPins

 HRESULT ResetPins(void);

Resets all pins to NULL.

•	Returns an HRESULT value.


CMultiPinPosPassThru::SetPins

HRESULT SetPins(CBasePin **apPins, int iPinCount);

Resets pins and allocates an array of pointers to IMediaPosition interfaces on the pins.

•	Returns an HRESULT value.

apPins

Array of input pin pointers.

iPinCount

Number of input pins in the array.


COARefTime Class

This class converts between the OLE Automation-compatible REFTIME type and the REFERENCE_TIME type used within and between filters.

Time parameters within the control interfaces are represented as double values, containing a fractional number of seconds. Interfaces supported between and within filters use a 64-bit LONGLONG type containing the time in 100-nanosecond units. Filters use this class to convert between the two formats. It is derived from CRefTime and thus is a LONGLONG, but it can be constructed from and assigned double values.

Member Functions

COARefTime 	Constructs a COARefTime object.

Operators

double 	Returns the reference time as a double value.

Operator = 	Copy constructor for the COARefTime class.

Operator == 	Tests for equality between COARefTime objects.

Operator != 	Tests for inequality between COARefTime objects.

Operator < 	Tests if one COARefTime object is less than another COARefTime object.

Operator > 	Tests if one COARefTime object is greater than another COARefTime object.

Operator <= 	Tests if one COARefTime object is less than or equal to another COARefTime object.

Operator >= 	Tests if one COARefTime object is greater than or equal to another COARefTime object.

Operator + 	Adds two COARefTime objects.

Operator - 	Subtracts one COARefTime object from another COARefTime object.

Operator += 	Adds two COARefTime objects and makes this object equal to the result.

Operator -= 	Subtracts one COARefTime object from another COARefTime object and makes this object equal to the result.

Operator * 	Multiplies two COARefTime objects.

Operator / 	Divides one COARefTime object by another COARefTime object.


COARefTime::COARefTime

COARefTime(CRefTime t);

COARefTime(REFERENCE_TIME t);

COARefTime(double d);

Constructs a COARefTime object.

t

CRefTime value or REFERENCE_TIME value passed through to the class. Units are 100 nanoseconds.

d

A double value that constructs the COARefTime class. Units in this case are (fractional) seconds.


COARefTime::double

operator double() {

    return double(RefTime.QuadPart) / 10000000;

  };

Returns the reference time as a double value, converted from 100-nanosecond units to seconds.


COARefTime::Operator =

COARefTime& operator=(const double& rd)  {

    RefTime.QuadPart = (LONGLONG) (rd * 10000000);

    return *this;

A duplicate constructor for a COARefTime object.

rd

A double value that constructs a COARefTime object.


COARefTime::Operator ==

inline BOOL operator==(const COARefTime& rt)

Tests for equality between COARefTime objects.

•	Returns TRUE if the COARefTime object tested is equal to this object; otherwise, returns FALSE.

rt

A COARefTime object corresponding to the right side of the operator.

This object is on the left side of the operator.


COARefTime::Operator !=

inline BOOL operator!=(const COARefTime& rt)

Tests for inequality between COARefTime objects.

•	Returns TRUE if the COARefTime object tested is not equal to this object; otherwise, returns FALSE.

rt

A COARefTime object corresponding to the right side of the operator.

This object is on the left side of the operator.


COARefTime::Operator <

inline BOOL operator < (const COARefTime& rt)

Tests if one COARefTime object is less than another COARefTime object.

•	Returns TRUE if the COARefTime object tested is less than this object; otherwise, returns FALSE.

rt

A COARefTime object corresponding to the right side of the operator.

This object is on the left side of the operator.


COARefTime::Operator >

inline BOOL operator > (const COARefTime& rt)

Tests if one COARefTime object is greater than another COARefTime object.

•	Returns TRUE if the COARefTime object tested is greater than this object; otherwise, returns FALSE.

rt

A COARefTime object corresponding to the right side of the operator.

This object is on the left side of the operator.


COARefTime::Operator >=

inline BOOL operator >= (const COARefTime& rt)

Tests if one COARefTime object is greater than or equal to another COARefTime object.

•	Returns TRUE if the COARefTime object tested is greater than or equal to this object; otherwise, returns FALSE.

rt

A COARefTime object corresponding to the right side of the operator.

This object is on the left side of the operator.


COARefTime::Operator <=

inline BOOL operator <= (const COARefTime& rt)

Tests if one COARefTime object is less than or equal to another COARefTime object.

•	Returns TRUE if the COARefTime object tested is less than or equal to this object; otherwise, returns FALSE.

rt

A COARefTime object corresponding to the right side of the operator.

This object is on the left side of the operator.


COARefTime::Operator +

inline COARefTime operator+(const COARefTime& rt)

Adds two COARefTime objects.

•	Returns the result of the addition.

rt

A COARefTime object to be added.


COARefTime::Operator -

inline COARefTime operator-(const COARefTime& rt)

Subtracts one COARefTime object from another COARefTime object.

•	Returns the result of the subtraction.

rt

A COARefTime object to be subtracted.

This object is the object subtracted from.


COARefTime::Operator +=

inline COARefTime& operator+=(const COARefTime& rt)

Adds two COARefTime objects and makes this object equal to the result.

•	Returns the result.

rt

A COARefTime object to be added.


COARefTime::Operator -=

inline COARefTime& operator-=(const COARefTime& rt)

Subtracts one COARefTime object from another COARefTime object and makes this object equal to the result.

•	Returns the result.

rt

A COARefTime object to be subtracted.

This object is the object subtracted from.


COARefTime::Operator *

inline COARefTime operator*(LONG l)

Multiplies the COARefTime object by a value.

•	Returns the result.

l

The value to multiply by.


COARefTime::Operator /

inline COARefTime operator/(LONG l)

Divides one COARefTime object by a value.

•	Returns the result.

l

The value to divide by.


COutputQueue Class

COutputQueue is a class that is used by output pins to send samples to another filter by using the local memory-based transport (that is, to input pins that support the IMemInputPin interface). COutputQueue uses IMemInputPin::ReceiveCanBlock to determine if the connected input pin has a blocking implementation of IMemInputPin::Receive. If so, all samples are queued in COutputQueue and a thread is created to pass samples from the queue to the connected input pin. If the input pin's IMemInputPin::Receive method does not block, samples are passed directly to IMemInputPin::Receive. COutputQueue can also batch samples to reduce the number of calls to the downstream pin.

COutputQueue is useful when the filter has other work to do while samples that it has already completed are being processed downstream. This occurs, for example, in a filter that can read more data off disk while data is being processed, or when it has more than one output pin and does not want to starve an output pin because IMemInputPin::Receive has no optional batching of samples.

To use this class, create one COutputQueue object for every output pin for which it is to be used. This can either be created when the pin is created and deleted when the pin is disconnected, or it can be created when the pin goes active and deleted when the pin goes inactive.

The samples sent to this object by calling its COutputQueue::Receive or COutputQueue::ReceiveMultiple member function should have references added via IUnknown::AddRef (as they usually are if they were obtained directly from an allocator). This object then calls IUnknown::Release on all samples it receives, whether they were processed successfully or not. Note that Release is not called for special (control) samples.

Some control information, such as end of stream, needs to be queued with the data and processed once all the data has been delivered. This information is queued in the form of special control packets. COutputQueue implements a sticky HRESULT so it will not send any more data after it gets a return code that is not S_OK from the downstream ReceiveMultiple call. This state is reset by the EndFlush and EOS calls. However, if the sticky HRESULT is not S_OK, EOS itself is not sent downstream; the HRESULT is just reset. Because of this, if this object is not deleted when the pin goes inactive, BeginFlush and EndFlush should be called at that time to free the state.

In many ways this object acts as a proxy for the connected input pin, supporting a similar set of methods for stream control.

Protected Data Members

m_pPin 	Pointer to the output pin.

m_pInputPin 	Pointer to the connected input pin.

m_bBatchExact 	TRUE if commands are batched; FALSE if commands are sent singly.

m_lBatchSize 	Work in batches of this batch size. Ignored if m_bBatchExact is not TRUE.

m_List 	Pointer to CSampleList.

m_hSem 	Handle used for signaling.

m_evFlushComplete 	Event signaling that flushing has finished.

m_hThread 	Worker thread handle.

m_ppSamples 	Pointer to an array of batched samples.

m_nBatched 	Number of samples currently batched awaiting processing.

m_lWaiting 	Variable set to non-zero value when waiting for a free element.

m_bFlushing 	Flag for flushing state.

m_bFlushed 	Flag to signify if samples have been flushed.

m_bTerminate 	Termination flag.

m_bSendAnyway 	Flag to override batch processing.

m_hr 	HRESULT structure for return values; used to implement a "sticky" return value.

Member Functions

COutputQueue 	Constructs a COutputQueue object.

BeginFlush 	Causes all unsent samples to be discarded and sets flushing state.

EndFlush 	Finalizes flush of batched or queued samples and resets flushing state.

EOS 	Queues an end-of-stream call to the connected input pin after all batched and queued samples have been passed to the input pin.

FreeSamples 	Removes and releases batched and queued samples.

InitialThreadProc 	Executed by the thread on thread creation.

IsQueued 	Determines if samples are being queued or being sent directly.

IsSpecialSample 	Determines if the sample is a control sample.

NotifyThread 	Notifies the thread that there is something to do.

NewSegment 	Queues an IPin::NewSegment call to the connected input pin after all queued samples have been passed to the input pin.

QueueSample 	Queues the prepared sample.

Receive 	Passes in a single sample to send to the input pin.

ReceiveMultiple 	Passes a set of samples to send to the input pin.

Reset 	Resets the deferred return code m_hr to allow the output queue to be ready for more data.

SendAnyway 	Frees any batches samples to be sent to the input pin.

ThreadProc 	Implements the thread that sends samples downstream.


COutputQueue::COutputQueue

COutputQueue(IPin     *pInputPin,

              HRESULT   *phr,

              BOOL       bAuto = TRUE,

              BOOL       bQueue = TRUE,

              LONG       lBatchSize,

              BOOL       bBatchExact,

              LONG       lListSize,

              DWORD      dwPriority);

Constructs a COutputQueue object.

pInputPin

Connected pin to which to send data.

phr

HRESULT return code.

bAuto

If TRUE, the queuing mode is determined by asking the connected input pin if the pin can block (by calling IMemInputPin::ReceiveCanBlock). If FALSE, queued or direct mode is set by the bQueue parameter.

bQueue

Determines if samples are queued for delivery by a worker thread or are being sent directly. Ignored if bAuto is TRUE.

lBatchSize

Size of the batch (1 for no batching).

bBatchExact

Batch exactly to lBatchSize (but use SendAnyway to override batching).

lListSize

Likely number in the list.

dwPriority

Priority given to the created thread.

The phr parameter should be updated only to report errors. Usually bAuto will be TRUE. In that case, the constructor calls IMemInputPin::ReceiveCanBlock on the downstream pin to determine whether to create a thread, and so to send samples asynchronously. If bAuto is FALSE, a thread is created if, and only if, bQueue is TRUE.

If the batch size is not 1, data is not sent until lBatchSize samples have been received by the object. The exceptions are that, if fewer than lBatchSize samples are passed to COutputQueue::Receive or COutputQueue::ReceiveMultiple in this object and bBatchExact is FALSE, the samples will be sent anyway.

If bBatchExact is TRUE, the COutputQueue::SendAnyway member function will cause the samples to be sent to the thread (if the thread is created).


COutputQueue::BeginFlush

void BeginFlush();

Causes all unsent samples to be discarded and sets the flushing state.

This member function calls BeginFlush on the connected input pin.


COutputQueue::EndFlush

void EndFlush();

Finalizes flush of batched or queued samples and resets the flushing state.

The downstream pin is guaranteed not to block at this stage.


COutputQueue::EOS

void EOS();

Queues an end-of-stream call to the connected input pin after all batched and queued samples have been passed to the input pin.

The end-of-stream call is queued as a special control packet when in a queued mode. This member function does not actually send an end-of-stream packet if the m_hr HRESULT value is not S_OK when it is time to make the call.


COutputQueue::FreeSamples

void FreeSamples();

Removes and releases batched and queued samples.


COutputQueue::InitialThreadProc

static DWORD WINAPI InitialThreadProc(LPVOID pv);

Implements the static member function that the thread executes on thread creation.

•	The meaning of the return value is defined by the derived class.

pv

The this pointer for the COutputQueue object.

On thread creation, the worker thread executes this static function with a pointer to the COutputQueue object as the parameter. This function simply calls the COutputQueue::ThreadProc member function of that object (that is, the function pointed to by pv).


COutputQueue::IsSpecialSample

BOOL IsSpecialSample(IMediaSample *pSample)

Determines if a sample is one of the special control samples (containing no data).

•	Returns one of the following values.

Value 	Meaning

TRUE 	pSample is a special control sample.

FALSE 	pSample is an IMediaSample interface.

pSample

Pointer to the sample to be passed to the connected input pin.

Special control samples are queued in line with the data by methods (such as COutputQueue::EOS) that require processing once all queued data has been delivered. The COutputQueue::ThreadProc member function detects these special samples on the queue by using IsSpecialSample and processes them appropriately.

A special sample is one of following types and contains no media data:

SEND_PACKET

EOS_PACKET

RESET_PACKET

NEW_SEGMENT

Special control samples are relevant only if you plan to change or extend the default base class implementation of COutputQueue in a derived class. Normal use of the COutputQueue class does not require the use of control samples.


COutputQueue::IsQueued

BOOL IsQueued();

Determines if the COutputQueue object is in queued or direct mode.

•	Returns one of the following values.

Value 	Meaning

TRUE 	In queued mode. Samples are delivered asynchronously by a worker thread.

FALSE 	In direct mode. Receive calls are passed synchronously to the input pin.


COutputQueue::NewSegment

HRESULT NewSegment(REFERENCE_TIME tStart,

                        REFERENCE_TIME tStop,

                        double dRate);

Queues an IPin::NewSegment call to the connected input pin after all queued samples have been passed to the input pin.

•	Returns an HRESULT value.

tStart

[in] Start time of the segment.

tStop

[in] Stop time of the segment.

dRate

[in] Rate of the segment.

This member function calls the IPin::NewSegment method on the output pin once all previous data has been delivered. Like COutputQueue::EOS, the COutputQueue::NewSegment call and its parameters are queued as a special control sample if the COutputQueue object is in queued mode, and the IPin::NewSegment method is called from the worker thread in COutputQueue::ThreadProc.

Special control samples, as implemented by this member function, are only relevant if you plan to change or extend the default base class implementation of COutputQueue in a derived class. Normal use of the COutputQueue class does not require the use of control samples.

This member function allows filters that process buffers containing more than one sample to delineate the rendering of the samples between start and stop time, as indicated by the tStart and tStop parameters.

COutputQueue::NewSegment is intended to be implemented on an input pin. A connected output pin on the upstream filter calls this member function after completing delivery of previous data and before calling IMemInputPin::Receive with any new data. It indicates that all data arriving after this call is part of a segment delineated by the parameters.


COutputQueue::NotifyThread

void NotifyThread();

Notifies the thread that there is data on the queue to process.

The critical section must be held when this is called.


COutputQueue::QueueSample

void QueueSample(IMediaSample *pSample);

Queues a sample.

pSample

Pointer to the sample to be passed to the connected input pin.

The critical section must be held when this is called.


COutputQueue::Receive

HRESULT Receive(IMediaSample *pSample);

Passes in a single sample to send to the input pin.

•	Returns an HRESULT value, which may include the following values, or others.

Value 	Meaning

S_FALSE 	End of stream detected before or while processing sample; any further samples will be discarded and this value returned.

Other 	An error occurred before or while processing sample; any further samples will be discarded and this value returned.

S_OK 	Queued successfully or passed to the connected input pin if there is no queue.

pSample

Pointer to the sample to be passed to the connected input pin.

If the sticky return code (m_hr) is not S_OK, the sample is not sent and the sticky return code is returned. The samples are all released (via Release) after processing, regardless of whether the processing was successful.


COutputQueue::ReceiveMultiple

HRESULT ReceiveMultiple (IMediaSample **ppSamples,

                              long    nSamples,

                              long   *nSamplesProcessed);

Passes a set of samples to send to the input pin.

•	Returns an HRESULT value, which may include the following values, or others.

Value 	Meaning

S_FALSE 	End of stream detected before or while processing sample; any further samples will be discarded and this value returned.

Other 	An error occurred before or while processing sample; any further samples will be discarded and this value returned.

S_OK 	Queued successfully or passed to the connected input pin if there is no queue.

ppSamples

Pointer to the set of samples to be passed to the connected input pin.

nSamples

Number of samples pointed to by ppSamples.

nSamplesProcessed

Updated to be the number of samples processed.

If the sticky return code is not S_OK, the sample is not sent and the sticky return code is returned. The samples are all released (via Release) after processing, regardless of whether the processing was successful.


COutputQueue::Reset

void Reset();

Resets the deferred return code m_hr to ready the output queue for more data.

The sticky return code m_hr is set to S_OK if data is queued; otherwise, this function queues the sample and notifies the thread.


COutputQueue::SendAnyway

void SendAnyway();

If bBatchExact was specified on construction, any batched samples are freed to be sent to the input pin.


COutputQueue::ThreadProc

DWORD ThreadProc();

Implements the thread that sends samples downstream.

•	Returns 0 if thread is terminated.

This is the main thread procedure for the class, which is called from COutputQueue::InitialThreadProc. It sends a sample or a batch of samples to the connected input pin (depending on the m_bBatchExact, m_nBatched, and m_lBatchSize data members) when conditions are met. Otherwise, it increments the m_lWaiting data member, while holding the critical section and waits for m_hSem to be set (not holding the critical section) to continue.


CPersistStream Class

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 "do nothing" functions here.

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, do not forget that a WCHAR is 2 bytes.

5	Whenever your data changes, call SetDirty.

Version Numbers

At some point you may 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 needs to be saved.

Member Functions

CPersistStream 	Constructs a CPersistStream object.

SetDirty 	Indicates that the object needs to be saved to the stream.

Overridable Member Functions

SizeMax 	Returns the number of bytes needed for data (not including version number).

GetClassID 	Returns the class identifier of this stream.

GetSoftwareVersion 	Returns the version number for this file format.

ReadFromStream 	Reads the filter's data from the stream.

WriteToStream 	Writes the filter's data to the stream.

CPersistStream implements IPersistStream. For more implementation information, see "OLE Programmers Reference (Vol. 1): Structured Storage Overview."

Implemented IPersistStream Methods

GetSizeMax 	Returns the number of bytes needed for data (including version number).

IsDirty 	Checks if the object needs to be saved.

Load 	Loads the data from the stream into memory.

Save 	Saves the data from memory to the stream.


CPersistStream::CPersistStream

CPersistStream(IUnknown *pUnk, HRESULT *phr);

Constructs a CPersistStream object.

pUnk

The IUnknown interface of the delegating object.

phr

Pointer to the general OLE return value. Note that this value is changed only if this function fails.


CPersistStream::GetClassID

HRESULT GetClassID(CLSID *pClsID);

Retrieves the class identifier for this filter.

•	Returns an HRESULT value.

pClsID

A pointer to a CLSID structure. Copy your class ID to here.


CPersistStream::GetSizeMax

HRESULT GetSizeMax(ULARGE_INTEGER * pcbSize);

Returns the maximum byte size needed for the current stream, including the version number.

•	Returns an HRESULT value.

pcbSize

Size in bytes needed to save this stream, including the version number.

This member function implements the IPersistStream::GetSizeMax method.


CPersistStream::GetSoftwareVersion

virtual DWORD GetSoftwareVersion(void);

Returns the software version for this stream.

•	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.


CPersistStream::IsDirty

HRESULT IsDirty();

Indicates whether the object has changed since it was last saved to its current stream.

•	Returns one of the following.

S_OK 	The filter needs saving.

S_FALSE 	The filter does not need saving.

This member function implements the IPersistStream::IsDirty method.


CPersistStream::Load

HRESULT Load(LPSTREAM pStm);

Loads the filter's data from a given stream.

•	Returns an HRESULT value.

pStm

Pointer to the stream from which to be loaded.

This member function implements the IPersistStream::Load method.


CPersistStream::ReadFromStream

virtual HRESULT ReadFromStream(IStream *pStream);

Reads the filter's data from the given stream.

•	Returns NOERROR by default; the overriding member function should return a valid HRESULT value.

pStream

Pointer to an IStream from which data is to be read.

The default version reads nothing; it can be overridden to read data specific to your class.


CPersistStream::Save

HRESULT Save(LPSTREAM pStm, BOOL fClearDirty);

Saves the filter's data to the given stream.

•	Returns an HRESULT value.

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. When called as part of Save, the flag is normally reset; when called as part of Save As, the flag is normally not reset.

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

HRESULT SetDirty(BOOL fDirty);

Changes the dirty flag for the current stream.

•	Returns an HRESULT value.

fDirty

The new dirty flag for this stream. TRUE means that the data has not been saved.


CPersistStream::SizeMax

virtual int SizeMax();

Retrieves the maximum byte size needed for the current stream, not including the version number.

•	Returns the number of bytes needed for data, not including the version number.

The default version returns zero; it should be overridden to provide some other appropriate value.


CPersistStream::WriteToStream

virtual HRESULT WriteToStream(IStream *pStream);

Writes the filter's data to the given stream.

•	Returns NOERROR by default; the overriding member function should return a valid HRESULT value.

pStream

Pointer to an IStream to write the filter's data to.

The default version writes nothing; it can be overridden to write data specific to your class.


CPosPassThru Class

The CPosPassThru class is a utility class that handles the IMediaPosition and IMediaSelection interfaces for single-input pin renderers or transform filters that provide seeking by calling methods on the output pin to which they are connected.

IMediaPosition is the interface originally used for seeking in time-based media streams. IMediaSelection is an interface intended to replace IMediaPosition in filter graphs that require seeking to units other than time, such as samples, or fields. This class performs conversions between the two interfaces when the seeking unit format for IMediaSelection is set to time.

Renderers will expose this class from the filter; transform filters will expose it from the output pin and not the renderer. In both cases, the methods will be implemented by calls to the IMediaPosition or IMediaSelection interface provided by the output pin of the connected upstream filter.

Create one of these, giving it the IPin pointer to your input pin, and delegate all IMediaPosition and IMediaSelection methods to it. It will find the output pin connected to the input pin, query this output pin for the IMediaPosition or IMediaSelection interface, and respond appropriately.

Call the CPosPassThru::ForceRefresh member function if the pin connection changes.

Member Functions

CPosPassThru 	Constructs a CPosPassThru object.

ForceRefresh 	Releases any cached interfaces held on the upstream pin.

Overridable Member Functions

GetMediaTime 	Override to return an accurate current position.

Implemented IMediaPosition Methods

get_CurrentPosition 	Retrieves the position within the media that playback has reached.

get_Duration 	Retrieves the total duration of the media.

get_PrerollTime 	Retrieves the time before the start position that the filter graph will start any nonrandom access device rolling.

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 	Sets the time before the start position that the filter graph will start any nonrandom access device rolling.

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.

Implemented IMediaSelection Methods

GetCurrentPosition 	Retrieves the current position within the media stream.

GetDuration 	Retrieves the length of time that the media stream will play.

GetStopPosition 	Retrieves the position within the media stream at which playback should stop.

GetTimeFormat 	Retrieves the current media time format.

IsFormatSupported 	Determines if a specified time format is supported.

QueryPreferredFormat 	Retrieves the preferred time format to be used by the interface.

SetSelection 	Sets the start time, end time, and rate of play.

SetTimeFormat 	Sets the time format, which determines the format of units used during seeking.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Returns a specified reference-counted interface.


CPosPassThru::CPosPassThru

CPosPassThru(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT * phr, IPin * pPin);

Constructs a CPosPassThru object.

pName

Name of the object used in the CPosPassThru constructor for debugging purposes.

pUnk

Pointer to the owner of this object.

phr

Pointer to an HRESULT value for resulting information.

pPin

Pointer to the input pin for the filter.

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.


CPosPassThru::ForceRefresh

HRESULT ForceRefresh();

Releases any cached interfaces on the upstream pin.

•	Returns S_OK.

For efficiency, the CPosPassThru class may cache the IMediaPosition interface of the connected upstream output pin. This method releases any cached interface pointers and forces them to be obtained again via QueryInterface if needed.

Call this member function if the pin connection changes to release any cached interfaces.


CPosPassThru::get_CurrentPosition

HRESULT get_CurrentPosition(REFTIME* pllTime);

Retrieves the position within the stream at which playback should begin.

•	Returns an HRESULT value.

pllTime

The returned start time as a double value in seconds.

The start position is applied before the rate and therefore is the position at typical playback speed.


CPosPassThru::get_Duration

HRESULT get_Duration(REFTIME * plength);

Retrieves the total duration of the media stream.

•	Returns an HRESULT value.

plength

The returned length of the media stream.

The duration assumes normal playback speed, and it is therefore unaffected by the rate.


CPosPassThru::get_PrerollTime

HRESULT get_PrerollTime(REFTIME* pllTime);

Retrieves the time prior to the start position that devices should start rolling.

•	Returns an HRESULT value.

pllTime

Returned preroll time as a double value in seconds.

Preroll time is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.


CPosPassThru::get_Rate

HRESULT get_Rate(double * pdRate);

Retrieves the rate of playback relative to normal playback speed.

•	Returns an HRESULT value.

pdRate

Returned rate.

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.


CPosPassThru::get_StopTime

HRESULT get_StopTime(REFTIME* pllTime);

Retrieves the time at which the media stream stops.

•	Returns an HRESULT value.

pllTime

The returned stop time as a double value in seconds.

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.


CPosPassThru::GetCurrentPosition

HRESULT GetCurrentPosition(LONGLONG* pCurrent);

Retrieves the current position in terms of the total length of the media stream.

•	Returns an HRESULT value.

pCurrent

The current position in current time format units.

This member function implements the IMediaSelection::GetCurrentPosition interface.


CPosPassThru::GetDuration

HRESULT GetDuration(LONGLONG* pDuration);

Retrieves the length of time that the media stream will play.

•	Returns an HRESULT value.

pDuration

The returned length of the media stream.

This member function implements the IMediaSelection::GetDuration method.


CPosPassThru::GetMediaTime

HRESULT GetMediaTime(LONGLONG* pStart,

    LONGLONG* pEnd );

Retrieves the starting and ending media times.

•	Returns an HRESULT value (E_FAIL by default).

pStart

The returned starting media time.

pEnd

The returned ending media time.

Override this member function to return the media time of the current sample. This represents the current position in terms of media time (for example, frame 20 of a total 130 frames).


CPosPassThru::GetStopPosition

HRESULT GetStopPosition(LONGLONG* pStop);

Retrieves the time at which the media stream stops.

•	Returns an HRESULT value.

pStop

The returned stop time.

This member function implements the IMediaSelection::GetStopPosition method.


CPosPassThru::GetTimeFormat

HRESULT GetTimeFormat(const GUID Format);

Sets the media time format, which determines the format of units used during seeking.

•	Returns an HRESULT value.

Format

The media time format currently supported by this interface.

This member function implements the IMediaSelection::GetTimeFormat method.

See the IMediaSelection::IsFormatSupported method for a list of time formats.


CPosPassThru::IsFormatSupported

HRESULT IsFormatSupported(const GUID Format);

Determines if a specified time format is supported.

•	Returns an HRESULT value.

Format

Time format to compare.

This member function implements the IMediaSelection::IsFormatSupported method. See that method for a list of valid time formats.


CPosPassThru::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void **ppv);

Returns a specified reference-counted interface.

•	Returns pointers to the IMediaPosition, IMediaSelection, and IUnknown interfaces by default.

riid

Reference identifier.

ppv

Pointer to the interface.

Override this method to publish any additional interfaces implemented by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CPosPassThru::put_CurrentPosition

HRESULT put_CurrentPosition(REFTIME llTime);

Sets the time that the media stream begins.

•	Returns an HRESULT value.

llTime

Start time expressed as a double value in seconds.

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. Do not call this method when the filter graph is actually running, only when it is paused or stopped.

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.


CPosPassThru::put_PrerollTime

HRESULT put_PrerollTime(REFTIME llTime);

Sets the time prior to the start position that devices should start rolling.

•	Returns an HRESULT value.

llTime

Preroll time to be set.

Preroll time is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.


CPosPassThru::put_Rate

HRESULT put_Rate(double dRate);

Sets the rate of playback relative to normal speed.

•	Returns an HRESULT value.

dRate

The rate to set.

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. This will not be supported by all media.


CPosPassThru::put_StopTime

HRESULT put_StopTime(REFTIME llTime);

Sets the time at which the media stream will stop.

•	Returns an HRESULT value.

llTime

Stop time as a double value in seconds.

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.


CPosPassThru::QueryPreferredFormat

HRESULT QueryPreferredFormat(GUID *pFormat);

Retrieves the preferred time format to be used by the interface.

•	Returns an HRESULT value.

pFormat

Time format preferred by the interface.

This member function implements the IMediaSelection::QueryPreferredFormat method.

See the description for IMediaSelection::IsFormatSupported for a list of available time formats. If the time format returned is not satisfactory, use the IMediaSelection::IsFormatSupported method to query for supported time formats that you can use.


CPosPassThru::SetSelection

HRESULT SetSelection(LONGLONG Current, LONGLONG Stop);

Sets the time that the media stream begins and stops.

•	Returns an HRESULT value.

Current

Start time expressed as a LONGLONG value.

Stop

Stop time expressed as a LONGLONG value.

This member function implements the IMediaSelection::QueryPreferredFormat method.


CPosPassThru::SetTimeFormat

HRESULT SetTimeFormat(const GUID Format);

Sets the time format, which determines the format of units used during seeking.

•	Returns an HRESULT value.

Format

The time format to be supported by this interface.

This member function implements the IMediaSelection::SetTimeFormat method. See the IMediaSelection::IsFormatSupported method for a list of time formats.


CPullPin Class

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 ActiveMovie™ asynchronous reader filter just reads a media stream from a file and provides no parsing.

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.

DecideAllocator 	Proposes an allocator for use by the asynchronous reader.

Disconnect 	Breaks a connection to the asynchronous reader.

Duration 	Returns the total duration of the media stream.

GetReader 	Returns 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.

EndFlush 	Signals end of flushing operation.

EndOfStream 	Sens end-of-stream notification downstream.

OnError 	Handles run-time errors that have caused pulling to stop.

Receive 	Handles the arrival of data from the asynchronous reader.


CPullPin::Active

HRESULT Active(void);

Instructs the pin to start pulling data from the asynchronous reader.

•	Returns an HRESULT value.

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

LONGLONG AlignDown(LONGLONG ll, LONG lAlign);

Aligns a LONGLONG value down to the next LONG boundary.

•	Returns the ll value aligned to lAlign.

ll

Element to be aligned.

lAlign

Alignment boundary.

Aligning downwards is a truncation operation.


CPullPin::AlignUp

LONGLONG AlignUp(LONGLONG ll, LONG lAlign);

Aligns a LONGLONG value up to the next LONG boundary.

•	Returns an HRESULT value.

ll

Element to be aligned.

lAlign

Alignment boundary.


CPullPin::BeginFlush

virtual HRESULT BeginFlush(void);

Override to flush this pin and all downstream pins.

•	Returns an HRESULT value.

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

HRESULT Connect(IUnknown* pUnk,

    IMemAllocator* pAlloc, BOOL bSync);

Initiates a connection from this pin to the asynchronous reader.

•	Returns S_OK if successfully connected to the IAsyncReader interface from the object specified by pUnk.

pUnk

Object to query for existence of asynchronous reader (IAsyncReader).

pAlloc

Optional allocator to propose as preferred allocator if necessary.

bSync

Set TRUE if the reader uses synchronous rather than asynchronous reads.


CPullPin::CPullPin

CPullPin(void);

Constructs a CPullPin object.


CPullPin::DecideAllocator

HRESULT DecideAllocator(IMemAllocator* pAlloc,

    ALLOCATOR_PROPERTIES * pProps);

Negotiates an allocator to use with the asynchronous reader.

•	Returns an HRESULT value.

pAlloc

Allocator to propose as preferred allocator if necessary (optional). Pass NULL if not proposing allocator.

pProps

Size, count, and alignment of allocator (optional). Pass 0 if not requesting allocator properties.

This member function calls the IAsyncReader::RequestAllocator method to negotiate an allocator.


CPullPin::Disconnect

HRESULT Disconnect(void);

Breaks a connection to the asynchronous reader.

•	Returns NOERROR if there is no connection.

This member function disconnects any connection to an asynchronous file reader made in the CPullPin::Connect method.


CPullPin::Duration

HRESULT Duration(REFERENCE_TIME* ptDuration);

Returns the total duration of the media stream.

•	Returns an HRESULT value.

ptDuration

Duration in 100 nanosecond units.


CPullPin::EndFlush

virtual HRESULT EndFlush(void) PURE;

Override to signal the end of a flushing operation.

•	Returns an HRESULT value.

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

virtual HRESULT EndOfStream(void) PURE;

Override to send an end-of-stream notification downstream.

•	Returns an HRESULT value.

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

IAsyncReader* GetReader(void);

Returns the asynchronous reader.

•	Returns a reference-counted IAsyncReader interface.


CPullPin::Inactive

HRESULT Inactive(void);

Instructs the pin to stop pulling data from the asynchronous reader.

•	Returns an HRESULT value.

This member function calls the IAsyncReader::BeginFlush method, ends the thread, calls the IAsyncReader::EndFlush method and then decommits the allocator.


CPullPin::OnError

virtual void OnError(HRESULT hr) PURE;

Override to handle run-time errors that have caused pulling to stop.

hr

HRESULT value of the trapped error.

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

virtual HRESULT Receive(IMediaSample*) PURE;

Override this member function to handle the arrival of data from the asynchronous reader.

•	Returns an HRESULT value. Returning a value other than S_OK will stop the data.

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

HRESULT Seek(REFERENCE_TIME tStart,

    REFERENCE_TIME tStop);

Sets the start and stop times of the media stream.

•	Returns an HRESULT value.

tStart

Start time (defaults to zero).

tStop

Stop time (defaults to the value of CPullPin::Duration).

If the filter graph is running (active), the media rendering will start immediately at the new position defined by tStart.


CQueue Class

This class implements a simple Queue Abstract Data Type (ADT). The queue contains a finite number of objects, and a semaphore controls the access to these objects. The semaphore is created with an initial count (N). Each time an object is added, a call to the Microsoft® Win32® WaitForSingleObject function is made on the handle of the semaphore. When this function returns, it reserves a slot in the queue for the new object. If no slots are available, the member function blocks until it becomes available. Each time an object is removed from the queue, the Win32 ReleaseSemaphore function is called on the handle of the semaphore, thus freeing a slot in the queue. If no objects are present in the queue, the function blocks until an object has been added.

Member Functions

CQueue 	Constructs a CQueue object.

GetQueueObject 	Retrieves an object from the queue.

PutQueueObject 	Puts an object into the queue.


CQueue::CQueue

CQueue(int n);

CQueue();

Constructs a CQueue object.

n

Size of the queue to create.

If constructed with no parameters, the size of the queue is set to DEFAULT_QUEUESIZE.


CQueue::GetQueueObject

T GetQueueObject();

Retrieves an object from the queue.

•	Returns an object of type T (template).

This member function blocks until an object is available on the queue. It uses a CCritSec object for security.


CQueue::PutQueueObject

void PutQueueObject(T object);

Puts an object into the queue.

object

Template object to be inserted into the queue.

This member function blocks if there is not an open slot into which to put the object. It releases any blocking CQueue::GetQueueObject member function that is waiting for an object to retrieve.


CRefTime Class

This class is used to manage reference times. It shares the same data layout as the REFERENCE_TIME data type, but adds some (nonvirtual) functions that provide simple comparison, conversion, and arithmetic capabilities.

A reference time is a unit of time represented in 100-nanosecond (ns) units. This time unit is the same time unit used by the Microsoft® Win32® FILETIME structure, although the two types may not be interchanged. Note that the time a REFERENCE_TIME represents is not the time elapsed since 1/1/1601. It is either stream time or reference time, depending upon the context.

Data Members

m_time 	REFERENCE_TIME value of this object.

Member Functions

CRefTime 	Constructs a CRefTime object.

GetUnits 	Returns the reference time in units of 100 nanoseconds.

Millisecs 	Returns the reference time in milliseconds.

Operators

operator (REFERENCE_TIME) 	Casts the CRefTime object to a REFERENCE_TIME data type. The result is the m_time value.

operator = 	Implements the copy constructor for the CRefTime class.

operator += 	Adds two CRefTime objects and makes this object equal to the result.

operator -= 	Subtracts one CRefTime object from another CRefTime object and makes this object equal to the result.


CRefTime::CRefTime

inline CRefTime()

inline CRefTime(LONG msecs)

inline CRefTime(REFERENCE_TIME rt)

Constructs a CRefTime object.

(void)

Sets the new CRefTime value to zero.

msecs

Sets the new CRefTime value in milliseconds.

rt

Copies an existing CRefTime value for the new object.

When constructed without parameters, the reference time value defaults to zero.


CRefTime::GetUnits

inline LONGLONG GetUnits(void)

Returns the reference time in 100-nanosecond units.

•	Returns the reference time value.


CRefTime::Millisecs

inline LONG Millisecs(void)

Returns the reference time in milliseconds.

•	Returns the reference time value.


CRefTime::operator REFERENCE_TIME

inline operator REFERENCE_TIME() const

Cast operator that allows a CRefTime object to be used in place of a REFERENCE_TIME object. For example:

CRefTime cRT(1000);

REFERENCE_TIME rt = (REFERENCE_TIME)cRT;

•	Returns the value of m_time.


CRefTime::operator =

inline CRefTime& operator=(const CRefTime& rt)

inline CRefTime& operator=(const LONGLONG ll)

Assigns a new value to the object from an existing value.

•	Returns a reference to this object after the operation.

rt

Used to copy an existing CRefTime object.

ll

Used to copy a LONGLONG reference time value.


CRefTime::operator +=

inline CRefTime& operator+=(const CRefTime& rt)

Adds the value of another CRefTime object to this CRefTime object.

•	Returns a reference to this object.

rt

CRefTime object to be added.


CRefTime::operator -=

inline CRefTime& operator-=(const CRefTime& rt)

Subtracts another CRefTime object from this CRefTime object.

•	Returns the result.

rt

CRefTime object to be subtracted.


CRenderedInputPin Class

This input pin 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). For an example of a filter that uses this class, see the dump sample filter.

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

HRESULT Active();

Notifies the pin that the filter has changed state from stopped to paused.

•	Returns an HRESULT value.

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(TCHAR *pObjectName,

    CBaseFilter *pFilter, CCritSec *pLock, HRESULT *phr,

    LPCWSTR pName);

Constructs a CRenderedInputPin object.

pObjectName

Name of the object for debugging purposes.

pFilter

Pointer to the pin's owning filter.

pLock

Critical section for the pin.

phr

Pointer to an HRESULT value.

pName

Pin name.


CRenderedInputPin::EndFlush

HRESULT EndFlush(void);

Informs the pin to end a flush operation.

•	Returns an HRESULT value.

This member function overrides CBaseInputPin::EndFlush. It sets both m_bAtEndOfStream and m_bCompleteNotified to FALSE before calling the base class implementation.


CRenderedInputPin::EndOfStream

HRESULT EndOfStream(void);

Informs the pin that no additional data is expected until a new run command is issued.

•	Returns an HRESULT value.

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

HRESULT Run(REFERENCE_TIME tStart);

Notifies the pin that the filter has changed state from stopped to paused.

•	Returns an HRESULT value (S_OK by default).

tStart

Start time. Unreferenced by this class; for possible use by the derived class.

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

This input pin class channels calls to the rendering filter.

Protected Data Members

m_pRenderer 	Pointer to the CBaseRenderer object.

Member Functions

CRendererInputPin 	Constructs a CRendererInputPin object.

Overridable Member Functions

Active 	Switches the pin to the active (paused or running) mode.

BeginFlush 	Informs the pin to begin a flush operation.

BreakConnect 	Adds customized code upon breaking a connection.

CheckMediaType 	Determines if the pin can support a specific media type.

CompleteConnect 	Completes the connection.

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.

Inactive 	Switches the pin to an inactive state and releases the memory of the allocator.

Receive 	Returns the next block of data from the stream.

SetMediaType 	Sets the media type of the pin.

Implemented IPin Methods

QueryId 	Retrieves an identifier for the pin.


CRendererInputPin::Active

HRESULT Active();

Switches the pin to the active (paused or running) mode.

•	Returns an HRESULT value.

This member function overrides CBasePin::Active and calls the renderer filter's CBaseRenderer::Active member function.


CRendererInputPin::BeginFlush

HRESULT BeginFlush();

Informs the pin to begin a flush operation.

•	Returns an HRESULT value.

This member function implements the IPin::BeginFlush method. It overrides CBaseInputPin::BeginFlush and calls the renderer filter's BeginFlush member function before calling the base class implementation.


CRendererInputPin::BreakConnect

HRESULT BreakConnect();

Override this member function to add customized code upon breaking a connection.

•	Returns an HRESULT value.

This member function overrides CBasePin::BreakConnect and calls the renderer filter's BreakConnect member function before calling the base class implementation.


CRendererInputPin::CheckMediaType

HRESULT CheckMediaType(const CMediaType *pmt);

Override this member function to determine if the pin can support this specific media type.

•	Returns an HRESULT value.

pmt

Pointer to a media type object that contains the proposed media type.

This member function is typically called before calling the CRendererInputPin::SetMediaType member function.

This member function overrides CBasePin::CheckMediaType and calls the pure virtual CBaseRenderer::CheckMediaType member function, which must be overridden.


CRendererInputPin::CompleteConnect

HRESULT CompleteConnect(IPin *pReceivePin);

Override this member function to inform the derived class when the connection process has completed.

•	Returns an HRESULT value.

pReceivePin

Pointer to the connected (receiving) pin.

This member function overrides CBasePin::CompleteConnect and calls the renderer filter's CompleteConnect member function before calling the base class implementation.


CRendererInputPin::CRendererInputPin

CRendererInputPin(CBaseRenderer *pRenderer,

    HRESULT *phr, LPCWSTR Name);

Constructs a CRendererInputPin object.

pRenderer

Pointer to the rendering filter in the base class.

phr

Pointer to an HRESULT value.

Name

Pin name.


CRendererInputPin::EndFlush

HRESULT EndFlush(void);

Informs the pin to end a flush operation.

•	Returns an HRESULT value.

This member function overrides CBaseInputPin::EndFlush and calls the renderer filter's EndFlush member function before calling the base class implementation.

Note that because this is a renderer, it does not pass the flush on downstream.


CRendererInputPin::EndOfStream

HRESULT EndOfStream(void);

Informs the pin that no additional data is expected until a new run command is issued.

•	Returns an HRESULT value.

This member function implements the IPin::EndOfStream method. It calls CheckStreaming to see that the filter is in a streaming state and then calls the CBaseRenderer::EndOfStream member function.


CRendererInputPin::Inactive

HRESULT Inactive(void);

Informs the pin that it is going into the inactive state.

•	Returns an HRESULT value.

This member function overrides CBaseInputPin::Inactive. It calls the renderer filter's CBaseRenderer::Inactive member function, which returns NOERROR by default.


CRendererInputPin::QueryId

HRESULT QueryId(LPWSTR *Id);

Retrieves an identifier for the pin.

•	Returns an HRESULT value.

Id

Pin identifier.

This member function implements the IPin::QueryId method. It overrides the CBasePin::QueryId member function and assigns the string "In" to Id. Note that it uses the Microsoft® Win32® CoTaskMemAlloc function to initialize Id, so the user is responsible for freeing the format block by using CoTaskMemFree.


CRendererInputPin::Receive

HRESULT Receive(IMediaSample *pMediaSample);

Returns the next block of data from the stream.

•	Returns an HRESULT value.

pMediaSample

Media sample.

This member function implements the IMemInputPin::Receive method, and it overrides the CBaseInputPin::Receive member function, which it calls to verify formats.

This is a blocking synchronous member function. It blocks and waits until it is time for the sample to be rendered. (It calls CBaseRenderer::Receive, which actually does the blocking.) Because only one sample is ever outstanding, this member function checks the media type and calls CRendererInputPin::SetMediaType to change the pin's media type if the sample's type has changed.

Call the IUnknown::AddRef method if you need to hold the returned data block beyond the completion of the CRendererInputPin::Receive member function. If you call AddRef, be sure to call the IUnknown::Release method upon completion of AddRef.


CRendererInputPin::SetMediaType

HRESULT SetMediaType(const CMediaType *pmt);

Override this member function to set the media type of the pin.

•	Returns an HRESULT value.

pmt

Pointer to a media type object that was previously agreed upon.

This member function overrides CBasePin::SetMediaType and calls the renderer filter's SetMediaType member function, which returns NOERROR by default, after calling the base class implementation.


CRendererPosPassThru Class

The IMediaSelection interface is used to seek to a specific sample, frame, or indexed field. These values are indicated by a whole number, such as frame 20 of a sequence of 530. However, when asked for a reference start or end time (in seconds), the sample needs to have this information previously set. The CRendererPosPassThru class, implemented on the video renderer, performs this service because the renderer is responsible for keeping track of reference time and stream time.

Member Functions

CRendererPosPassThru 	Constructs a CRendererPosPassThru object.

GetMediaTime 	Returns the media start and end times registered in the object.

RegisterMediaTime 	Registers the media start and end times with the object.

ResetMediaTime 	Resets the object's media start and end times.


CRendererPosPassThru::CRendererPosPassThru

CRendererPosPassThru(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT * phr, IPin * pPin);

Constructs a CRendererPosPassThru object.

pName

Name of the object used in the CRendererPosPassThru constructor for debugging purposes.

pUnk

Pointer to the owner of this object.

phr

Pointer to an HRESULT value for resulting information.

pPin

Pointer to the input pin for the filter.

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.


CRendererPosPassThru::GetMediaTime

HRESULT GetMediaTime(LONGLONG* pStartTime,

    LONGLONG* pEndTime);

Retrieves the current media start and end times registered in the object.

•	Returns an HRESULT value.

pStartTime

The returned starting media time.

pEndTime

The returned ending media time.

This member function returns the media times set by the CRendererPosPassThru::RegisterMediaTime member function. The starting media time is always returned. Set pEndTime to a nonzero value to retrieve the ending media time.


CRendererPosPassThru::RegisterMediaTime

HRESULT RegisterMediaTime(IMediaSample *pMediaSample),

    HRESULT RegisterMediaTime(LONGLONG pStartTime,

    LONGLONG pEndTime);

Registers the media start and end times with the object.

•	Returns an HRESULT value. Returns VFW_E_MEDIA_TIME_NOT_SET if the sample does not have its media times set.

pMediaSample

An IMediaSample object containing the media times.

pStartTime

The returned starting media time.

pEndTime

The returned ending media time.


CRendererPosPassThru::ResetMediaTime

HRESULT ResetMediaTime(void);

Resets the object's media start and end times.

•	Returns an HRESULT value.

Sets the start and stop times to zero.


CSource Class

This class and its corresponding class, CSourceStream, simplify the construction of source filters that produce continuous streams of data comparable to the way the CTransformFilter class assists in the creation of transform filters.

The CSource class provides a wrapper for the CBaseFilter class that performs the pin management and works with the CSourceStream class to provide the pins.

To use the CSource class to build a filter:

•	Derive your filter-level class from the CSource class. Provide CreateInstance in it to create a new object of the class.

•	Provide a means of adding objects that are derived from the CSourceStream class to support the output pins during construction of the class. You can either create them yourself during construction or provide the developer with a means of creating them later.

For an example of using the CSource class, see the BALL sample in the \SAMPLES\BALL directory of the Microsoft® ActiveMovie™ Software Development Kit (SDK).

This class does not help build an asynchronous file reader source filter, which requires support of an IAsyncReader interface and a downstream parser filter that supports the CPullPin class.

Protected Data Members

m_cStateLock 	Locks this data member to serialize access to the filter state.

m_iPins 	Number of pins on this filter; updated by the CSource::AddPin and CSource::RemovePin member functions.

m_paStreams 	Array of streams associated with this filter.

Member Functions

AddPin 	Adds a pin to the source filter.

CSource 	Constructs a CSource object.

FindPinNumber 	Retrieves the number of the pin through the IPin parameter.

GetPin 	Returns a pointer to a specified pin.

GetPinCount 	Gets the number of pins contained by the filter.

pStateLock 	Returns a pointer to the filter-critical section.

RemovePin 	Removes a pin from the source filter.

Implemented IFilter Methods

FindPin 	Retrieves a pointer to the pin with the specified identifier.


CSource::CSource

CSource(TCHAR *pName, LPUNKNOWN lpunk, CLSID clsid, HRESULT *phr);

Initializes the CSource object.

pName

Debugging name of this object.

lpunk

Controlling IUnknown passed to the CreateInstance function.

clsid

Class identifier of the filters.

phr

Resulting value for this constructor.

The derived class could create the pins here, unless it provides a means for the developer to do this.


CSource::AddPin

HRESULT AddPin(CSourceStream * pStream);

Adds a pin to the source filter.

•	Returns S_OK if successful, or E_OUTOFMEMORY if no memory is available.

pStream

Pointer to the CSourceStream object associated with the pin.


CSource::FindPinNumber

int FindPinNumber(IPin *iPin);

Retrieves the number of the pin supporting a given IPin interface.

•	Returns the pin number or -1 if no matching pin number is found.

iPin

IPin interface of the pin to retrieve.


CSource::GetPin

CBasePin *GetPin(int n);

Returns a pointer to the specified pin.

•	Returns the pointer to the pin or NULL if the index is out of range.

n

Pin number of the requested pin.

This member function is specified in CBaseFilter and is implemented here. Note that this pin interface will not have been reference counted when obtained.


CSource::GetPinCount

int GetPinCount(void) ;

Retrieves the number of pins contained by the filter.

•	Returns the pin count.

This member function is specified in CBaseFilter and is implemented here.


CSource::pStateLock

CCritSec* pStateLock(void);

Retrieves a pointer to the filter-critical section.

•	Returns the critical section.

Locking consists of holding the filter-critical section by calling the pStateLock member function and using the returned object to serialize access to functions. Typically, this lock may be held by a function when the worker thread may want to hold it. Therefore, to access a shared state from the worker thread, add another critical-section object. The exception occurs during the processing loop of the thread when it is safe to retrieve the filter-critical section from within CSourceStream::FillBuffer.


CSource::RemovePin

HRESULT RemovePin(CSourceStream * pStream);

Removes a pin from the source filter.

•	Returns S_OK if successful or S_FALSE if unsuccessful.

pStream

CSourceStream object associated with the pin.

The pStream parameter is not deleted. This member function adjusts pin locations in the m_paStreams array.


CSourcePosition Class

CSourcePosition is an abstract class that assists source filters with the implementation of IMediaPosition methods.

Derive from this class and set the duration and default stop positions. This class supports IMediaPosition, and calls the pure virtual member functions CSourcePosition::ChangeStart, CSourcePosition::ChangeStop, and CSourcePosition::ChangeRate when CSourcePosition::put_CurrentPosition, CSourcePosition::put_StopTime, or CSourcePosition::put_Rate is called, to allow a source filter to handle these commands and start sending new data.

Override the CSourcePosition::ChangeStart, CSourcePosition::ChangeStop, and CSourcePosition::ChangeRate member functions to do something when the properties change.

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_Duration 	Retrieves the total duration of the media.

get_PrerollTime 	Retrieves the time prior to the start position that the filter graph will start any nonrandom access device rolling.

put_PrerollTime 	Sets the time prior to the start position that the filter graph will start any nonrandom access device rolling.

get_Rate 	Retrieves the playback rate, relative to normal playback of the media.

put_Rate 	Sets the playback rate, relative to normal playback of the media.

get_CurrentPosition 	Retrieves the position within the media at which playback will start.

put_CurrentPosition 	Sets the position within the media at which playback should start.

get_StopTime 	Retrieves the position within the media at which playback should stop.

put_StopTime 	Sets the position within the media at which playback should stop.


CSourcePosition::ChangeRate

virtual HRESULT ChangeRate() PURE;

Override this member function to handle notification of a change of sample rate.

•	Returns an HRESULT value.

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

virtual HRESULT  ChangeStart() PURE;

Override this member function to handle notification of a change of start time.

•	Returns an HRESULT value.

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

virtual HRESULT ChangeStop() PURE;

Override this member function to handle notification of a change in stop time.

•	Returns an HRESULT value.

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(TCHAR *pName, LPUNKNOWN pUnk,

    HRESULT * phr, CCritSec * pCritSec);

Constructs a CSourcePosition object.

pName

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.

pCritSec

Pointer to a CCritSec object used for locking.

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.


CSourcePosition::get_CurrentPosition

HRESULT get_CurrentPosition(REFTIME* pllTime);

Retrieves the position within the stream at which playback should begin.

•	Returns an HRESULT value.

pllTime

The returned start time as a double value in seconds.

The start position is applied before the rate and therefore is the position at typical playback speed.


CSourcePosition::get_Duration

HRESULT get_Duration(REFTIME* plength);

Retrieves the total duration of the media stream.

•	Returns an HRESULT value.

plength

The returned length of the media stream.

The duration assumes normal playback speed; it is therefore unaffected by the rate.


CSourcePosition::get_PrerollTime

HRESULT get_PrerollTime(REFTIME* pllTime);

Retrieves the time prior to the start position that devices should start rolling.

•	Returns an HRESULT value.

pllTime

Returned preroll time as a double value in seconds.

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

HRESULT get_Rate(double * pdRate);

Retrieves the rate of playback relative to normal playback speed.

•	Returns an HRESULT value.

pdRate

Returned rate.

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

HRESULT get_StopTime(REFTIME* pllTime);

Retrieves the time at which the media stream stops.

•	Returns an HRESULT value.

pllTime

The returned stop time as a double value in seconds.

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

HRESULT put_CurrentPosition(REFTIME llTime);

Sets the time within the media stream that playback should begin.

•	Returns an HRESULT value.

llTime

Start time expressed as a double value in seconds.

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

HRESULT put_PrerollTime(REFTIME llTime);

Sets the time prior to the start position that devices should start rolling.

•	Returns an HRESULT value.

llTime

Preroll time to be set.

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

HRESULT put_Rate(double dRate);

Sets the rate of playback relative to normal speed.

•	Returns an HRESULT value.

dRate

The rate to set.

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. This will not be supported by all media.


CSourcePosition::put_StopTime

HRESULT put_StopTime(REFTIME llTime);

Sets the time at which the media stream will stop.

•	Returns an HRESULT value.

llTime

Stop time as a double value in seconds.

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.


CSourceStream Class

Derive from this class to provide a class that creates the data stream from one of the output pins. It should be used with an object that is derived from the CSource class derived object to provide the filter-level object.

The CSourceStream class creates a worker thread to push data downstream when the filter enters a paused or running state. The thread first calls the CSourceStream::OnThreadCreate member function. If this succeeds, it will loop, calling the CSourceStream::FillBuffer member function until the CSourceStream::Inactive member function stops it. As the thread quits, it calls the CSourceStream::OnThreadDestroy member function. If OnThreadCreate fails, OnThreadDestroy is called, and the active member function will fail.

To use the CSourceStream class, supporting a single media type, carry out the following steps:

1	Override the CSourceStream::GetMediaType member function to report the supported output format.

2	Override the CSourceStream::FillBuffer member function with a means of filling out each IMediaSample object with data.

To use the CSourceStream class, supporting multiple media types, carry out the following:

1	Override the CSourceStream::CheckMediaType and CSourceStream::GetMediaType member functions to report the supported media types (for more information, see the CBaseMediaFilter class).

2	Override the CSourceStream::FillBuffer member function with a means of filling out each IMediaSample object with data.

See SAMPLES\BALL in the Microsoft® ActiveMovie™ Software Development Kit (SDK) for an example of a pin supporting multiple types.

If you want more complex management of your worker thread, you can override most of the associated member functions. See SAMPLES\VIDCAP in the Microsoft ActiveMovie Software Development Kit (SDK) for an example.

Member Functions

Active 	Called by the CBaseMediaFilter class to start the worker thread.

CSourceStream 	Constructs a CSourceStream object.

CheckRequest 	Determines if a command is waiting for the thread.

Exit 	Called by the CSourceStream::Inactive member function to exit the worker thread.

GetRequest 	Retrieves the next command for the thread.

Inactive 	Called by the CBaseMediaFilter member function to shut down the worker thread.

Init 	Called by the CSourceStream::Active member function to initialize the worker thread.

Pause 	Pauses the stream of the worker thread. This will acquire all necessary resources.

Run 	Starts the worker thread generation of a media sample stream.

Stop 	Stops the stream.

Overridable Member Functions

CheckMediaType 	Determines if a specific media type is supported. Override this member function if you use multiple types.

DoBufferProcessingLoop 	Loops, collecting a buffer and calling the CSourceStream::FillBuffer processing function.

FillBuffer 	Override this member function to fill the stream buffer during the creation of a media sample.

GetMediaType 	Retrieves the media type or types that this pin supports; override the appropriate version of this member function to support one or multiple media types.

OnThreadCreate 	Called as the worker thread is created; override this member function for special processing.

OnThreadDestroy 	Called during the destruction of a worker thread; override this member function for special processing.

OnThreadStartPlay 	Called at the start of processing Pause or Run command; override this member function for special processing.

ThreadProc 	Override this member function to create a custom thread procedure.

Implemented IPin Methods

QueryId 	Retrieves an identifier for the pin.


CSourceStream::Active

HRESULT Active(void);

Starts the worker thread.

•	Returns an HRESULT value, including the following values.

Value 	Meaning

S_OK 	Thread was started successfully.

S_FALSE 	Pin is already active.

E_FAIL 	Thread could not start.


CSourceStream::CheckMediaType

virtual HRESULT CheckMediaType(CMediaType *pMediaType);

Determines if this pin supports the supplied media type.

•	Returns an HRESULT value, which may include the following.

Value 	Meaning

S_OK 	Media type is acceptable.

E_INVALIDARG 	Media type is not acceptable.

pMediaType

Media type to check.

Override this member function if you support multiple media types.


CSourceStream::CheckRequest

BOOL  CheckRequest(Command *pCom);

Determines if a command is waiting for the thread.

•	Returns TRUE if the pCom parameter contains a command; otherwise, returns FALSE.

pCom

Pointer to the location to which to return a command, if any.

This member function does not block. This is a type safe override of the method in the CThread class.


CSourceStream::CSourceStream

CSourceStream(TCHAR *pObjectName,

                  HRESULT *phr,

                  CSource *pms,

                  LPCWSTR pName);

Creates a CSourceStream object.

pObjectName

Name of the object.

phr

Resulting value for this constructor.

pms

Pointer for the CSource object.

pName

Name of the pin.


CSourceStream::DoBufferProcessingLoop

virtual HRESULT DoBufferProcessingLoop(void);

Loops, collecting a buffer and calling the CSourceStream::FillBuffer processing function.

•	Returns an HRESULT value.


CSourceStream::Exit

HRESULT Exit(void);

Causes the thread to exit.

•	Returns NOERROR if the member function was received.

If the thread returns an error, it sets the return value of the CSourceStream::ThreadProc member function.


CSourceStream::FillBuffer

 virtual HRESULT FillBuffer(IMediaSample *pSample) PURE;

Fills the stream buffer during the creation of a media sample that the current pin provides.

•	Returns an HRESULT value.

pSample

IMediaSample buffer to contain the data.

The CSourceStream::ThreadProc member function calls the CSourceStream::FillBuffer member function. The derived class must supply an implementation of this member function.


CSourceStream::GetMediaType

virtual HRESULT GetMediaType(int iPosition, CMediaType *pMediaType);

virtual HRESULT GetMediaType(CMediaType *pMediaType);

Fills out the fields of the CMediaType object to the supported media type.

•	Returns one of the following HRESULT values.

Value 	Meaning

S_OK 	Media type was set.

VFW_S_NO_MORE_ITEMS 	End of the list of media types has been reached.

S_FALSE 	Media type exists but is not currently usable.

Error Code 	Media type could not be set.

iPosition

Position of the media type within a list of multiple media types. Range is zero through n.

pMediaType

Pointer to a CMediaType object to be set to the requested format.

This member function sets the requested media type. If only a single media type is supported, override this member function with the single-parameter definition. Only the default implementations of the CSourceStream::CheckMediaType and CSourceStream::GetMediaType member functions call this member function. Override the single-version GetMediaType or the two-parameter version, CheckMediaType.


CSourceStream::GetRequest

Command GetRequest(void);

Retrieves the next command for the thread.

•	Returns the next command.

This member function blocks until a command is available. It is a type safe override of the member function in the CThread class.


CSourceStream::Inactive

HRESULT Inactive(void);

Identifies a pin as inactive and shuts down the worker thread.

•	Returns an HRESULT value, including the following values.

Value 	Meaning

S_OK 	Thread exited successfully.

S_FALSE 	Pin is already inactive.


CSourceStream::Init

HRESULT Init(void);

Initializes the worker thread.

•	Returns an HRESULT value, including the following values.

Value 	Meaning

S_OK 	Thread was initialized successfully.

S_FALSE 	Thread was already initialized.

The CSourceStream::Active member function calls this member function.


CSourceStream::OnThreadCreate

virtual HRESULT OnThreadCreate(void);

Starts or stops a process upon the creation of a thread.

•	Returns an HRESULT value, including the following values.

Value 	Meaning

NOERROR 	No error occurred.

Error code 	Thread should exit.


CSourceStream::OnThreadDestroy

virtual HRESULT OnThreadDestroy(void);

Starts or stops a process upon the destruction of a thread.

•	Returns either NOERROR or an HRESULT value (greater than zero) that indicates an error.


CSourceStream::OnThreadStartPlay

virtual HRESULT OnThreadStartPlay(void);

Starts a process upon the beginning of the playing of the thread.

•	Default implementation returns NOERROR.


CSourceStream::Pause

HRESULT Pause(void);

Pauses a media sample stream.

•	Returns an HRESULT value, including the following value.

Value 	Meaning

S_OK 	Thread paused successfully.


CSourceStream::Run

HRESULT Run(void);

Starts a media sample stream.

•	Returns S_OK if successful; otherwise, returns an HRESULT error value.


CSourceStream::Stop

HRESULT Stop(void);

Stops a media sample stream.

•	Returns S_OK if successful; otherwise, returns an HRESULT error value.


CSourceStream::ThreadProc

virtual DWORD ThreadProc(void);

Implements the thread procedure.

•	Returns one of the following values.

Value 	Meaning

0 	Thread completed successfully.

1 	Thread did not complete successfully. It may have left resources allocated.

When this member function returns, the thread exits. Override this member function if the provided version is not sophisticated enough.

See \SAMPLES\VIDCAP in the Microsoft ActiveMovie Software Development Kit (SDK) for an example.


CSystemClock Class

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 actual time calls.

CSystemClock also 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.

Overridden CBaseReferenceClock Methods

GetTime 	Returns the current reference time in 100-nanosecond units.

SetTimeDelta 	Adjusts the values returned from CSystemClock::GetTime by the amount specified in this member function.

Implemented IPersist Methods

GetClassID 	Returns the class identifier of this clock.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Passes out pointers to any interfaces.


CSystemClock::CreateInstance

static CUnknown *CreateInstance(LPUNKNOWN pUnk,

    HRESULT *phr);

Creates a new instance when placed in the factory template table.

•	Returns a pointer to a new Component Object Model (COM) object.

pUnk

Pointer to LPUNKNOWN.

phr

Pointer to an HRESULT value in which to return resulting information.

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(TCHAR *pName, LPUNKNOWN pUnk, HRESULT *phr);

Constructs a CSystemClock object.

pName

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.

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

HRESULT GetClassID(CLSID *pClsID);

Retrieves the class identifier for this clock.

•	Returns an HRESULT value.

pClsID

Pointer to a CLSID structure.


CSystemClock::GetTime

HRESULT GetTime(REFERENCE_TIME *pTime);

Retrieves the current reference time.

•	Returns an HRESULT value.

pTime

REFERENCE_TIME variable that will be updated with the current time in 100-nanosecond units.

This member function overrides the pure virtual CBaseReferenceClock::GetTime member function. It reads the time from the implemented clock and returns the current time.


CSystemClock::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IReferenceClock, IPersist, and IUnknown interfaces.


CSystemClock::SetTimeDelta

HRESULT SetTimeDelta(REFERENCE_TIME& TimeDelta);

Sets a delta on the value that the system clock will return. Note that the code will never return a time earlier than the previously returned time. Thus, if you set the clock to a time in the past, successive calls to CSystemClock::GetTime will return the current value until this new time is reached, and then the clock will start to increment again.

•	Returns an HRESULT value.

TimeDelta

REFERENCE_TIME delta that will be added to the clock before returning values.

This member function overrides the pure virtual CBaseReferenceClock::SetTimeDelta member function. This member function allows derived clocks to periodically adjust the system clock value, typically to alter the perceived rate at which the clock is running in order to synchronize with a device clock. This member function is protected.


CThread Class

CThread is an abstract class, a worker thread class that provides creation, synchronization, and communication with a worker thread. The worker thread can be accessed from several client threads. The class provides member functions to create the thread, pass commands to it, and wait for it to exit.

Use a CCritSec object to ensure that only one thread can make a request at a time. Use two CAMEvent objects: one to signal to the worker that a request is outstanding, and the other to signal to the client thread that the request has been completed. A nonblocking CThread::CheckRequest member function allows the worker thread to check for new requests while working asynchronously.

Derive from this class to provide your own thread member function. You may also want to provide type-safe signaling member functions that package parameters and return values using the CThread::CallWorker member function.

Thread creation is independent of object creation. Create a member variable derived from CThread, and then use the member functions to start and stop the thread when needed.

Data Members

m_AccessLock 	Critical section object that locks access by client threads.

m_WorkerLock 	Critical section object that locks access to shared objects.

Member Functions

CallWorker 	Makes a request to the worker thread.

CheckRequest 	Determines if there is an outstanding request. This is a nonblocking member function.

Close 	Blocks until the thread has exited and released its resources.

Create 	Starts the thread running.

CThread 	Constructs a CThread object.

GetRequest 	Blocks until the next request is made and then returns a DWORD value.

GetRequestHandle 	Returns an event handle.

GetRequestParam 	Returns the latest request.

InitialThreadProc 	Retrieves a this parameter. Carry out this member function before calling the CThread::ThreadProc member function.

Reply 	Returns a DWORD value to the requesting thread and releases it, signaling completion of the request.

ThreadExists 	Determines whether a thread exists or has exited.

ThreadProc 	Indicates a pure virtual member function that is called on the worker thread.


CThread::CallWorker

DWORD CallWorker(DWORD dw);

Makes a request to the worker thread and blocks for a response.

•	Returns a value that is defined by the derived class.

dw

The derived class defines the meaning of the parameter.

This member function uses a CCritSec object to ensure that only one request is made at a time. It is therefore not valid to call the CThread::CallWorker member function from the thread itself or from any member function that is executing in the context of the thread.


CThread::CheckRequest

BOOL CheckRequest(DWORD *pParam);

Determines if there is an outstanding request. This is a nonblocking member function.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Outstanding request is still active.

FALSE 	No request is active.

pParam

Parameter that assumes the value passed by the last call to the CThread::CallWorker member function.

If there is an outstanding request, the requesting thread will block until the CThread::GetRequest member function is called. The request remains outstanding (that is, this member function continues to return TRUE) until either the CThread::Reply or CThread::GetRequest member function is called.


CThread::Close

void Close(void);

Blocks until the thread has exited and its resources have been released.

You must instruct the thread to exit by some other means; for example, call the CThread::CallWorker member function with a request that is interpreted by the derived class to mean complete and exit.

If the thread is still running when the CThread object is destroyed, the CThread::Close member function is called internally.


CThread::Create

BOOL Create(void);

Starts the thread running.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Thread was successfully started.

FALSE 	Thread is already running.

This member function creates the thread and calls the CThread::ThreadProc member function from the derived class.


CThread::CThread

CThread();

Constructs a CThread object.

Creates a CThread object but does not create an actual thread. This is carried out by calling the CThread::Create member function.


CThread::GetRequest

DWORD GetRequest();

Blocks until the next request is made.

•	Returns a value that is defined by the derived class.

This member function blocks the requesting thread until the CThread::Reply function is called.


CThread::GetRequestHandle

HANDLE GetRequestHandle() const;

Returns an event handle for performance improvements.

•	Returns an event handle.

To use the Microsoft Win32 WaitForMultipleObjects function, you will need this handle in the thread's wait list or the thread will not be responsive.


CThread::GetRequestParam

DWORD GetRequestParam() const;

Returns the most recent request.

•	Returns a DWORD that indicates the request made previously by the CThread::GetRequest member function.


CThread::InitialThreadProc

DWORD InitialThreadProc(LPVOID pv);

Receives a this pointer and calls the CThread::ThreadProc member function.

•	Returns the DWORD returned by CThread::ThreadProc. This DWORD is not defined by this class.

pv

The this pointer.


CThread::Reply

void Reply(DWORD dw);

Returns a DWORD value to the requesting thread and releases it, signaling completion of the request.

dw

Value returned by the CThread::CallWorker member function on the client side.


CThread::ThreadExists

BOOL ThreadExists();

Determines whether the thread has been created and has not yet exited.

•	Returns one of the following values.

Value 	Meaning

TRUE 	Thread exists and has not exited.

FALSE 	Thread does not exist.


CThread::ThreadProc

virtual DWORD ThreadProc();

Overridden member function in which to implement a thread.

•	The meaning of this return value is not defined by the CThread class.

The thread calls this member function upon startup. Derived classes must override this member function. When this member function returns, the thread terminates. This member function is protected.


CTransformFilter Class

CTransformFilter is an abstract base class that supports a simple transform filter with a single input and a single output. It is derived from the CUnknown class, and it supports the IFilter interface. Each pin, declared as Friends in this class, supports the IPin interface and uses the shared memory transport based on the IMemInputPin interface. The filter uses classes derived from the CBaseFilter class to support IFilter; the CTransformInputPin input pin class is derived from the CBaseInputPin class, and the CTransformOutputPin output pin class is derived from the CBaseOutputPin class.

Note that, while most member functions in this class are designed to be overridden, the following pure virtual member functions must be overridden:

•	CheckInputType

•	CheckTransform

•	DecideBufferSize

•	GetMediaType

•	Transform

For more information about using this class to create a transform filter, see Creating a Transform Filter.

Protected Data Members

m_idTransform 	Identifier used for performance measurement.

m_pInput 	Pointer to the input pin class object.

m_pOutput 	Pointer to the output pin class object.

m_csFilter 	Critical section that protects the filter state. This critical section is held whenever the state is currently changing or might change. It is passed to the CBaseMediaFilter constructor so that the base class uses it too.

m_csReceive 	Critical section that is held when processing events that occur on the receiving thread (CTransformInputPin::Receive and CTransformInputPin::EndOfStream).

m_bEOSDelivered 	End-of-stream delivery status flag.

m_bSampleSkipped 	Status flag that indicates if a frame was skipped.

m_bQualityChanged 	Status flag that indicates if the stream has degraded. This is set to TRUE in CTransformFilter::Receive if the call to the derived class Transform member function fails (CTransformFilter::Receive returns NOERROR in this case because returning S_FALSE indicates that the end-of-stream has arrived).

Member Functions

CTransformFilter 	Constructs a CTransformFilter object.

Overridable Member Functions

AlterQuality 	Receives a quality-control notification from the output pin and provides an opportunity to alter the quality of the media stream.

BeginFlush 	Receives notification of entering the flushing state and passes it downstream.

BreakConnect 	Informs the derived class when the connection is broken.

CheckConnect 	Informs the derived class when the connection process is starting.

CheckInputType 	Verifies that the input pin supports the media type and proposes the media type of the output pin (pure virtual).

CheckTransform 	Verifies that the input and output pins support the media type (pure virtual).

CompleteConnect 	Informs the derived class when the connection process has completed.

DecideBufferSize 	Sets the number and size of buffers required for the transfer (pure virtual).

EndFlush 	Receives notification of leaving the flushing state and passes it downstream.

EndOfStream 	Receives an end-of-stream notification and passes it downstream.

GetMediaType 	Returns one of the media types that the output pin supports (pure virtual).

GetPin 	Returns the pin for the index specified.

GetPinCount 	Returns the number of pins on the filter.

NewSegment 	Informs the derived class that a new segment has started and delivers it downstream.

Receive 	Receives the media sample, calls the CTransformFilter::Transform member function, and then delivers the media sample.

RegisterPerfId 	Registers a performance measurement identifier.

SetMediaType 	Informs the derived class when the media type is established for the connection.

StartStreaming 	Informs the derived class that streaming is starting.

StopStreaming 	Informs the derived class that streaming is ending.

Transform 	Performs transform operations, reading from the input IMediaSample interface and writing the data to the output IMediaSample interface (pure virtual).

Implemented IFilter Methods

FindPin 	Retrieves the pin with the specified identifier.

Stop 	Transitions the filter to State_Stopped state if it is not in this state already, and informs the derived class.

Pause 	Transitions the filter to State_Paused state if it is not in this state already, and informs the derived class.


CTransformFilter::AlterQuality

virtual HRESULT AlterQuality(Quality q);

Receives a quality-control notification and provides an opportunity to alter the quality of the media stream.

•	Returns an HRESULT value. S_FALSE means to pass the message to the upstream filter (whether or not any action has been taken). An overriding member function can return NOERROR to indicate that the message has been handled completely (or as completely as possible) and no further action should be taken.

q

A quality-control notification message.

This member function returns S_FALSE by default. It is called by the CTransformOutputPin::Notify member function before calling the CTransformInputPin::PassNotify member function to pass the quality control message upstream. If the filter is responsible for affecting the quality of the media stream, override this member function and respond to the quality-notification message.


CTransformFilter::BeginFlush

virtual HRESULT BeginFlush();

Receives notification of entering the flushing state and passes it downstream.

•	Returns an HRESULT value.

By default, this member function calls the CBaseOutputPin::DeliverEndFlush member function on the output pin to send the BeginFlush notification to the next filter. Override this member function if you are using queued data or a worker thread.


CTransformFilter::BreakConnect

virtual HRESULT BreakConnect(PIN_DIRECTION dir);

Informs the derived class when the connection is broken.

•	Returns NOERROR by default. The overriding member function returns an HRESULT value.

dir

Direction of the pin.

This member function is called by both CTransformInputPin::BreakConnect and CTransformOutputPin::BreakConnect. It returns NOERROR by default. Override this member function to handle special cases in both input and output pin connections. Special cases might typically be releasing interfaces obtained in the CTransformFilter::CheckConnect member function.


CTransformFilter::CheckConnect

virtual HRESULT CheckConnect(PIN_DIRECTION dir,

    IPin *pPin);

Informs the derived class when the connection process is starting.

•	Returns NOERROR by default. The overriding member function returns an HRESULT value.

dir

Direction of the pin.

pPin

Pointer to the pin making the connection.

This member function is called by both CTransformInputPin::CheckConnect and CTransformOutputPin::CheckConnect. It returns NOERROR by default. Override this member function to handle special cases in both input and output pin connections. Special cases might include querying (obtaining) other interfaces.


CTransformFilter::CheckInputType

virtual HRESULT CheckInputType(const CMediaType* mtIn)

    PURE;

Verifies that the input pin supports the media type, and proposes the media type for the output pin.

•	The overriding member function returns an HRESULT value.

mtIn

Pointer to an input media type object.

You must override this member function to verify the media type. This member function must return an error if it cannot support the media type as an input. If it can, the overriding member function should propose the output media type supplied by the output pin.


CTransformFilter::CheckTransform

virtual HRESULT CheckTransform(const CMediaType* mtIn,

    const CMediaType* mtOut) PURE;

Verifies that the input and output pins support the media type.

•	The overriding member function returns an HRESULT value.

mtIn

Pointer to the input media type object.

mtOut

Pointer to the output media type object.

The derived class must implement this member function by overriding it. It should return an error if the filter cannot accept these types as its input and output types.


CTransformFilter::CompleteConnect

virtual HRESULT CompleteConnect(PIN_DIRECTION direction,

    IPin *pReceivePin);

Informs the derived class when the connection process has completed.

•	Returns an HRESULT value.

direction

The pin direction.

pReceivePin

Pointer to the output pin that is being connected to.

This member function is called by both CTransformInputPin::CompleteConnect and CTransformOutputPin::CompleteConnect. It returns NOERROR by default. Override this member function to handle special cases in both input and output pin connections.


CTransformFilter::CTransformFilter

CTransformFilter(TCHAR * pObjectName, LPUNKNOWN lpUnk,

    CLSID clsid, HRESULT * phr);

Constructs a CTransformFilter object.

pObjectName

Name given to the CTransformFilter object.

lpUnk

Pointer to LPUNKNOWN.

clsid

Class identifier of the CTransformFilter class.

prh

Pointer to an HRESULT value in which to return resulting information.

The constructor of the derived class calls this member function. The pin objects are not created at this time; they are created when calling the CTransformFilter::GetPin member function. Thus the pins (m_pInput and m_pOutput) cannot be referred to in the constructor unless GetPin is first called. (An external object can find pins only by enumerating them or by calling IFilter::FindPin. These each call GetPin, so the pins are, in fact, created as soon as they are needed.)


CTransformFilter::DecideBufferSize

virtual HRESULT DecideBufferSize(IMemAllocator * pAlloc,

    ALLOCATOR_PROPERTIES * ppropInputRequest) PURE;

Sets the number and size of buffers required for the transfer.

•	Returns an HRESULT value.

pAlloc

The allocator assigned to the transfer.

ppropInputRequest

The requested allocator properties for count, size, and alignment, as specified by the ALLOCATOR_PROPERTIES structure.

This member function is called by the CTransformOutputPin::DecideBufferSize member function. Override and implement this member function to call the CMemAllocator::SetProperties member function with appropriate values for the output stream. This call may fail if the allocator cannot satisfy the request.


CTransformFilter::EndFlush

virtual HRESULT EndFlush();

Receives notification of leaving the flushing state and passes it downstream.

•	Returns an HRESULT value.

This member function is called by the CTransformInputPin::EndFlush member function. Override this member function if you are using queued data or a worker thread. It calls CBaseOutputPin::DeliverEndFlush to deliver the notification downstream.


CTransformFilter::EndOfStream

virtual HRESULT EndOfStream();

Receives an end-of-stream notification and passes it downstream.

•	Returns an HRESULT value.

By default, this member function calls the CBaseOutputPin::DeliverEndOfStream member function on the output pin to send the end-of-stream notification to the next filter. Override this member function if you are using queued data or a worker thread. If you overrode CTransformFilter::Receive and have queued data, you need to handle this condition and deliver EOS after all queued data is sent.


CTransformFilter::FindPin

HRESULT FindPin(LPCWSTR Id, IPin **ppPin);

Retrieves the pin with the specified identifier.

•	Returns NOERROR if the pin name was found; otherwise, returns VFW_E_NOT_FOUND.

Id

The identifier of the pin.

ppPin

A pointer to the IPin interface for this pin after the filter has been restored.

This member function overrides the CBaseFilter::FindPin member function. If the Id parameter is "In", it retrieves the input pin's IPin pointer; if the Id parameter is "Out", it retrieves the output pin's IPin pointer.

The ppPin parameter is set to NULL if the identifier cannot be matched.


CTransformFilter::GetMediaType

virtual HRESULT GetMediaType(int iPosition,

    CMediaType *pMediaType) PURE;

Returns one of the media types that the output pin supports (pure virtual).

•	Returns an HRESULT value by the overriding member function. It returns VFW_S_NO_MORE_ITEMS when asked for a media type beyond the position list. It may return S_FALSE to indicate that the media type exists but is not currently usable. In this case, the IEnumMediaTypes::Next method skips this media type.

iPosition

Position of the media type in the media type list.

pMediaType

Returned media type object.

The derived class is responsible for implementing this member function and maintaining the list of media types that it supports.

The base transform class assumes that only the output pin proposes media types, because the output pin depends on the type of connection of the input pin. For this reason, it is only the CTransformOutputPin::GetMediaType member function of the output pin that is routed to this function.


CTransformFilter::GetPin

virtual CBasePin * GetPin(int n);

Returns a pin for a specified index.

•	Returns a pointer to a CBasePin object.

n

The index of the pin to return.

This member function overrides the CBaseFilter::GetPin member function and need not be overridden unless one or more of the transform pin classes (CTransformInputPin or CTransformOutputPin) are overridden. Upon successful return, both pins are valid.


CTransformFilter::GetPinCount

virtual int GetPinCount();

Returns the number of pins on the filter.

•	Returns 2. If you override this class to support more pins, this member function returns the total number of pins on the filter.

This member function overrides the CBaseFilter::GetPinCount member function. The CTransformFilter class supports only one input pin and one output pin.


CTransformFilter::NewSegment

virtual HRESULT NewSegment(REFERENCE_TIME tStart,

    REFERENCE_TIME tStop, double dRate);

Informs the derived class that a new segment has started and delivers it downstream.

•	Returns an HRESULT value.

tStart

The start time of the segment.

tStop

The stop time of the segment.

dRate

The rate of the segment.

This member function is called by the CTransformInputPin::NewSegment member function and calls the CBaseOutputPin::DeliverNewSegment member function.


CTransformFilter::Pause

HRESULT Pause (void);

Transitions the filter to State_Paused state if it is not in this state already, and informs the derived class.

•	Returns an HRESULT value.

This member function overrides the CBaseFilter::Pause member function and implements the IMediaFilter::Pause method. It checks the input and output pin connections, then calls CTransformFilter::StartStreaming, and finally calls the base class implementation (CBaseFilter::Pause).


CTransformFilter::Receive

HRESULT Receive(IMediaSample *pSample);

Receives the media sample, calls the CTransformFilter::Transform member function, and then delivers the media sample.

•	Returns an HRESULT value.

pSample

The media sample to receive.

This member function is called by the CTransformInputPin::Receive member function, which implements the IMemInputPin::Receive method. If you override this member function, you may need to override CTransformFilter::EndOfStream, CTransformFilter::BeginFlush, and CTransformFilter::EndFlush too.


CTransformFilter::RegisterPerfId

virtual void RegisterPerfId();

Registers a performance measurement identifier.

By default, this member function registers the performance identifier (m_idTransform) with the string "Transform". Override this member function to register a performance measurement with a less generic string. This should be done to avoid confusion with other filters. This member function is enabled only when PERF is defined.


CTransformFilter::SetMediaType

virtual HRESULT SetMediaType(PIN_DIRECTION direction,

    const CMediaType *pmt) PURE;

Informs the derived class when the media type is established for the connection.

•	Returns NOERROR by default. The overriding member function returns an HRESULT value.

direction

Pin direction.

pmt

Pointer to the media type object.

Override this member function to detect when the media type is set. The implementations of CTransformInputPin::SetMediaType and CTransformOutputPin::SetMediaType call this member function.


CTransformFilter::StartStreaming

virtual HRESULT StartStreaming();

Informs the derived class that streaming is starting.

•	Returns NOERROR by default. The overriding member function returns an HRESULT value.

The filter is in the process of switching to active mode (paused or running). Optionally, you can override this member function to allocate any necessary resources.


CTransformFilter::Stop

HRESULT Stop(void);

Transitions the filter to State_Stopped state if it is not in this state already, and informs the derived class.

•	Returns an HRESULT value.

This member function overrides the CBaseFilter::Stop member function and implements the IMediaFilter::Stop method. It first decommits on the input and output pins by calling CBaseInputPin::Inactive and CBaseOutputPin::Inactive, and then calls CTransformFilter::StopStreaming to inform the derived class.


CTransformFilter::StopStreaming

virtual HRESULT StopStreaming();

Informs the derived class that streaming is ending.

•	Returns NOERROR by default. The overriding member function returns an HRESULT value.

The filter is in the process of leaving active mode and entering stopped mode. Override this member function to free any resources allocated in StartStreaming.


CTransformFilter::Transform

virtual HRESULT Transform(IMediaSample * pIn,

    IMediaSample *pOut) PURE;

Performs transform operations of the filter.

•	The overriding member function returns an HRESULT value. If it returns S_FALSE, the default implementation of the sample will not be delivered by the default implementation of the CTransformFilter::Receive member function.

pIn

Pointer to the input IMediaSample interface.

pOut

Pointer to the output IMediaSample interface.

The CTransformFilter::Receive member function calls this member function, which must be overridden with a member function that implements the transform that is intended for the filter.

Perform your transform operation in the implementation of this member function, reading the data from the input IMediaSample interface and writing the data to the output IMediaSample interface. The member function returns when the transform is complete, without releasing or delivering either of the samples. Change properties on the output sample if they are not the same as the input sample. For example, change the start and stop time (IMediaSample::SetTime), sample status flags (IMediaSample::IsSyncPoint), and so forth.


CTransformInputPin Class

The CTransformInputPin class implements the input pin of a simple transform filter. It is the class assigned to the m_pInput data member of the CTransformFilter class. Typically, you can create objects derived from CTransformFilter without modifying the CTransformInputPin class. That is, you can usually override the member functions in CTransformFilter that are called by member functions of this class. This means that you need not derive your own classes for either of the pin classes.

However, if you want to override this class and have your filter class derived from CTransformFilter, you must override the CTransformFilter::GetPin member function to create pins of your derived class.

Protected Data Members

m_pTransformFilter 	Pointer to the owning CTransformFilter object.

Member Functions

CTransformInputPin 	Constructs a CTransformInputPin object.

CurrentMediaType 	Retrieves the media type currently assigned to the filter.

PassNotify 	Passes a quality-control notification to the appropriate sink.

Overridable Member Functions

BreakConnect 	Informs the derived class when the connection is broken.

CheckConnect 	Informs the derived class when the connection process is starting.

CheckMediaType 	Determines if the pin can use a specified media type.

CheckStreaming 	Verifies conditions for continuing with a streaming operation.

CompleteConnect 	Informs the derived class when the connection process has completed.

SetMediaType 	Informs the derived class when the media type is established for the connection.

Implemented IPin Methods

BeginFlush 	Informs the pin to begin a flush operation.

EndFlush 	Informs the pin to end a flush operation and notifies the pin that it can start accepting data again.

EndOfStream 	Informs the input pin that no additional data is expected until a new run command is issued.

NewSegment 	Specifies that samples following this call are grouped as a segment with a given start time, stop time, and rate.

QueryId 	Retrieves an identifier for the pin.

Implemented IMemInputPin Methods

Receive 	Receives the next block of data from the stream.


CTransformInputPin::BeginFlush

HRESULT BeginFlush(void);

Informs the pin to begin a flush operation.

•	Returns an HRESULT value.

This member function implements the IPin::BeginFlush method and overrides the CBaseInputPin::BeginFlush member function. It checks to see if the pin is connected, then calls CBaseInputPin::BeginFlush, and finally calls the CTransformFilter::BeginFlush member function.


CTransformInputPin::BreakConnect

HRESULT BreakConnect();

Informs the derived class when the connection is broken.

•	Returns NOERROR in this implementation.

This member function overrides the CBasePin::BreakConnect member function and calls the CTransformFilter::BreakConnect member function, which currently returns NOERROR. Override CTransformFilter::BreakConnect to undo anything carried out in CTransformInputPin::CheckConnect (such as releasing extra interfaces).


CTransformInputPin::CheckConnect

HRESULT CheckConnect(IPin *pPin);

Informs the derived class when the connection process is starting.

•	Returns NOERROR by default.

pPin

Pointer to the IPin interface of the connecting pin.

This member function overrides the CBasePin::CheckConnect member function and calls the CTransformFilter::CheckConnect member function, which returns NOERROR by default. Override CTransformFilter::CheckConnect to add any additional interfaces.


CTransformInputPin::CheckMediaType

HRESULT CheckMediaType(const CMediaType* mtIn);

Determines if the pin can use a specified media type.

mtIn

Pointer to a media type object.

This member function calls the pure-virtual CTransformFilter::CheckInputType member function, which must be overridden when deriving a class from the CTransformFilter class. The overridden CheckInputType member function is responsible for determining what media types the input pin supports.


CTransformInputPin::CheckStreaming

HRESULT CheckStreaming();

Verifies conditions for continuing with a streaming operation.

•	Returns one of the following HRESULT values, depending on the state.

Value 	Meaning

S_OK 	Receive or EndOfStream operations can safely proceed.

S_FALSE 	Currently in flushing state.

VFW_E_RUNTIME_ERROR 	A run-time error occurred when processing a previous sample.

VFW_E_WRONG_STATE 	The filter is in the State_Stopped state.

VFW_E_NOT_CONNECTED 	The output pin either does not exist or is not connected.

This member function overrides the CBaseInputPin::CheckStreaming member function and calls that base class implementation for most of the condition checks. It determines if the pin is connected, if it is in a paused or running state, and if it is not currently flushing data or processing a run-time error.


CTransformInputPin::CompleteConnect

HRESULT CompleteConnect(IPin *pReceivePin);

Informs the derived class when the connection process has been completed.

•	Returns an HRESULT value.

pReceivePin

Pointer to the input pin being connected to.

This member function overrides the CBasePin::CompleteConnect member function. It calls the base class CBasePin::CompleteConnect member function and then calls CTransformFilter::CompleteConnect.


CTransformInputPin::CTransformInputPin

CTransformInputPin(TCHAR *pObjectName,

    CTransformFilter *pTransformFilter,

    HRESULT * phr, LPCWSTR pName);

Constructs a CTransformInputPin object.

pObjectName

Name of the CTransformInputPin object.

pTransformFilter

Pointer to the CTransformFilter class.

phr

Pointer to an HRESULT value in which to return resulting information. This should 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.

pName

Name of the pin.


CTransformInputPin::CurrentMediaType

CMediaType& CurrentMediaType();

Retrieves the media type currently assigned to the filter.

•	Returns the value of CBasePin::m_mt.


CTransformInputPin::EndFlush

HRESULT EndFlush(void);

Informs the pin to end a flush operation and notifies the pin that it can start accepting data again.

•	Returns an HRESULT value.

This member function implements the IPin::EndFlush method and overrides the CBaseInputPin::EndFlush member function. It checks to see if the pin is connected, then calls the CBaseInputPin::EndFlush member function, and finally calls the CTransformFilter::EndFlush member function.


CTransformInputPin::EndOfStream

HRESULT EndOfStream(void);

Informs the input pin that no additional data is expected until a new run command is issued.

•	Returns an HRESULT value.

This member function implements the IPin::EndOfStream method. It calls CTransformInputPin::CheckStreaming to see that the filter is in a streaming state and then calls the CTransformFilter::EndOfStream member function.


CTransformInputPin::NewSegment

HRESULT NewSegment(REFERENCE_TIME tStart,

    REFERENCE_TIME tStop, double dRate);

Specifies that samples following this call are grouped as a segment with a given start time, stop time, and rate.

•	Returns an HRESULT value.

tStart

The start time of the segment.

tStop

The stop time of the segment.

dRate

The rate of the segment.

This member function implements the IPin::NewSegment method and overrides the CBasePin::NewSegment member function. It calls the base class implementation first (CBasePin::NewSegment), and then calls CTransformFilter::NewSegment to pass the notification on to the next filter downstream.


CTransformInputPin::PassNotify

HRESULT PassNotify(Quality q);

Passes a quality-control notification to the appropriate sink.

•	Returns an HRESULT value.

q

A quality-control notification object.

Output pins receive quality-control notifications and, if possible, filters act upon them to degrade appropriately. Often, filters cannot respond to the notifications; in this case the notification should be passed to the quality-control sink or, by default, upstream to the next filter. The PassNotify member function is called from the CTransformOutputPin::Notify member function when a notification requires passing. The Quality structure passed is the one that the output pin received.


CTransformInputPin::QueryId

HRESULT QueryId(LPWSTR * Id);

Retrieves an identifier for the pin.

•	Returns an HRESULT value.

Id

The pin identifier.

This member function implements the IPin::QueryId method and overrides the CBasePin::QueryId member function. It returns the name "In". The caller is responsible for freeing the memory by using the Microsoft® Win32® CoTaskMemFree function.


CTransformInputPin::Receive

HRESULT Receive(IMediaSample * pSample);

Receives the next block of data from the stream.

•	Returns an HRESULT value.

pSample

Pointer to a media sample.

This member function implements the IMemInputPin::Receive method. Add a reference to the block of data if access to it is required after the completion of this method. For instance, some decoder filters for temporal compression data streams require that the previous sample be kept in order to decode the current sample.

This member function calls the CTransformFilter::Receive member function, which does the work of calling the transform function and then passing the sample on.


CTransformInputPin::SetMediaType

HRESULT SetMediaType(const CMediaType* mt);

Informs the derived class when the media type is established for the connection.

•	Returns an HRESULT value.

mt

Pointer to an input media type to be used.

This member function overrides the CBasePin::SetMediaType member function. It calls the base class CBasePin::SetMediaType member function, which returns NOERROR, and then calls CTransformFilter::SetMediaType, which may be overridden by the derived class to be informed when the media type is set.


CTransformOutputPin Class

The CTransformOutputPin class implements the output pin of a simple transform filter. It is the class assigned to the m_pOutput data member of the CTransformFilter class. Typically, you can create objects of a class derived from CTransformFilter without modifying the CTransformOutputPin class. If you want to override this class and derive a class from CTransformFilter, use the class and then override the CTransformFilter::GetPin member function to create pins of your derived class.

Protected Data Members

m_pTransformFilter 	Pointer to the owning CTransformFilter object.

Public Data Members

m_pPosition 	Pointer to a CPosPassThru object that implements the IMediaPosition interface to pass media position commands on to the upstream filter.

Member Functions

CTransformOutputPin 	Constructs a CTransformOutputPin object.

CurrentMediaType 	Retrieves the media type currently assigned to the filter.

Overridable Member Functions

BreakConnect 	Informs the derived class when the connection is broken.

CheckConnect 	Informs the derived class when the connection process is starting.

CheckMediaType 	Determines if the pin can use a specified media type.

CompleteConnect 	Informs the derived class when the connection process has completed.

DecideBufferSize 	Determines the number and size of buffers required.

GetMediaType 	Returns the media type that the output pin uses.

SetMediaType 	Informs the derived class when the media type is established for the connection.

Implemented IQualityControl Methods

Notify 	Receives a quality-control notification, typically from a downstream filter. This method is inherited from the IQualityControl interface through the CBasePin class.

Implemented IPin Methods

QueryId 	Retrieves an identifier for the pin.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface 	Returns an interface and increments the reference count.


CTransformOutputPin::BreakConnect

HRESULT BreakConnect();

Informs the derived class when the connection is broken.

•	Returns NOERROR.

This member function overrides the CBaseOutputPin::BreakConnect member function and calls the CTransformFilter::BreakConnect member function, which returns NOERROR by default. It then calls the base class implementation in CBaseOutputPin::BreakConnect. Override CTransformFilter::BreakConnect to undo anything carried out in the CTransformOutputPin::CheckConnect member function (for example, releasing interfaces previously added to the reference count).


CTransformOutputPin::CheckConnect

HRESULT CheckConnect(IPin *pPin);

Informs the derived class when the connection process is starting.

•	Returns NOERROR by default.

pPin

Pointer to the IPin interface of the connecting pin.

This member function overrides the CBasePin::CheckConnect member function and calls the CTransformFilter::CheckConnect member function, which returns NOERROR by default. It then calls the base class implementation in CBaseOutputPin::CheckConnect. Override CTransformFilter::CheckConnect to add any additional interfaces.


CTransformOutputPin::CheckMediaType

HRESULT CheckMediaType(const CMediaType* mtIn);

Determines if the input pin supports this media type.

mtIn

Pointer to a media type object.

This member function calls the pure-virtual CTransformFilter::CheckTransform member function, which must be overridden when deriving a class from the CTransformFilter class. The overridden CTransformFilter::CheckTransform member function determines which media types the output pin supports.


CTransformOutputPin::CompleteConnect

HRESULT CompleteConnect(IPin *pReceivePin);

Informs the derived class when the connection process has completed.

•	Returns an HRESULT value.

pReceivePin

Pointer to the output pin that is being connected to.

This member function overrides the CBaseOutputPin::CompleteConnect member function and calls the CTransformFilter::CompleteConnect member function, which returns NOERROR by default. It then calls the base class implementation in CBaseOutputPin::CompleteConnect. Override the CTransformFilter::CompleteConnect member function to retrieve any additional interfaces not retrieved by the base class that your output pin may need from the connected pin.


CTransformOutputPin::CTransformOutputPin

CTransformOutputPin(TCHAR *pObjectName,

    CTransformFilter *pTransformFilter,

    HRESULT * phr, LPCWSTR pName);

Constructs a CTransformOutputPin object.

pObjectName

Name of the CTransformOutputPin object.

pTransformFilter

Pointer to the CTransformFilter class.

phr

Pointer to an HRESULT value in which to return resulting information. This should be modified only if a failure occurs. If it is a failure code on input, construction can be aborted, but in any case the destructor will be called by the creator when the HRESULT error is detected.

pName

Name of the pin.


CTransformOutputPin::CurrentMediaType

CMediaType& CurrentMediaType();

Retrieves the media type currently assigned to the filter.

•	Returns the value of CBasePin::m_mt.


CTransformOutputPin::DecideBufferSize

HRESULT DecideBufferSize(IMemAllocator * pAlloc,

    ALLOCATOR_PROPERTIES * ppropInputRequest);

Determines the number and size of buffers required.

•	Returns an HRESULT value.

pAlloc

The allocator assigned to the transfer.

ppropInputRequest

The requested allocator properties for count, size, and alignment, as specified by the ALLOCATOR_PROPERTIES structure.

This member function overrides the CBaseOutputPin::DecideBufferSize member function and calls the pure virtual CTransformFilter::DecideBufferSize member function, which your derived class must override and implement. This member function is called from the CBaseOutputPin class during the connection process.


CTransformOutputPin::GetMediaType

HRESULT GetMediaType(int iPosition,

    CMediaType *pMediaType);

Returns the media type for the output pin to use.

•	Returns an HRESULT value and depends upon the implementation of the pure virtual CTransformFilter::GetMediaType member function. HRESULT can include one of the following constants.

Constant 	Meaning

NOERROR 	A media type is returned.

S_FALSE 	Although the iPosition parameter typically is valid, it does not correspond to a media type that is currently valid.

VFW_S_NO_MORE_ITEMS 	The iPosition parameter is beyond the valid range.

Use other standard error values, such as E_INVALIDARG, for error cases.

iPosition

Position of the media type in the media type list.

pMediaType

Returned media type object.

This member function overrides the CBasePin::GetMediaType member function and calls the pure virtual CTransformFilter::GetMediaType member function, which must be overridden to return media types supported by your filter. This is part of the implementation of CBasePin::EnumMediaTypes.


CTransformOutputPin::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method. It overrides the CBasePin::NonDelegatingQueryInterface member function and passes references to the IPin, IQualityControl, IMediaPosition, IMediaSelection, and IUnknown interfaces. Override this class to return other interfaces on the object in the derived class.


CTransformOutputPin::Notify

HRESULT Notify(IFilter * pSelf, Quality q);

Notifies the recipient that a quality change is requested.

•	Default base class implementation returns E_FAIL.

pSelf

Pointer to the filter that is sending the quality notification.

q

Quality notification structure.

This member function implements the IQualityControl::Notify method and overrides the CBasePin::Notify member function. It calls the CTransformFilter::AlterQuality member function to determine if the filter can do something to adjust the quality of the media stream (such as discarding samples). If that member function returns S_FALSE, it calls the CTransformInputPin::PassNotify member function, which passes the notification to the upstream filter after verifying that it is connected upstream.


CTransformOutputPin::QueryId

HRESULT QueryId(LPWSTR * Id);

Retrieves an identifier for the pin.

•	Returns an HRESULT value.

Id

The pin identifier.

This member function implements the IPin::QueryId method and overrides the CBasePin::QueryId member function. It returns the name "Out". The caller is responsible for freeing the memory by using the Microsoft® Win32® CoTaskMemFree function.


CTransformOutputPin::SetMediaType

HRESULT SetMediaType(const CMediaType* mt);

Sets the media type for the connection to use.

•	Returns an HRESULT value (NOERROR by default).

mt

Pointer to an output media type to be used.

This member function overrides the CBasePin::SetMediaType member function and calls the CTransformFilter::SetMediaType member function with the direction set to output. Override CTransformFilter::SetMediaType to handle any conditions that you want handled at this time in the connection process.


CTransInPlaceFilter Class

CTransInPlaceFilter is an abstract base class that provides support for a simple transform filter with a single input and a single output. It is derived from the CUnknown class, and it supports the IFilter interface, the IMediaFilter interface, and two pins. Each pin supports the IPin interface and uses the shared memory transport based on the IMemInputPin interface. The filter uses classes derived from the CBaseMediaFilter class to support IFilter and IMediaFilter. The input pin is derived from the CBaseInputPin class, and the output pin is derived from the CBaseOutputPin class.

For more information about using this class to create a transform filter, see Creating a Transform Filter.

Protected Data Members

m_idTransInPlace 	Performance-measuring identifier.

m_pAllocator 	The allocator on the input pin.

Member Functions

CTransInPlaceFilter 	Constructs a CTransInPlaceFilter object.

InputPin 	Returns a pointer to the input pin associated with the filter.

OutputPin 	Returns a pointer to the output pin associated with the filter.

Overridable Member Functions

CheckTransform 	Verifies that the media type is supported by input and output pins.

CompleteConnect 	Reconnects the input or output pin if necessary.

DecideBufferSize 	Determines the size of the transport buffer.

GetMediaType 	Returns the media type to be used by the output pin.

GetPin 	Returns a pin if an index is specified.

Receive 	Receives the sample, calls the derived class's Transform member function, and then delivers the sample.

RegisterPerfId 	Registers a performance measurement identifier (if PERF is defined).

Transform 	Performs transformation operations in place on the IMediaSample interface (pure virtual).


CTransInPlaceFilter::CheckTransform

HRESULT CheckTransform(const CMediaType *mtIn,

    const CMediaType *mtOut);

Verifies that the media is supported by input and output pins.

•	Returns S_OK by default.

mtIn

The input pin media type.

mtOut

The output pin media type.

This member function overrides the CTransformFilter::CheckTransform member function. The base class functions that call this member function are overridden in this class to call the CTransformFilter::CheckInputType member function that is overridden in the derived class, with the assumption that the type does not change. Usually there is no reason for this member function to be called. In debug builds some calls will be made, and returning S_OK ensures that these calls do not assert.


CTransInPlaceFilter::CompleteConnect

HRESULT CompleteConnect(PIN_DIRECTION direction,

    IPin *pReceivePin);

Reconnects the input or output pin if necessary.

•	Returns an HRESULT value.

direction

The pin direction.

pReceivePin

Pointer to the output pin to which to connect.

This member function overrides the CTransformFilter::CompleteConnect member function. It is called by one of the pin classes at the end of a successful connection. Because the input and output pins must both use the same allocator, this member function reconnects the opposite pin if necessary.

When the input pin is first connected, the output pin has not yet been connected and the downstream filter's allocator is unknown, so the allocator for the input pin is chosen to be the upstream pin's allocator. When the transform filter's output pin is connected, however, it has access to the downstream filter's allocator and should force a reconnect on the input pin and offer that allocator. When the input pin is reconnected, it forces a reconnect on the output pin if the allocator chosen for the input pin's connection differs from the output pin's connection. This member function supplies the reconnection for either output or input pins.


CTransInPlaceFilter::CTransInPlaceFilter

CTransInPlaceFilter(TCHAR * pObjectName, LPUNKNOWN lpUnk,

    CLSID clsid, HRESULT * phr);

Constructs a CTransInPlaceFilter object.

pObjectName

Name given to the CTransInPlaceFilter object.

lpUnk

Pointer to LPUNKNOWN.

clsid

Class identifier of the CTransInPlaceFilter class.

phr

Pointer to the HRESULT value for resulting information.


CTransInPlaceFilter::DecideBufferSize

HRESULT DecideBufferSize(IMemAllocator * pAlloc,

    ALLOCATOR_PROPERTIES * * ppropInputRequest);

Determines the size of the transport buffer.

•	Returns E_UNEXPECTED because it is not expected to be called.

pAlloc

Pointer to an IMemAllocator object.

ppropInputRequest

The requested allocator properties for count, size, and alignment, as specified by the ALLOCATOR_PROPERTIES structure.

This member function overrides the CTransformFilter::DecideBufferSize member function. Because this transform class uses a buffer belonging to another filter, which has already been set, this member function is never called. It is implemented to prevent "undefined pure virtual" compiler warnings.


CTransInPlaceFilter::GetMediaType

HRESULT GetMediaType(int iPosition,

    CMediaType *pMediaType);

Returns the media type to be used by the output pin.

•	Returns E_UNEXPECTED because it is not expected to be called.

iPosition

Position of the media type in the media type list.

pMediaType

Returned media type object.

In the CTransformFilter class, this member function is called by the associated input or output pin class's GetMediaType member function to retrieve the next media type in the list and return it to the pin's CBasePin::EnumMediaTypes member function.

However, in the CTransInPlaceFilter class, the pin classes override the CBasePin::EnumMediaTypes member function so that it bypasses the filter and calls the enumerator of the opposite connected pin. (For example, the output pin enumerator uses the upstream filter's enumerator, and the input pin uses the connected downstream filter's enumerator.) Therefore, this member function should never be called by the inplace pin classes. It is implemented to prevent "undefined pure virtual" compiler warnings.


CTransInPlaceFilter::GetPin

virtual CBasePin * GetPin(int n);

Returns a pin if an index is specified.

•	Returns a pointer to a CBasePin object.

n

The index of the pin to return.

This member function is implemented and need not be overridden unless one or more of the transform pin classes (CTransInPlaceInputPin or CTransInPlaceOutputPin) are being overridden.


CTransInPlaceFilter::InputPin

CTransInPlaceInputPin *InputPin();

Returns a pointer to the input pin associated with the filter.

This member function is protected.


CTransInPlaceFilter::OutputPin

CTransInPlaceOutputPin *OutputPin();

Returns a pointer to the output pin associated with the filter.

This member function is protected.


CTransInPlaceFilter::Receive

virtual HRESULT Receive(IMediaSample *pSample);

Receives the media sample, calls the CTransInPlaceFilter::Transform member function, and then delivers the media sample.

•	Returns an HRESULT value.

pSample

The sample to deliver.

This member function overrides the CTransformFilter::Receive member function. Override it only if you need more control of the process.


CTransInPlaceFilter::RegisterPerfId

virtual void RegisterPerfId();

Registers a performance measurement identifier.

By default, this member function registers the performance identifier (m_idTransform) with the string "TransinPlace". Override this member function to register a performance measurement with a less generic string. This should be done to avoid confusion with other filters. This member function is enabled only when PERF is defined.


CTransInPlaceFilter::Transform

virtual HRESULT Transform(IMediaSample *pSample) PURE;

Transforms the data in pSample in place.

pSample

Pointer to the input IMediaSample interface.

You must supply this member function in the derived class to perform the actual work of your filter. This member function is called by CTransInPlaceFilter::Receive before passing the sample on to the downstream filter. Transform can return S_FALSE to indicate that the sample is not to be delivered downstream.


CTransInPlaceInputPin Class

The CTransInPlaceInputPin class implements the input pin of a transform-inplace filter (CTransInPlaceFilter). This is part of a transform filter that transforms data in place rather than making a copy of it. It is the class returned by the CTransInPlaceFilter::InputPin member function.

Typically, objects of a class derived from CTransInPlaceInputPin can be created without modifying this class. That is, you can usually override member functions in the CTransInPlaceFilter class that are called by member functions of the CTransInPlaceInputPin class and not have to derive your own classes for either of the pin classes.

However, if you want to override this class and derive your filter class from CTransInPlaceFilter, you must override the CTransInPlaceFilter::GetPin member function to create pins of your derived class.

Protected Data Members

m_pTIPFilter 	Pointer to the CTransInPlaceFilter object that owns this pin.

Member Functions

CTransInPlaceInputPin 	Constructs a CTransInPlaceInputPin object.

Overridable Member Functions

CheckMediaType 	Determines if the pin can use a specified media type.

Implemented IPin Methods

EnumMediaTypes 	Provides a media type enumerator from the downstream filter.

Implemented IMemInputPin Methods

GetAllocator 	Retrieves the upstream allocator.

NotifyAllocator 	Receives notification of which allocator will be used by the connected output pin.


CTransInPlaceInputPin::CheckMediaType

HRESULT CheckMediaType(const CMediaType* pmt)

Determines if the media type is acceptable.

•	Returns an HRESULT value.

pmt

The media type being checked.

This member function overrides the CTransformInputPin::CheckMediaType member function. It first calls the owning filter's CheckInputType member function. Then, if the filter's output pin is not connected, this member function agrees to any media type. If the output pin is connected, it asks the downstream connected input pin if it accepts this type and returns the result.


CTransInPlaceInputPin::CTransInPlaceInputPin

CTransInPlaceInputPin(TCHAR *pObjectName,

    CTransInPlaceFilter *pFilter, HRESULT * phr,

    LPCWSTR pName);

Constructs a CTransInPlaceInputPin object.

pObjectName

Name of the CTransInPlaceInputPin class object.

pFilter

Pointer to the CTransInPlaceFilter class.

phr

Pointer to an HRESULT value in which to return resulting information. This should 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.

pName

Name of the pin.

This member function does not create the pins. The pins are created when they are first required. All external attempts to access pins (by enumeration or by CBaseFilter::FindPin) go through CTransInPlaceFilter::GetPin, which creates the pins initially.


CTransInPlaceInputPin::EnumMediaTypes

HRESULT EnumMediaTypes(IEnumMediaTypes **ppEnum)

Provides an enumerator for media types by retrieving one from downstream.

•	Returns an HRESULT value.

ppEnum

[out] A pointer to an enumerator for the media types.

This member function overrides the CBasePin::EnumMediaTypes member function and implements the IPin::EnumMediaTypes method. Transform-inplace filters use the media type enumerator from adjacent filters because they do not change the media type. When asked by a connected output pin of the upstream filter for this pin's media type enumerator, this member function simply retrieves the allocator from the input pin connected to its output pin (if it is connected).


CTransInPlaceInputPin::GetAllocator

HRESULT GetAllocator(IMemAllocator ** ppAllocator)

Retrieves the upstream allocator.

•	Returns an HRESULT value.

ppAllocator

The returned allocator.

This member function overrides the CBaseInputPin::GetAllocator member function and implements the IMemInputPin::GetAllocator method. If an allocator has already been agreed upon, this member function supplies that allocator. Otherwise, if the downstream input pin can supply an allocator, it does so. If no allocator is available, this member function returns VFW_E_NO_ALLOCATOR.


CTransInPlaceInputPin::NotifyAllocator

HRESULT NotifyAllocator(IMemAllocator * pAllocator,

    BOOL bReadOnly);

Receives notification of which allocator will be used by the connected output pin.

•	Returns an HRESULT value.

pAllocator

Pointer to the IMemAllocator object to use. This may or may not be the same CTransInPlaceInputPin object that the input pin provided in the CTransInPlaceInputPin::GetAllocator member function (the output pin could provide its own allocator).

bReadOnly

Flag to indicate if the samples from this allocator are read-only.

This member function overrides the CBaseInputPin::NotifyAllocator member function and implements the IMemInputPin::NotifyAllocator method. This member function remembers the allocator and passes it to the output pin because they both must share the same allocator.


CTransInPlaceOutputPin Class

The CTransInPlaceOutputPin class implements the output pin of a simple transform-inplace filter (CTransInPlaceFilter).

Protected Data Members

m_pTIPFilter 	Pointer to the CTransInPlaceFilter object that owns this pin.

Member Functions

CTransInPlaceOutputPin 	Construct a CTransInPlaceOutputPin object.

Overridable Member Functions

CheckMediaType 	Determines if the media type is acceptable.

DecideAllocator 	Negotiates the allocator to use (uses the allocator from the upstream output pin).

Implemented IPin Methods

EnumMediaTypes 	Provides a media type enumerator from the upstream filter.

Implemented IMemInputPin Methods

NotifyAllocator 	Receives notification of which allocator will be used (not normally called on output pin).


CTransInPlaceOutputPin::CheckMediaType

HRESULT CheckMediaType(const CMediaType* pmt);

Determines if the media type is acceptable.

•	Returns an HRESULT value.

pmt

Pointer to a media type object containing the proposed media type.

This member function overrides the CTransformOutputPin::CheckMediaType member function. It calls the pure virtual CTransformFilter::CheckInputType member function to verify the media type (which you must implement in your derived class) because it does not change the media type from input to output. If it is not connected, it returns S_OK, which agrees to any media type; otherwise, it calls QueryAccept on the output pin of the upstream filter and returns the result.


CTransInPlaceOutputPin::CTransInPlaceOutputPin

CTransInPlaceOutputPin(TCHAR *pObjectName,

    CTransInPlaceFilter *pFilter, HRESULT * phr,

    LPCWSTR pName);

Constructs a CTransInPlaceOutputPin object.

pObjectName

Name of the CTransInPlaceOutputPin object.

pFilter

Pointer to the owning CTransInPlaceFilter filter.

phr

Pointer to an HRESULT value in which to return resulting information.

pName

Name of the pin.


CTransInPlaceOutputPin::DecideAllocator

virtual HRESULT DecideAllocator(IMemInputPin * pPin,

    IMemAllocator ** ppAlloc);

Negotiates the allocator to use (uses the allocator from the upstream output pin).

•	Retrieves the value that is returned when calling the CTransInPlaceInputPin::NotifyAllocator method on the downstream input pin.

pPin

Pointer to the IMemInputPin interface of the downstream input pin.

ppAlloc

Returned allocator pointer.

This member function overrides the CBaseOutputPin::DecideAllocator member function. This implementation uses the allocator that is negotiated by its input pin because a transform-inplace filter does not supply its own allocator. It then calls IMemInputPin::NotifyAllocator on the downstream input pin with that allocator.

If you want to use your own allocator, it is better to derive from CTransformFilter than from CTransInPlaceFilter because the purpose of a transform-inplace filter is to use an existing allocator.


CTransInPlaceOutputPin::EnumMediaTypes

HRESULT EnumMediaTypes(IEnumMediaTypes **ppEnum);

Provides a media type enumerator from the upstream filter.

•	Returns an HRESULT value.

ppEnum

A pointer to an enumerator for the media types.

This member function overrides the CBasePin::EnumMediaTypes member function and implements the IPin::EnumMediaTypes method. Transform-inplace filters use the media type enumerator from adjacent filters because they do not change the media type. This member function calls IPin::EnumMediaTypes on the output pin connected to the filter's input pin. If an application receives an enumerator, the application must release it when finished.


CTransInPlaceOutputPin::NotifyAllocator

HRESULT NotifyAllocator(IMemAllocator * pAllocator,

    BOOL bReadOnly);

Receives notification of which allocator will be used.

•	Returns an HRESULT value.

pAllocator

Pointer to the IMemAllocator object to use.

bReadOnly

Flag to indicate if the samples from this allocator are read-only.

This member function is called by the CTransInPlaceInputPin::NotifyAllocator member function to notify the output pin as to which allocator has been decided on. This is not usually implemented on output pins, but in the case of transform-inplace filters, the output pin will use the same allocator as the input pin and needs to know what allocator to use when negotiating its downstream connection.


CUnknown Class

The CUnknown class is an abstract base class from which all Microsoft® ActiveMovie™ Component Object Model (COM) objects are derived. The purpose of the CUnknown class is to allow the creation of simple COM objects that can be combined with other COM objects to support multiple interfaces.

To use CUnknown, derive your object from CUnknown and separately provide it with an IUnknown interface by using the DECLARE_IUNKNOWN macro in the public section of your object class definition. If you are deriving from an object that has already done this, such as CBaseFilter, you do not need to do it yourself.

The CUnknown class supports only one interface, IUnknown. To support any interfaces your object provides that are not provided by the base class from which they are derived, override NonDelegatingQueryInterface. In that member function, use the CUnknown::GetInterface member function to return any interfaces your object supports directly. Then pass any interface it is queried for that is not implemented in the derived class on to the base class to retrieve the interface.

For example, CBaseFilter supports the following interfaces directly:

•	IFilter

•	IMediaFilter

•	IPersist

•	IAMovieSetup

CBaseFilter also supports IUnknown by passing queries for this interface to CUnknown. The following code sample demonstrates how this is done.

/* Override this to say what interfaces are supported and where */

STDMETHODIMP CBaseFilter::NonDelegatingQueryInterface(REFIID riid,

                                                      void **ppv)

{

    CheckPointer(ppv,E_POINTER);

    ValidateReadWritePtr(ppv,sizeof(PVOID));

    /* Do we have this interface */

    if (riid == IID_IFilter) {

         return GetInterface((IFilter *) this, ppv);

    } else if (riid == IID_IMediaFilter) {

                   return GetInterface((IMediaFilter *) this, ppv);

    } else if (riid == IID_IPersist) {

                   return GetInterface((IPersist *) this, ppv);

    } else if (riid == IID_IAMovieSetup) {

                   return GetInterface((IAMovieSetup *) this, ppv);

    } else {

                   return CUnknown::NonDelegatingQueryInterface(riid, ppv);

    }

}

Note that CUnknown does the right thing if it does not support the interface, so it is always important to pass on any unsupported interfaces.

To build composite objects, the CUnknown constructor has an LPUNKNOWN parameter that is a pointer to the top-level IUnknown object for the entire composite object (the object that includes all objects based on a class derived from CUnknown). If this value is not NULL, CUnknown saves this value (in its private m_pUnknown member variable).

If the LPUNKNOWN value passed to the CUnknown object is NULL, the m_pUnknown member is set to point to the CUnknown object itself. This way, the top-level object's IUnknown is made the same as its implementation of INonDelegatingUnknown.

The derived class will typically override the NonDelegatingQueryInterface method to return interfaces that it supports; however, it must delegate support for IUnknown to the CUnknown class implementation. Usually NonDelegatingAddRef and NonDelegatingRelease do not need to be overridden because reference counting for the whole object is managed inside the top-level object. However, NonDelegatingRelease may need to be overridden sometimes because its default action when the reference count goes to zero is to delete the object from inside itself.

CUnknown provides the CUnknown::GetOwner member function. GetOwner simply returns an LPUNKNOWN pointer to the controlling unknown. This is used in the DECLARE_IUNKNOWN macro when calling QueryInterface. It can also be used when creating a composite object to pass an LPUNKNOWN pointer to a component interface as an (equivalent) alternative to passing the LPUNKNOWN pointer that was passed to the composite object constructor.

When QueryInterface is called on an interface owned by a component interface, it is immediately passed to the NonDelegatingQueryInterface method of the top-level object's INonDelegatingUnknown::NonDelegatingQueryInterface method, which either returns an interface it implements itself or passes the call to the correct member or base class's INonDelegatingUnknown::NonDelegatingQueryInterface method. This then repeats the process until a component is found that implements the interface or calls CUnknown::NonDelegatingQueryInterface, which fails the call.

Note that the top-level object's CUnknown::NonDelegatingQueryInterface member function (as distinct from its own implementation) must be called to support IUnknown.

This design makes support for COM Aggregation straightforward. The CreateInstance member function called from the class factory passes the outer unknown (the pUnkOuter parameter from CoCreateInstance) on to CUnknown, and the object behaves as if it were part of a larger object by delegating its QueryInterface calls to the outer unknown.

Protected Data Members

m_cRef 	Number of reference counts (so the INonDelegatingUnknown::NonDelegatingRelease method can be overridden).

Member Functions

CUnknown 	Construsts a CUnknown object.

GetInterface 	Returns an interface pointer to the requested client.

GetOwner 	Returns an LPUNKNOWN pointer to the controlling unknown.

Implemented INonDelegatingUnknown Methods

NonDelegatingAddRef 	Increments the reference count for an interface.

NonDelegatingQueryInterface 	Returns an interface and increments the reference count.

NonDelegatingRelease 	Decrements the reference count for an interface.


CUnknown::CUnknown

CUnknown(TCHAR *pName, LPUNKNOWN pUnk, HRESULT *phr);

Constructs a CUnknown object.

pName

Name of the object used in the CBaseObject constructor for debugging purposes.

pUnk

Pointer to the owner of this object. If non-null, IUnknown calls are delegated to this object.

phr

Pointer to an HRESULT value for resulting information.

The object is initialized with a reference count of zero. This reference count may be incremented when the object is queried for its first interface, depending on whether the object is currently being aggregated.


CUnknown::GetInterface

HRESULT GetInterface(LPUNKNOWN pUnk, void **ppv);

Returns an interface pointer.

•	Returns an HRESULT value.

pUnk

Pointer to the IUnknown interface.

ppv

Retrieved interface.

This member function performs a thread-safe increment of the reference count. To retrieve the interface and add a reference, call this member function from your overriding implementation of the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CUnknown::GetOwner

LPUNKNOWN GetOwner(void);

Retrieves the Component Object Model (COM) class owner of this object.

•	Returns an LPUNKNOWN pointer to the controlling IUnknown interface.


CUnknown::NonDelegatingAddRef

ULONG NonDelegatingAddRef();

Increments the reference count for an interface.

•	Returns the reference count of the object.

This member function provides a base class implementation of the INonDelegatingUnknown::NonDelegatingAddRef method. When the object derived from CUnknown is part of an aggregated object, this reference count modification is private to the embedded object.


CUnknown::NonDelegatingQueryInterface

HRESULT NonDelegatingQueryInterface(REFIID riid,

    void ** ppv);

Returns an interface and increments the reference count.

•	Returns a pointer to the interface.

riid

Reference identifier.

ppv

Pointer to the interface.

This member function provides a base class implementation of the INonDelegatingUnknown::NonDelegatingQueryInterface method. Override this class to return interfaces on the object in the derived class.


CUnknown::NonDelegatingRelease

ULONG NonDelegatingRelease();

Decrements the reference count for an interface.

•	Returns the reference count.

This member function provides a base class implementation of the INonDelegatingUnknown::NonDelegatingRelease method. When the object derived from CUnknown is part of an aggregated object, this reference count modification is private to the embedded object.


CVideoTransformFilter Class

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 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 makes the decision 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 of 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.

Once 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 (available if PERF is defined). Logs 1 for key frames; logs 2 for non-key frames.

m_idLate 	Performance identifier for measuring lateness (available if PERF is defined).

m_idSkip 	Performance identifier for measuring frame skipping (available if PERF is defined).

m_idTimeTillKey 	Performance identifier that represents an estimate of the time in milliseconds until the next key frame arrives (available if PERF is defined).

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_nKeyFramePeriod 	The largest observed interval between key frames.

m_nFramesSinceKeyFrame 	Used to count frames since the last key frame.

m_nWaitForKey 	Used to ensure output after a format change before getting the first key frame. When non-zero, frames are not passed to the renderer. Set to 30 when format is changed and decremented on each non-key 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

BeginFlush 	Receives notification of entering the flushing state and passes it downstream.

Receive 	Receives the media sample and either skips the sample or transforms and delivers the media sample.

StartStreaming 	Overrides CTransformFilter::StartStreaming to reset the quality control information when streaming starts or flushing starts.


CVideoTransformFilter::BeginFlush

virtual HRESULT BeginFlush();

Receives notification of entering the flushing state and passes it downstream.

•	Returns an HRESULT value.

This member function overrides the CTransformFilter::BeginFlush member function. It calls CVideoTransformFilter::StartStreaming to reset quality control member variables and then calls the base class CTransformFilter::BeginFlush member function.


CVideoTransformFilter::CVideoTransformFilter

CVideoTransformFilter(TCHAR * pObjectName,

    LPUNKNOWN lpUk, CLSID clsid, HRESULT * phr);

Constructs a CVideoTransformFilter object.

pObjectName

Name given to the CVideoTransformFilter object.

lpUk

Pointer to LPUNKNOWN.

clsid

Class identifier of the CVideoTransformFilter class.

phr

Pointer to the HRESULT value for resulting information.


CVideoTransformFilter::Receive

HRESULT Receive(IMediaSample *pSample);

Receives the media sample and either skips the sample or transforms and delivers the media sample.

•	Returns an HRESULT value.

pSample

Sample to deliver.

This member function overrides the CTransformFilter::Receive member function. Override only if you need more control of the process.


CVideoTransformFilter::RegisterPerfId

virtual void RegisterPerfId();

Registers performance measurement identifiers.

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 estd. time to next key

This member function also calls CTransformFilter::RegisterPerfId for its performance identifier.

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. This member function is enabled only when PERF is defined.


CVideoTransformFilter::ShouldSkipFrame

BOOL ShouldSkipFrame( IMediaSample * pIn);

Determines if the filter should start, continue, or stop skipping frames.

•	Returns TRUE if the filter should skip this sample; otherwise, returns FALSE.

pIn

The received sample to be transformed or skipped.

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 of 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.

The member function sends an EC_QUALITY_CHANGE notification when sample skipping starts. Once skipping starts, all samples are skipped until the next key frame arrives.


CVideoTransformFilter::StartStreaming

virtual HRESULT StartStreaming();

Overrides CTransformFilter::StartStreaming to reset the quality control information when streaming starts or flushing starts.

•	Returns NOERROR.

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

This 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 ActiveMovie™ 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 four-thousand-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 so can be cast to a GUID straightforwardly. 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 	Returns the FOURCC from a FOURCCMap object.

SetFOURCC 	Sets the FOURCC portion of the FOURCCMap object.


FOURCCMap::FOURCCMap

FOURCCMap();

FOURCCMap(DWORD Fourcc);

FOURCCMap(const GUID * pguid);

Constructs a FOURCCMap object. Provides a mapping between old-style multimedia format DWORD types and new-style GUID types.

Fourcc

The DWORD media tag formerly used for Microsoft multimedia types.

pguid

The globally unique identifier (GUID).

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

DWORD GetFOURCC(void);

Retrieves the FOURCC DWORD from the FOURCCMap object.

•	Returns the FOURCC DWORD value. Note that if you construct a FOURCCMap object from a GUID that was not originally derived from FOURCC, the return value will be essentially random.


FOURCCMap::SetFOURCC

void SetFOURCC(const GUID * pguid);

Sets the FOURCC portion of the FOURCCMap object.

pguid

Pointer to the returned globally unique identifier (GUID) part of the FOURCCMap object.


BSTR Functions

The wxutil.h header file provides helper functions for allocating and freeing task-allocated BSTR strings.

Functions

FreeBSTR 	Frees the task-allocated BSTR string.

WriteBSTR 	Creates a task-allocated BSTR string by allocating task-allocated memory and copying a wide string to it.


FreeBSTR

HRESULT FreeBSTR(BSTR* pstr);

Frees a task-allocated BSTR string from memory.

•	Returns an HRESULT value.

pstr

Address of the BSTR to free (deallocate).

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.


WriteBSTR

HRESULT WriteBSTR(BSTR* pstrDest, LPCWSTR szSrc);

Allocates and fills a task-allocated BSTR string.

•	Returns an HRESULT value.

pstrDest

Pointer to where the address of the allocated BSTR will be stored.

szSrc

Wide (Unicode) string that will be copied to the newly allocated BSTR string.

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.


Bitmap Functions and Data

The wxutil.h header file provides functions to help convert between VIDEOINFO and BITMAPINFO structures.

Functions

ContainsPalette 	Checks if a VIDEOINFO structure includes a palette.

GetBitCount 	Finds the number of bits per pixel.

GetBitmapFormatSize 	Finds the size (in bytes) needed to build a VIDEOINFO structure and related data.

GetBitmapPalette 	Finds the first palette entry in a VIDEOINFO 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.

These functions are made available to help manage VIDEOINFOs. The VIDEOINFO structure is used throughout ActiveMovie™ to describe video data streams. Although very similar, in part, to the BITMAPINFO structure used in Microsoft® Win32® and existing multimedia, it also adds some new video-specific fields.

Global Data

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.


ContainsPalette

BOOL ContainsPalette(const VIDEOINFO *pVideoInfo);

Checks if a VIDEOINFO structure includes a palette.

•	Returns TRUE if the VIDEOINFO contains a palette; otherwise, returns FALSE.

pVideoInfo

Pointer to a VIDEOINFO structure.


GetBitCount

WORD GetBitCount(const GUID *pSubtype);

Finds the number of bits per pixel.

•	Returns the number of bits per pixel for this subtype, or USHRT_MAX if an error occurred.

pSubtype

Pointer to a GUID for a given video subtype.


GetBitmapFormatSize

LONG GetBitmapFormatSize(const BITMAPINFOHEADER *pHeader);

Finds the size (in bytes) needed to build a VIDEOINFO structure and related data.

•	Returns the number of bytes for the VIDEOINFO structure described by this BITMAPINFOHEADER, including prefix information, the BITMAPINFOHEADER field, and any other color information on the end.

pHeader

Pointer to a BITMAPINFOHEADER structure.


GetBitmapPalette

const RGBQUAD * GetBitmapPalette(

    const VIDEOINFO *pVideoInfo);

Finds the first palette for a VIDEOINFO structure.

•	Returns a pointer to the first entry in a palette.

pVideoInfo

Pointer to a VIDEOINFO structure.


GetBitmapSize

DWORD GetBitmapSize(const BITMAPINFOHEADER *pHeader);

Finds the size (in bytes) needed to hold an image.

•	Returns the number of bytes necessary to hold an image. Note that this value may be rounded up.

pHeader

Pointer to a BITMAPINFOHEADER.


GetBitmapSubtype

const GUID GetBitmapSubtype(

    const BITMAPINFOHEADER *pHeader);

Finds the GUID subtype for a given bitmap info header structure.

•	Returns the GUID of the subtype of video described by this bitmap info header, or GUID_NULL if an error occurred.

pHeader

Pointer to a BITMAPINFOHEADER.


GetSubtypeName

TCHAR * GetSubtypeName(const GUID *pSubtype);

Finds the (debug) name for a given GUID subtype.

•	Returns the debug name of this GUID, or TEXT("UNKNOWN") if the name is not known.

pSubtype

Pointer to a GUID for a given video subtype.


GetTrueColorType

const GUID GetTrueColorType(

    const BITMAPINFOHEADER *pHeader);

Finds the GUID subtype for a given bitmap header with 16-bit color depth.

•	Returns the GUID of the subtype of video described by this bitmap info header, or GUID_NULL if an error occurred.

pHeader

Pointer to a BITMAPINFOHEADER.


CCritSec Debug Functions

To make deadlocks easier to track, it is useful to insert in the code an assertion that says whether a critical section is owned or not. The routines that do the checking are global functions to avoid having different numbers of member functions in the debug and retail class implementations of CCritSec. In addition, a routine that allows usage of specific critical sections to be traced is provided. This is not on by default—there are far too many.

Functions and Macros

CritCheckIn 	Checks that the current thread is the owner of the given critical section.

CritCheckOut 	Checks that the current thread is not the owner of the given critical section.

DbgLockTrace 	Enables or disables debug logging of a given critical section.


CritCheckIn

BOOL CritCheckIn(CCritSec * pcCrit);

Checks that the owner of pcCrit is the current thread.

•	Returns TRUE if the current thread is the owner of this critical section; otherwise, returns FALSE.

pcCrit

Pointer to a CCritSec critical section.

If this macro is used and DEBUG is not defined when the ActiveMovie™ headers are included, it will always return TRUE.


CritCheckOut

BOOL CritCheckOut(CCritSec * pcCrit);

Checks that the owner of pcCrit is not the current thread.

•	Returns TRUE if the current thread is not the owner of this critical section; otherwise, returns FALSE.

pcCrit

Pointer to a CCritSec critical section.

If this macro is used and DEBUG is not defined when the ActiveMovie headers are included, it will always return TRUE.


DbgLockTrace

void DbgLockTrace(CCritSec * pcCrit, BOOL fTrace);

Enables or disables debug logging of a given critical section.

pcCrit

Pointer to a CCritSec critical section.

fTrace

TRUE if logging is to be enabled, FALSE if it is to be disabled.

This is ignored unless DEBUG is defined when the ActiveMovie headers are included.


Conversion Functions

The wxutil.h header file provides functions for converting between integers and wide strings.

Functions

atoi 	Converts a string to an integer.

atoiA 	Converts a string to an integer.

atoiW 	Converts a wide string to an integer.

IntToWstr 	Converts an integer to a wide string.

WstrToInt 	Converts a wide string to an integer.


atoi

int atoi(const TCHAR *sz);

int atoiA(const CHAR *sz);

int atoiW(const WCHAR *sz);

Converts a given string value to an integer.

•	Returns the integer value of the string.

sz

Source character string.

These versions of atoi functions only support decimal digits, and do not allow leading white-space or signs. Other versions may vary.


IntToWstr

void IntToWstr(int i, LPWSTR wstrDest);

Converts a given integer value to a wide string representation.

i

Integer value to be converted.

wstrDest

Indicator to where the resulting wide string is to be placed.


WstrToInt

int WstrToInt(LPCWSTR wstrSrc);

Converts a given wide string value to an integer.

•	Returns the integer value of the string.

wstrSrc

Source wide character string.


Error Message Function

The errors.h header file provides a function for getting an error message for a given message identifier in the current language. The same header also provides the MAX_ERROR_TEXT_LEN equate, which indicates the maximum number of characters allowed in a message.

Function

AMGetErrorText 	Gets the error message text for a given message ID.


AMGetErrorText

DWORD AMGetErrorText( HRESULT hr, TCHAR *pBuffer, DWORD MaxLen );

Retrieves the error message text for a given message identifier in the appropriate language.

•	Returns the number of characters stored in the buffer, or 0 if an error occurred.

hr

Message identifier for the message text to be returned.

pBuffer

Area into which the message text will be stored.

MaxLen

The number of characters that pBuffer points to.


Math Helper Functions

Functions

llMulDiv 	Implements ((a*b)+rnd)/c for 32-bit values of a.

Int64x32Div32 	Implements ((a*b)+rnd)/c for 64-bit values of a.


llMulDiv

LONGLONG llMulDiv(LONGLONG a, LONGLONG b, LONGLONG c,

    LONGLONG rnd);

Multiplies a by b, adds rnd to the 128-bit result, then divides by c.

•	Returns either the (a * b + rnd)/c calculation or one of the following values.

Value 	Condition

0x7FFFFFFFFFFFFFFF 	Overflow occurred because the result is too large (positive).

0x8000000000000000 	Overflow occurred because the result is too large (negative).

Rounding on the division is toward zero. Division by zero is counted as an overflow condition.


Int64x32Div32

LONGLONG Int64x32Div32(LONGLONG a, LONG b, LONG c,

    LONG rnd) ;

Multiplies a by b, adds rnd to the 96-bit result, then divides by c.

•	Returns either the (a * b + rnd)/c calculation or one of the following values.

Value 	Condition

0x7FFFFFFFFFFFFFFF 	Overflow occurred because the result is too large (positive).

0x8000000000000000 	Overflow occurred because the result is too large (negative).

Rounding on the division is toward zero. Division by zero is counted as an overflow condition.


Media Type Functions

The mtype.h header file provides helper functions for handling media types. These general-purpose functions 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.

Functions

CopyMediaType 	Copies a task-allocated AM_MEDIA_TYPE 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.


CopyMediaType

void CopyMediaType(AM_MEDIA_TYPE *pmtTarget,

    const AM_MEDIA_TYPE *pmtSource);

Copies a task-allocated AM_MEDIA_TYPE structure.

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.

The resources in the pmtTarget structure should be freed by calling FreeMediaType when the structure comes to an end of its life.


CreateMediaType

AM_MEDIA_TYPE * CreateMediaType(AM_MEDIA_TYPE *pSrc);

Creates a task-allocated AM_MEDIA_TYPE structure.

•	Returns a new AM_MEDIA_TYPE structure, or NULL if there is an error.

pSrc

Pointer to an AM_MEDIA_TYPE source structure.

The structure and resources allocated by this routine should be freed by calling DeleteMediaType when the structure comes to the end of its life.


DeleteMediaType

void DeleteMediaType(AM_MEDIA_TYPE *pmt);

Deletes a task-allocated AM_MEDIA_TYPE structure.

pmt

Pointer to an AM_MEDIA_TYPE structure.

The structure should have been created by a call to CreateMediaType.


FreeMediaType

void FreeMediaType(AM_MEDIA_TYPE& mt);

Frees a task-allocated AM_MEDIA_TYPE structure from memory.

mt

Address of the structure.

The structure should have been initialized by a call to CopyMediaType.


Object and Pin Functions

The wxutil.h header file provides helper functions for comparing objects and pins.

Functions

EqualPins 	Checks if two pins are on the same object.

IsEqualObject 	Checks if two interfaces are on the same object.


EqualPins

BOOL EqualPins(IUnknown * pPin1, IUnknown * pPin2);

Checks if two pins are on the same object.

•	Returns TRUE if the pins are both on the same object; otherwise, returns FALSE.

pPin1

Address of one pin.

pPin2

Address of the other pin.


IsEqualObject

BOOL IsEqualObject(IUnknown * pFirst, IUnknown * pSecond);

Checks if two interfaces are on the same object.

•	Returns TRUE if the interfaces are both on the same object; otherwise, returns FALSE.

pFirst

Address of one interface.

pSecond

Address of the other interface.


Property Page Helper Functions

The videoctl.h header file provides functions to help with property page implementations.

Functions

GetDialogSize 	Retrieves the size of a resource dialog 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

BOOL GetDialogSize(int iResourceID, DLGPROC pDlgProc,

    LPARAM lParam, SIZE *pResult);

Retrieves the size of a resource dialog in screen pixels.

•	Returns TRUE if the dialog resource was found; otherwise, returns FALSE.

iResourceID

Dialog box resource identifier.

pDlgProc

Pointer to the dialog procedure.

lParam

Any user data wanted in pDlgProc.

pResult

Returns the size of the dialog box.

This function can be used by property pages 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. When a property page has its GetPageInfo function called, it needs to return the actual display size in pixels. This method is passed the resource ID for the dialog box and will return its size in pixels.

To make the calculation, the function creates an instance of the dialog box. To avoid the dialog box flicking up onto the screen temporarily, the dialog's template in the resource file should not have a WS_VISIBLE property.


StringFromResource

TCHAR *StringFromResource(TCHAR *pBuffer,

    int iResourceID);

Loads a string from a resource file with the given resource identifier.

•	Returns the same string as pBuffer. If the function is not successful, returns a null string.

pBuffer

Returned string corresponding to iResourceID.

iResourceID

Resource identifier of the string to retrieve.

The pBuffer buffer must be at least STR_MAX_LENGTH bytes.


WideStringFromResource

WCHAR *WideStringFromResource(WCHAR *pBuffer,

    int iResourceID);

Loads a Unicode string from a resource file with the given resource identifier.

•	Returns the same string as pBuffer. If the function is not successful, returns a null string.

pBuffer

Returned string corresponding to iResourceID.

iResourceID

Resource identifier of the string to retrieve.

Property pages are typically called through their OLE 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.


Reference Time Functions

Functions

ConvertToMilliseconds 	Converts the reference time to milliseconds.


ConvertToMilliseconds

LONGLONG ConvertToMilliseconds(

    const REFERENCE_TIME& RT);

Converts the reference time to milliseconds.

•	Returns the reference time converted to milliseconds.

RT

Reference time, in 100-nanosecond units.


Stream Integer Functions

The pstream.h header file contains a set of stream integer functions. These functions encode an integer in an IStream as 11 Unicode characters followed by one Unicode space. The interface to these functions may truncate to 32 bits. Values such as (unsigned) 0x80000000 would be written as -2147483648 but would still load as 0x80000000 again through ReadInt.

Member Functions

WriteInt 	Writes an integer to a stream encoded as a Unicode string.

ReadInt 	Reads a Unicode string-encoded integer from a stream.


WriteInt

HRESULT WriteInt(IStream *pIStream, int n);

Writes an integer to an IStream, encoded as described in Stream Integer Functions.

•	Returns an HRESULT value.

pIStream

Pointer to an IStream to which the encoded integer is to be written.

n

Integer value to be written.

The ReadInt function can be used to read the value written by WriteInt.


ReadInt

int ReadInt(IStream *pIStream, HRESULT &hr);

Reads an integer from an IStream. This function is a stripped-down subset of what sscanf can do (without dragging in the C run time).

•	Returns the integer value (truncated to 32 bits), or zero if an error occurred.

pIStream

Pointer to an IStream from which the encoded integer is to be read.

hr

Reference to an HRESULT value (output).

The ReadInt function can be used to read the value written by WriteInt.


String Functions

The wxutil.h header file provides wide string functions, if they are not already provided by the Microsoft® Win32® environment.

Functions

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 	Gets the length of a wide string in wide characters.

wsprintfW 	Formats strings with wide format string and wide result buffer.


lstrcmpiW

int lstrcmpiW(

    LPCWSTR lpszString1,   /* address of first wide string */

    LPCWSTR lpszString2);  /* address of second wide string */

Compares two wide-character strings. The comparison is not case sensitive.

•	Returns a negative value if the function succeeds and the string pointed to by lpszString1 is less than the string pointed to by lpszString2. Returns a positive value if the string pointed to by lpszString1 is greater than the string pointed to by lpszString2. Returns zero if the strings are equal.

lpszString1

Pointer to the first null-terminated wide string to be compared.

lpszString2

Pointer to the second null-terminated wide string to be compared.

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

int lstrcmpW(

    LPCWSTR lpszString1,   /* address of first wide string */

    LPCWSTR lpszString2);  /* address of second wide string */

Compares two wide-character strings. The comparison is case sensitive.

•	Returns a negative value if the function succeeds and the string pointed to by lpszString1 is less than the string pointed to by lpszString2. Returns a positive value if the string pointed to by lpszString1 is greater than the string pointed to by lpszString2. Returns zero if the strings are equal.

lpszString1

Pointer to the first null-terminated wide string to be compared.

lpszString2

Pointer to the second null-terminated wide string to be compared.

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

LPWSTR lstrcpyW(

    LPWSTR lpszString1,    /* address of buffer */

    LPCWSTR lpszString2);  /* address of wide string to copy */

Copies a wide string to a buffer.

•	Returns a pointer to the buffer.

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.


lstrcpynW

LPWSTR lstrcpynW(

    LPWSTR lpszString1,  /* address of buffer */

    LPCWSTR lpszString2, /* address of wide string to copy */

    int     iMaxLength); /* max wide characters to copy */

Copies a wide string to a buffer, up to a specified number of wide characters.

•	Returns a pointer to the buffer.

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.

iMaxLength

Maximum number of wide characters to copy, including a terminating null character.

If iMaxLength is non-zero, lstrcpynW always inserts a terminating null wide character in the destination string, which could result in the source string being truncated.


lstrlenW

int lstrlenW(

    LPCWSTR lpszString);  /* address of wide string to count */

Returns the length, in wide characters, of the specified wide string.

•	If the function succeeds, the return value specifies the length, in wide characters, of the string.

lpszString

Pointer to a null-terminated wide string.


wsprintfW

int WINAPIV wsprintfW(LPWSTR pBuffer,

    LPCWSTR pFormat, ...);

Formats zero or more optional arguments (using pFormat to control the formatting) and copies the resulting wide string into the given buffer, pBuffer.

•	Returns the number of wide characters (not bytes) copied to the buffer, or -1 if an error occurred.

pBuffer

Pointer to an output buffer, to receive the formatted wide characters.

pFormat

printf-style format wide string.

...

Optional other arguments.


Assert Macros and Functions

Three types of assertions are provided here. The most commonly used is the ASSERT (condition) macro, which displays a message box that includes the file and line number if the condition evaluates to FALSE. There is also the EXECUTE_ASSERT macro, which is the same as ASSERT except the condition will still be executed in a build of any kind. The final type of assertion is the KASSERT macro, which is more suitable for pure (perhaps kernel) filters because the condition is printed onto the debugger rather than in a message box.

Macros and Functions

ASSERT 	Checks an assertion in a debug build.

DbgAssert 	Handles an assertion failure in a debug build.

DbgKernelAssert 	Handles a kernel assertion failure in a debug build.

EXECUTE_ASSERT 	Always evaluates a condition; if it is not TRUE in a debug build, treat this as an assertion failure.

KASSERT 	Checks a kernel assertion in a debug build.


ASSERT

ASSERT(cond);

In a debug build, if the condition evaluates to FALSE, the ASSERT macro will display a message box that includes the file name and line number.

cond

Boolean expression.

This macro is ignored unless DEBUG is defined when the Microsoft® ActiveMovie™ headers are included.


DbgAssert

void DbgAssert(const TCHAR *pCondition,

    const TCHAR *pFileName, INT iLine);

In a debug build, the DbgAssert function is called to display a message box that includes the condition text, file name, and line number. This function is available only in a debug build. Normally, DbgAssert will be called by macros such as ASSERT, not directly from other code.

pCondition

Pointer to a string version of a Boolean expression.

pFileName

Source file name.

iLine

Line number within the source file.


DbgKernelAssert

void DbgKernelAssert(const TCHAR *pCondition,

    const TCHAR *pFileName, INT iLine);

In a debug build, the DbgKernelAssert function is called to print the condition onto the debugger, including the condition text, file name, and line number. This function is available only in a debug build. Normally, DbgKernelAssert is called by macros such as KASSERT, not directly from other code.

pCondition

Pointer to a string version of a Boolean expression.

pFileName

Source file name.

iLine

Line number within the source file.


EXECUTE_ASSERT

EXECUTE_ASSERT(cond);

The condition is evaluated. In a debug build, if the condition evaluates to FALSE, the EXECUTE_ASSERT macro displays a message box that includes the file name and line number.

cond

Boolean expression that is always evaluated.


KASSERT

KASSERT(cond);

In a debug build, if the condition evaluates to FALSE, the KASSERT macro prints the condition on the debugger, including the file name and line number.

cond

Boolean expression.

This macro is ignored unless DEBUG is defined when the Microsoft ActiveMovie headers are included.


Breakpoint Macro and Functions

The breakpoint macro and functions can be used to break into the debugger in various ways and places.

Macro and Functions

DbgBreak 	Breakpoint with message box (macro).

DbgBreakPoint 	Breakpoint with message box (function).

KDbgBreak 	Breakpoint with message on debugger (debug-only function).


DbgBreak

DbgBreak(strLiteral);

In a debug build, this macro generates a message box with the indicated string literal, the source file name, and the source line number.

strLiteral

Text string, which must be in double quotes.

This macro is ignored unless DEBUG is defined when the Microsoft® ActiveMovie™ headers are included.


DbgBreakPoint

void DbgBreakPoint(const TCHAR *pCondition,

    const TCHAR *pFileName, INT iLine);

In a debug build, this function generates a message box with the indicated string literal, the source file name, and the source line number. This function is available only in a debug build.

pCondition

Pointer to a string indicating what happened.

pFileName

Source file name.

iLine

Line number within the source file.


KDbgBreak

KDbgBreak(strLiteral);

In a debug build, this macro generates a debugger message with the indicated string literal, the source file name, and the source line number.

strLiteral

Text string, which must be in double quotes.

This macro is ignored unless DEBUG is defined when the Microsoft ActiveMovie headers are included.


Debug Output

A facility for debug output (independent of the debug logging) is provided.

The debug output location is chosen by the following algorithm. (Case is ignored when comparing the strings listed.)

1	If a LogToFile value exists in the registry (under the HKEY_LOCAL_MACHINE\SOFTWARE\Debug\GLOBAL key):

•	and it has a value of "Console", the Microsoft® Win32® standard output handle is tried.

•	and it has a value of "Console", but standard output is not already opened, it allocates a console and uses that for output.

•	and it does not have the value of "Deb", "Debug", or "Debugger", a file of that name will be written to.

2	It tries the Win32 OutputDebugString function.

3	The output will be ignored if none of the above succeed.

Functions and/or Macros

DbgOutString 	Outputs a debug string.


DbgOutString

void DbgOutString(LPCTSTR psz);

Outputs the given string.

psz

Pointer to a string to be output.

DbgOutString is ignored unless DEBUG is defined when the Microsoft ActiveMovie™ headers are included. That is, it is a function in a debug-build, and a macro in other builds.


Debug Note (Trace) Macros

The NOTE macros provide trace abilities in the Microsoft® Foundation Class Library (MFC) style.

Macros

NOTE 	Logs a debug message with zero additional parameters.

NOTE1 	Logs a debug message with one additional parameter.

NOTE2 	Logs a debug message with two additional parameters.

NOTE3 	Logs a debug message with three additional parameters.

NOTE4 	Logs a debug message with four additional parameters.

NOTE5 	Logs a debug message with five additional parameters.


NOTE through NOTE5 Macros

NOTE(pFormat);

NOTE1(pFormat, a);

NOTE2(pFormat, a, b);

NOTE3(pFormat, a, b, c);

NOTE4(pFormat, a, b, c, d);

NOTE5(pFormat, a, b, c, d, e);

The NOTE through NOTE5 macros will format and print their parameters on the debugger.

pFormat

printf-style format string, which must be in double quotes.

a through e

Optional parameters, each of which must have a respective format string portion (such as "%d").

These macros are ignored unless DEBUG is defined when the Microsoft ActiveMovie™ headers are included.


Pointer Validation Macros

Macros

CheckPointer 	Checks a pointer for non-NULL and possibly returns an error code.

ValidateReadPtr 	Validates a read pointer.

ValidateReadWritePtr 	Validates a read/write pointer.

ValidateStringPtr 	Validates a string pointer.

ValidateStringPtrA 	Validates an "ANSI" string pointer.

ValidateStringPtrW 	Validates a wide (Unicode) string pointer.

ValidateWritePtr 	Validates a write pointer.


CheckPointer

CheckPointer(p, ret);

Checks a pointer, which should not be NULL. This can be used as follows:

HRESULT OneFunction(VOID *pSomeParameter)

{

    CheckPointer(pSomeParameter, E_INVALIDARG)

}

Or if the function returns a Boolean:

BOOL AnotherFunction(VOID *pSomeParameter)

{

    CheckPointer(pSomeParameter, FALSE)

}

p

Pointer value (of any type).

ret

Value to be returned from your function if p is NULL.

Be aware that this macro may return from your function.


ValidateReadPtr

ValidateReadPtr(const void * p, UINT cb);

Checks a read pointer. If the pointer is not valid, this macro calls DbgBreak.

p

Pointer value (of any type).

cb

Byte count to be checked.

This macro is ignored unless DEBUG or VFWROBUST is defined when the Microsoft® ActiveMovie™ headers are included.


ValidateReadWritePtr

ValidateReadWritePtr(const void * p, UINT cb);

Checks a read/write pointer. If the pointer is not valid, this macro calls DbgBreak.

p

Pointer value (of any type).

cb

Byte count to be checked.

This macro is ignored unless DEBUG or VFWROBUST is defined when the Microsoft ActiveMovie headers are included.


ValidateStringPtr

ValidateStringPtr(LPCTSTR p);

Checks a string pointer. If the pointer is not valid, this macro calls DbgBreak.

p

TCHAR string pointer value.

This macro is ignored unless DEBUG or VFWROBUST is defined when the Microsoft ActiveMovie headers are included.


ValidateStringPtrA

ValidateStringPtrA(LPCSTR p);

Checks an "ANSI" string pointer. If the pointer is not valid, this macro calls DbgBreak.

p

"ANSI" string pointer value.

This macro is ignored unless DEBUG or VFWROBUST is defined when the Microsoft ActiveMovie headers are included.


ValidateStringPtrW

ValidateStringPtrW(LPCWSTR p);

Checks a wide string pointer. If the pointer is not valid, this macro calls DbgBreak.

p

Wide string pointer value.

This macro is ignored unless DEBUG or VFWROBUST is defined when the Microsoft ActiveMovie headers are included.


ValidateWritePtr

ValidateWritePtr(const void * p, UINT cb);

Checks a write pointer. If the pointer is not valid, this macro calls DbgBreak.

p

Pointer value (of any type).

cb

Byte count to be checked.

This macro is ignored unless DEBUG or VFWROBUST is defined when the Microsoft ActiveMovie headers are included.


Miscellaneous Macros

Some miscellaneous macros are provided, mainly for debug string processing.

Macros

NAME 	Generates a debug-only name.

REMIND 	Generates a compile-time string.


NAME

NAME(strLiteral);

Generates a debug-only string.

strLiteral

Text string, which must be in double quotes.

This macro generates NULL unless DEBUG is defined when the Microsoft® ActiveMovie™ headers are included.


REMIND

REMIND(strLiteral);

Generates a compile-time string.

strLiteral

Text string, which must be in double quotes.

This generated string includes the parameter string, the source file name, and the line number.

For example, to generate a compile-time warning:

#pragma message (REMIND("Add automation support"))


Debug Logging by Module Level

The debug module facilities include general-purpose logging. For every module and executable, store a debugging level for each of the five categories (for example, LOG_ERROR and LOG_TIMING). This makes it easy to isolate and debug individual modules without seeing other people's spurious debug output. A level of zero means that output is always sent to the debugger.

The actual logging is accessed by calling DbgLog. The macro takes types and level fields, which define the type of informational string being presented and its relative importance. The types field can be a combination (one or more) of LOG_TIMING, LOG_TRACE, LOG_MEMORY, LOG_LOCKING, and LOG_ERROR. The level is a DWORD value, where zero is the most important. Using zero as the debug logging level is encouraged only for major errors or events because they will always be displayed on the debugger. Other debug output has its level matched against the current debug output level for this module; if it is less than or equal to the current setting, it will be displayed.

Each module or executable has its own debug output level for each of the five types. These are read in from the registry when the DbgInitialise function is called for dynamic-link libraries (DLLs) linking to strmbase.lib. This is done automatically when the DLL is loaded; executables must call it explicitly with the module instance handle given to them through the WinMain entry point. An executable must also call DbgTerminate when finished to clean up the resources the debug library uses. This also is done automatically for DLLs.

Types of Logging Information

A DWORD is used to indicate types of logging information, as indicated by the following bitmasks. Some operations may be performed on multiple types simultaneously.

LOG_TIMING 	Timing and performance measurements.

LOG_TRACE 	General step point call tracing.

LOG_MEMORY 	Memory and object allocation/destruction.

LOG_LOCKING 	Locking/unlocking of critical sections.

LOG_ERROR 	Debug error notification.

Registry Setting of Debug Levels by Type

For every module and executable ActiveMovie will load a debugging level key for each of the five types. The keys are stored in the registry under the HKEY_LOCAL_MACHINE\SOFTWARE\Debug\<Module Name>\<KeyName> key values. The allowable values for <KeyName> in the registry are: "TIMING", "TRACE", "MEMORY", "LOCKING", and "ERROR".

Functions and Macros

DbgCheckModuleLevel 	Checks if given types and levels are being logged.

DbgInitialise 	Initializes the debug library with the module handle and sets the current logging levels accordingly.

DbgLog 	Logs a message for given types and level. (Ignored except in debug builds.)

DbgLogInfo 	Logs a message for given types and level. (Not provided except in debug builds.)

DbgSetModuleLevel 	Changes the logging level for given types.

DbgTerminate 	Cleans up the debug library.

DisplayType 	Displays the given media type.


DbgCheckModuleLevel

BOOL DbgCheckModuleLevel(DWORD Types, DWORD Level);

Checks whether logging is currently enabled for the given message types and level. If logging is enabled for any of the given types at the level given, DbgCheckModuleLevel indicates that the message should be logged.

•	Returns TRUE if these module types and level are to be logged; otherwise, returns FALSE.

Types

One or more types of message, such as LOG_TIMING, masked together.

Level

Logging level for this message, where zero means always log.

DbgCheckModuleLevel is ignored unless DEBUG is defined when the Microsoft® ActiveMovie™ headers are included.


DbgInitialise

void DbgInitialise(HINSTANCE hInst);

Initializes the debug library. Among other things, it sets the current logging levels to correspond to the values that are appropriate for the indicated module.

hInst

Module instance handle.

DbgInitialise is ignored unless DEBUG is defined when the Microsoft ActiveMovie headers are included.


DbgLog

void DbgLog(DWORD Types, DWORD Level,

    const TCHAR *pFormat, ...);

Invokes the DbgLogInfo function.

Types

One or more types of message, such as LOG_TIMING, masked together.

Level

Logging level for this message, where zero means always log.

pFormat

printf-style format string, which must be in double quotes.

DbgLog is ignored unless DEBUG is defined when the Microsoft ActiveMovie headers are included.


DbgLogInfo

void DbgLogInfo(DWORD Types, DWORD Level,

    const TCHAR *pFormat,...);

If debug logging is enabled for the given message types and level, the DbgLogInfo function formats and sends the message to the debugger.

Types

One or more types of message, such as LOG_TIMING, masked together.

Level

Logging level for this message, where zero means always log.

pFormat

printf-style format string, which must be in double quotes.

DbgLogInfo exists only in debug builds.


DbgSetModuleLevel

void DbgSetModuleLevel(DWORD Types, DWORD Level);

For the message types whose bits are set in the Types parameter, DbgSetModuleLevel sets the current logging level for those types to Level. Other logging levels are unchanged.

Types

One or more types of message, such as LOG_TIMING, masked together.

Level

Logging level to be set for future messages. That is, future messages must have a level less than or equal to this value in order to be logged.

DbgSetModuleLevel is ignored unless DEBUG is defined when the Microsoft ActiveMovie headers are included.


DbgTerminate

void DbgTerminate();

Cleans up the debug library.

DbgTerminate is ignored unless DEBUG is defined when the Microsoft ActiveMovie headers are included.


DisplayType

void DisplayType(LPSTR label,

    const AM_MEDIA_TYPE *pmtIn);

Displays the media type details on the debug log. The major types and subtypes are converted into strings for display. It also asks the base classes for a string description of the subtype, so MEDIASUBTYPE_RGB565 becomes RGB 565 16-bit. In addition, it displays the fields in the BITMAPINFOHEADER structure; this should succeed because input types are not accepted unless the format is big enough.

label

Short message to be logged with the media type.

pmtIn

Pointer to the media type to be displayed.

DisplayType is ignored unless DEBUG is defined when the Microsoft ActiveMovie headers are included.


Object Register Debugging

For the CBaseObject class and classes derived from it, tracking of object creation and destruction is provided in debug builds. The object register is the list of objects (in those classes) that have been created but not yet destroyed. The "debug name" passed to the constructors of some classes gets stored in the object register.

Functions and Macros

DbgDumpObjectRegister 	Runs through the active object list, displaying their details.


DbgDumpObjectRegister

void DbgDumpObjectRegister()

Displays all objects in the object register.

DbgDumpObjectRegister is ignored unless DEBUG is defined when the Microsoft® ActiveMovie™ headers are included.


Wait Debugging

Facilities are provided for wait debugging. These build on the Microsoft® Win32® HANDLE-based wait facilities, but they may be expanded upon to debug specific wait conditions.

In the debug build, the global current time-out may be updated by calls to DbgSetWaitTimeout. (Note that updating the "current time-out" does not affect debug wait calls that are already waiting.) The initial "current time-out" value is set as follows:

1	If this is a debug build, and a value named TIMEOUT exists in the registry under the HKEY_LOCAL_MACHINE\SOFTWARE\Debug\GLOBAL key, that value is used. (It must be a REG_DWORD value, and it is treated as being in milliseconds.)

2	Otherwise, the default time-out value is INFINITE.

Functions and/or Macros

DbgSetWaitTimeout 	Changes the current time-out value.

DbgWaitForMultipleObjects 	Waits for an array of handles to be signaled, or for the "current time-out" to expire.

DbgWaitForSingleObject 	Waits for a handle to be signaled, or for the "current time-out" to expire.


DbgSetWaitTimeout

void DbgSetWaitTimeout(DWORD dwTimeout);

Updates the global "current time-out" value. (This update does not apply to waits already in effect.)

dwTimeout

The new time-out value in milliseconds, or INFINITE.

DbgSetWaitTimeout is ignored unless DEBUG is defined when the Microsoft® ActiveMovie™ headers are included.


DbgWaitForMultipleObjects

DWORD DbgWaitForMultipleObjects(DWORD nCount,

    CONST HANDLE *lpHandles, BOOL bWaitAll);

In a debug build, waits for the "current time-out," or the array of handles to become signaled.

In other builds, this is treated as a call to the Microsoft Win32® WaitForMultipleObjects function, with an INFINITE time-out.

nCount

Number of entries in the lpHandles array.

lpHandles

Array of HANDLE values.

bWaitAll

TRUE if all handles in the array must become signaled to satisfy the wait. FALSE if any one handle may satisfy the wait.


DbgWaitForSingleObject

DWORD DbgWaitForSingleObject(HANDLE h);

In a debug build, waits for the "current time-out," or the given handle to become signaled.

In other builds, this is treated as a call to the Microsoft Win32 WaitForSingleObject function, with an INFINITE time-out.

h

HANDLE value.


Structures

The Microsoft® ActiveMovie™ structures are described in this section.

Structure 	Meaning

ALLOCATOR_PROPERTIES 	Contains the count, size, alignment, and prefix properties of the allocator.

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_MEDIA_TYPE 	Describes a media sample type.

FILTER_STATE 	Describes the state of a filter.

FILTER_INFO 	Contains information about a filter.

PIN_DIRECTION 	Describes the direction of a pin.

PIN_INFO 	Contains information about a pin.

REGFILTER 	Describes a filter in the registry.

Quality 	Describes a quality message.

QualityMessageType 	Describes a quality message type.

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 	Meaning

DIBDATA 	Contains information about each DIB.

The following structures maintain information about the video.

Structure 	Meaning

ANALOGVIDEOINFO 	Maintains information about the format of the analog video signal.

COLORKEY 	Communicates color key information between the renderer and another filter.

VIDEOINFO 	Maintains information about the video.

VIDEOINFOHEADER 	Maintains information about the video header.

TRUECOLORINFO 	Maintains color information.

MPEG1VIDEOINFO 	Contains additional MPEG1 video system information.


ALLOCATOR_PROPERTIES

typedef struct _AllocatorProperties {

    long cBuffers;

        long cbBuffer;

           long cbAlign;

    long cbPrefix;

} ALLOCATOR_PROPERTIES;

Contains the count, size, alignment, and prefix properties of the allocator.

cBuffers

Count of buffers at this 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.

The CMediaSample::GetPointer member function points 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. Since the buffer pointer returned by IMediaSample::GetPointer points to the area immediately following the prefix, the cbPrefix address (the value returned by IMediaSample::GetPointer minus cbPrefix) should be aligned on an address that is a multiple of cbAlign bytes.


AMOVIESETUP_FILTER

typedef struct _AMOVIESETUP_FILTER

{

    const CLSID * clsID;

    LPWSTR     strName;

    DWORD      dwMerit;

    UINT       nPins;

    LPAMOVIESETUP_PIN lpPin;

}

AMOVIESETUP_FILTER

Contains filter information for registering a filter.

clsID

Class identifier of the filter.

strName

Name of the filter.

dwMerit

Merit used by the GraphBuilder when constructing a filter graph.

nPins

Number of pins on the filter.

lpPin

AMOVIESETUP_PIN structure providing pin information.


AMOVIESETUP_MEDIATYPE

typedef struct _AMOVIESETUP_MEDIATYPE

{

    const CLSID * clsMajorType;

    const CLSID * clsMinorType;

} AMOVIESETUP_MEDIATYPE;

Media type information for registering a filter.

clsMajorType

Major media type supported by the filter.

clsMinorType

Minor media type supported by the filter.


AMOVIESETUP_PIN

typedef struct _AMOVIESETUP_PIN

{

    LPWSTR           strName;

    BOOL             bRendered;

    BOOL             bOutput;

    BOOL             bZero;

    BOOL             bMany;

    const CLSID *    clsConnectsToFilter;

    LPWSTR           strConnectsToPin;

    UINT             nMediaTypes;

    LPAMOVIESETUP_MEDIATYPE lpMediaType;

}

AMOVIESETUP_PIN;

Pin information for registering a filter.

strName

Name of the pin.

bRendered

Set to TRUE if the filter renders this input; otherwise, set to FALSE.

bOutput

Flag to indicate if this pin is an output pin.

bZero

If the filter has zero instances of this pin, set this to TRUE; otherwise, set to FALSE. For example, a decompression filter might choose not to create a sound output pin for a movie without a sound track.

bMany

If the filter has many instances of this pin, set this to TRUE; otherwise, set to FALSE. For example, a mixer might have multiple instances of its input pin.

clsConnectsToFilter

CLSID of the filter to which this filter connects in a filter graph.

strConnectsToPin

Name of the pin to which this pin connects in a filter graph.

nMediaTypes

Number of media types supported by this pin.

lpMediaType

AMOVIESETUP_MEDIATYPE structure providing media type information.


AM_MEDIA_TYPE

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;

Describes a media sample type.

majortype

Major type of the media sample.

subtype

Subtype of the media sample.

bFixedSizeSamples

If TRUE, samples are of a fixed size.

bTemporalCompression

If TRUE, samples are compressed.

lSampleSize

Size of the sample in bytes.

formattype

Registered (GUID) format type.

pUnk

Pointer to the IUnknown interface.

cbFormat

Size of the format section of the media type.

pbFormat

Pointer to the format section of the media type. The layout of this is determined by the format type GUID. Format types include the following.

Format type 	Structure pointed to

FORMAT_VideoInfo 	VIDEOINFO

FORMAT_WaveFormatEx 	WAVEFORMATEX

FORMAT_MPEGVideo 	MPEG1VIDEOINFO


ANALOGVIDEOINFO

typedef struct tagAnalogVideoInfo {

    RECT            rcSource;

    RECT            rcTarget;

    DWORD           dwActiveWidth;

    DWORD           dwActiveHeight;

    REFERENCE_TIME  AvgTimePerFrame;

} ANALOGVIDEOINFO;

Maintains information about the format of the analog video signal.

rcSource

Source video rectangle.

rcTarget

Destination target rectangle.

dwActiveWidth

Source video width (always 720).

dwActiveHeight

Source video height (483 for NTSC, 575 for PAL/SECAM).

AvgTimePerFrame

Average time per frame in 100-nanosecond units.

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.


COLORKEY

typedef struct tagCOLORKEY

    {

    DWORD           KeyType;

    DWORD           PaletteIndex;

    COLORREF        LowColorValue;

    COLORREF        HighColorValue;

    }    COLORKEY;

Communicates color key information between the renderer and another filter.

KeyType

Key type.

PaletteIndex

Palette index.

LowColorValue

Lowest RGB color value.

HighColorValue

Highest RGB color value.

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

typedef struct tagDIBDATA {

LONG        PaletteVersion;     // Internal palette version token

    DIBSECTION  DibSection;     // Details of DIB section allocated

    HBITMAP     hBitmap;        // Handle to bitmap from DIB buffer

    HANDLE      hMapping;       // Handle to shared memory block

    BYTE        *pBase;         // Pointer to base memory address

} DIBDATA;

Maintains information about each GDI DIB.

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.

All the samples created from the allocator will have a DIBSECTION allocated to them. When a sample is received, a BitBlt can be performed to the window. This is a mechanism for the image allocator, an image sample, and the draw class to communicate bitmap information between them.


FILTER_INFO

typedef struct  _FilterInfo

    {

    /* [string] */ WCHAR achName[ 128 ];

    IFilterGraph __RPC_FAR *pGraph;

    }     FILTER_INFO;

Contains information about a filter.

achName

Name of the filter.

pGraph

Pointer to the IFilterGraph interface to which the filter is connected.


FILTER_STATE

typedef enum _FilterState

   {   State_Stopped   = 0,

       State_Paused    = State_Stopped + 1,

       State_Running   = State_Paused + 1

    }  FILTER_STATE;

Describes the state of a filter.

State_Stopped

Equal to 0. The filter is not processing data.

State_Paused

Equal to 1. The filter is processing but not rendering data.

State_Running

Equal to 2. The filter is processing and rendering data.


MPEG1VIDEOINFO

typedef struct tagMPEG1VIDEOINFO {

    VIDEOINFOHEADER hdr;

    DWORD           dwStartTimeCode;

    DWORD           cbSequenceHeader;

    BYTE            bSequenceHeader[1];

} MPEG1VIDEOINFO;

Describes an MPEG1 video stream.

hdr

Compatible with VIDEOINFO.

dwStartTimeCode

25-bit "group-of-pictures" time code at start of data.

cbSequenceHeader

Length in bytes of bSequenceHeader.

bSequenceHeader[1]

Sequence header including quantization matrices, if any.


PIN_DIRECTION

typedef enum _PinDirection {

    PINDIR_INPUT,

    PINDIR_OUTPUT

} PIN_DIRECTION;

Describes the direction of a pin.

PINDIR_INPUT

Input pin.

PINDIR_OUTPUT

Output pin.


PIN_INFO

typedef struct  _PinInfo

    {

    IFilter __RPC_FAR *pFilter;

    PIN_DIRECTION dir;

    /* [string] */ WCHAR achName[ 128 ];

    }        PIN_INFO;

Contains information about a pin.

pFilter

Pointer to the IFilter interface of the owning filter.

dir

Direction of the pin (input or output).

achName

Name of the pin.


REGFILTER

typedef struct {

    CLSID Clsid;

    LPWSTR Name;

} REGFILTER;

Identifies a filter in the registry.

Clsid

Class identifier of the filter.

Name

Name of the filter.


Quality

typedef struct{

    QualityMessageType Type;

    long     Proportion;   // milli-units. 1000 = no change.

                 // For Flood:

                 // What proportion of the media samples

                 // currently coming through are required

                 // in the future. 800 means please drop

                 // another 20 percent.

                 // For Famine:

                 // How much to "keep in"; for example, 800 means

                 // send me 20 percent less, perhaps by dropping

                 // 20 percent of the samples.

                 // 1100 would mean "I'm coping, send me more."

    REFERENCE_TIME    Late;

                 // How much you need to catch up by.

} Quality;

Describes a quality message.

Type

Either Famine or Flood, indicating that more or less data is needed by a downstream filter.

Late

If a famine exists downstream, this is the amount of time by which the stream is lagging.


QualityMessageType

typedef enum {

    Famine,

    Flood

} QualityMessageType;

Describes a quality message type.

Famine

More data is needed by a downstream filter.

Flood

Less data is needed by a downstream filter.


TRUECOLORINFO

typedef struct tag_TRUECOLORINFO {

    DWORD dwBitMasks[iMASK_COLORS];

    RGBQUAD bmiColors[iPALETTE_COLORS];

} TRUECOLORINFO;

Maintains color information.

dwBitMasks[iMASK_COLORS]

Array of color masks (one per color element).

bmiColors[iPALETTE_COLORS]

Array of palette colors.

This is a part of the larger VIDEOINFO structure that also contains a VIDEOINFOHEADER structure. This particular structure holds a palette and a set of color bit masks. This is not used for some RGB formats. For more information about which fields are valid under different circumstances, see the Microsoft Win32® documentation for BITMAPINFO.


VIDEOINFOHEADER

typedef struct tagVIDEOINFOHEADER {

    RECT                rcSource,

    RECT                rcTarget;

    DWORD               dwBitRate;

    DWORD               dwBitErrorRate;

    REFERENCE_TIME      AvgTimePerFrame;

    BITMAPINFOHEADER    bmiHeader;

} VIDEOINFOHEADER;

Maintains information about the video.

rcSource

Bit 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 (100-nanosecond units).

bmiHeader

Average time per frame (100-nanosecond units).

ActiveMovie filters interested in exchanging video data use the VIDEOINFO structure to describe the video format. The VIDEOINFO structure comprises three principle parts. The first part is VIDEOINFOHEADER, which describes source and destination rectangles, bit rates, and time information. The next part is BITMAPINFOHEADER, as described in the Microsoft Win32 documentation. The final part is TRUECOLORINFO, which holds palette and true color bit masks.


VIDEOINFO

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;

Describes the format of a video stream.

rcSource

Bit 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 (100-nanosecond units).

bmiHeader

Bitmap header.

bmiColors[iPALETTE_COLORS]

Array of palette colors.

dwBitMasks[iMASK_COLORS]

Array of color element bit masks.

TrueColorInfo

TRUECOLORINFO structure.

ActiveMovie filters that exchange video data use the VIDEOINFO structure to describe the video format. The VIDEOINFO structure comprises three principle parts. The first part is VIDEOINFOHEADER, which describes source and destination rectangles, bit rates, and time information. The next part is BITMAPINFOHEADER, as described in the Microsoft Win32 documentation. The final part is TRUECOLORINFO, which holds palette and true color bit masks.

The five fields at the start of the structure are equivalent to VIDEOINFOHEADER. They are expanded in full simply to reduce the amount of dereferencing needed when dealing with a pointer to a VIDEOINFO structure.

Which of the TRUECOLORINFO, dwBitMasks, and bmiColors fields are valid depends on the contents of the BITMAPINFOHEADER structure. For more information, see the Microsoft Win32 documentation on BITMAPINFO.


Error Messages

The following error messages are defined for returning HRESULT error conditions specific to ActiveMovie™. (You can call AMGetErrorText to get the text for any of these message IDs.) They are listed in alphabetical order. Note that the text here may not exactly match the text returned by AMGetErrorText, even if the current language is English.

VFW_E_ADVISE_ALREADY_SET 	An overlay advise link already exists.

VFW_E_ALREADY_CANCELLED 	Queued command has already been canceled.

VFW_E_ALREADY_COMMITTED 	Already in a committed state; must decommit.

VFW_E_ALREADY_CONNECTED 	Connection has already been made to a pin.

VFW_E_BAD_KEY 	A registry entry is corrupt.

VFW_E_BADALIGN 	Buffers cannot be set with this alignment.

VFW_E_BUFFER_NOTSET 	No buffer space has been set.

VFW_E_BUFFER_OVERFLOW 	Data length is greater than buffer size.

VFW_E_BUFFERS_OUTSTANDING 	Buffers are already assigned to the allocator.

VFW_E_CANNOT_CONNECT 	No combination of intermediate filters could be found to make the connection work.

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_CHANGING_FORMAT 	Could not change formats dynamically.

VFW_E_CIRCULAR_GRAPH 	Filter graph is circular.

VFW_E_COLOR_KEY_SET 	Setting a palette would conflict with the color key already set.

VFW_E_CORRUPT_GRAPH_FILE 	Cannot render the file because it is corrupt.

VFW_E_DUPLICATE_NAME 	An attempt to add a filter with a duplicate name failed.

VFW_E_ENUM_OUT_OF_RANGE 	Called an enumeration routine when the list has already been exhausted.

VFW_E_ENUM_OUT_OF_SYNC 	The enumerator has become invalid because the item being enumerated has changed.

VFW_E_FILE_TOO_SHORT 	A file appeared to contain valid information, but stopped before the end.

VFW_E_FILTER_ACTIVE 	Filter is active; must be stopped or paused.

VFW_E_IN_FULLSCREEN_MODE 	Cannot call IVideoWindow methods while in full-screen mode.

VFW_E_INVALID_CLSID 	This file is corrupt: it contains an invalid class identifier.

VFW_E_INVALID_DIRECTION 	Direction (Input or Output) is invalid.

VFW_E_INVALID_FILE_FORMAT 	A file parser discovered that the file does not have the correct format.

VFW_E_INVALID_FILE_VERSION 	The version number in the file was either meaningless or newer than the program reading it.

VFW_E_INVALID_RECT 	The supplied rectangle was invalid.

VFW_E_INVALID_MEDIA_TYPE 	This file is corrupt: it contains an invalid media type.

VFW_E_INVALIDMEDIATYPE 	Media major type is invalid.

VFW_E_INVALIDSUBTYPE 	Media subtype is invalid.

VFW_E_MEDIA_TIME_NOT_SET 	No media time stamp has been set for this sample.

VFW_E_MONO_AUDIO_HW 	Cannot support put_Balance because audio support is mono only.

VFW_E_MPEG_NOT_CONSTRAINED 	ActiveMovie cannot play this video stream because it falls outside the constrained standard.

VFW_E_NEED_OWNER 	This object can only be created as an aggregated object.

VFW_E_NO_ACCEPTABLE_TYPES 	There are no acceptable types.

VFW_E_NO_ADVISE_SET 	Called IOverlay::Unadvise before IOverlay::Advise was successful.

VFW_E_NO_ALLOCATOR 	No allocator exists.

VFW_E_NO_AUDIO_HARDWARE 	Cannot play back the audio stream: no audio hardware is available, or the hardware is not responding.

VFW_E_NO_CLOCK 	Cannot lock for synchronization because no clock has been defined.

VFW_E_NO_COLOR_KEY_FOUND 	No matching color key was available.

VFW_E_NO_COLOR_KEY_SET 	No color key has been set.

VFW_E_NO_DECOMPRESSOR 	Cannot play back the video stream: no suitable decompressor could be found.

VFW_E_NO_DISPLAY_PALETTE 	Display does not use a palette.

VFW_E_NO_FULLSCREEN 	No full screen was available for the graph.

VFW_E_NO_INTERFACE 	A required interface is not implemented.

VFW_E_NO_MODEX_AVAILABLE 	No full-screen modes are available.

VFW_E_NO_PALETTE_AVAILABLE 	No palettes are available for use.

VFW_E_NO_SINK 	No quality sink exists (neither default nor explicit).

VFW_E_NO_TIME_FORMAT_SET 	No media time format has yet been selected through IMediaSelection.

VFW_E_NO_TYPES 	There are no types available.

VFW_E_NOT_ALLOWED_TO_SAVE 	The filter graph has persistent storage in a state that does not allow updating.

VFW_E_NOT_COMMITTED 	Cannot allocate a sample when the allocator is not active.

VFW_E_NOT_CONNECTED 	The operation cannot be performed because the pins are not connected.

VFW_E_NOT_FOUND 	An object or name that was searched for was not found.

VFW_E_NOT_OVERLAY_CONNECTION 	Current pin connection is not using the IOverlay transport.

VFW_E_NOT_IN_GRAPH 	Cannot perform the requested function on an object that is not in the filter graph.

VFW_E_NOT_PAUSED 	The operation could not be performed because the filter is not paused.

VFW_E_NOT_RUNNING 	The operation could not be performed because the filter is not running.

VFW_E_NOT_SAMPLE_CONNECTION 	Current pin connection is not using IMemInputPin transport.

VFW_E_NOT_STOPPED 	The operation could not be performed because the filter is not stopped.

VFW_E_PALETTE_SET 	Setting a color key would conflict with the palette already set.

VFW_E_PROCESSOR_NOT_SUITABLE 	ActiveMovie cannot play MPEG movies on this processor.

VFW_E_RPZA 	Cannot play back the video stream: format 'RPZA' is not supported.

VFW_E_RUNTIME_ERROR 	A run-time error has occurred.

VFW_E_SAMPLE_REJECTED 	Filter rejected the sample (reason not stated).

VFW_E_SAMPLE_REJECTED_EOS 	Filter rejected the sample because the end of stream has been reached.

VFW_E_SAMPLE_TIME_NOT_SET 	No time stamp has been set for this sample.

VFW_E_SIZENOTSET 	Must set size before continuing.

VFW_E_START_TIME_AFTER_END 	The sample start time was later than the sample end time.

VFW_E_STATE_CHANGED 	The state changed while waiting to process the sample.

VFW_E_TIMEOUT 	A function with a time limit has timed out rather than completing.

VFW_E_TIME_ALREADY_PASSED 	Attempt to queue a command for a time in the past.

VFW_E_TOO_MANY_COLORS 	Too many colors for the current display settings.

VFW_E_TYPE_NOT_ACCEPTED 	ReceiveConnection rejected the media type passed in.

VFW_E_UNKNOWN_FILE_TYPE 	The media type of this file is not recognized.

VFW_E_UNSUPPORTED_AUDIO 	Cannot play back the audio stream: the audio format is not supported.

VFW_E_UNSUPPORTED_VIDEO 	Cannot play back the video stream: the video format is not supported.

VFW_E_WRONG_STATE 	The filter is in the wrong state to succeed.

VFW_S_AUDIO_NOT_RENDERED 	Cannot play back the audio stream: no audio hardware is available.

VFW_S_CONNECTIONS_DEFERRED 	Some connections have failed and have been deferred.

VFW_S_DUPLICATE_NAME 	An attempt to add a filter with a duplicate name succeeded with a modified name.

VFW_S_MEDIA_TYPE_IGNORED 	A connection could not be made with the media type in the persistent graph (the graph file), but has been made with a default (negotiated) media type.

VFW_S_NO_MORE_ITEMS 	The end of the list has been reached.

VFW_S_PARTIAL_RENDER 	Some streams were rendered but not all.

VFW_S_RESOURCE_NOT_NEEDED 	The resource specified is no longer needed.

VFW_S_RPZA 	Cannot play back the video stream: format 'RPZA' is not supported.

VFW_S_SOME_DATA_IGNORED 	The file contained some property settings that were not used.

VFW_S_STATE_INTERMEDIATE 	State transition has not completed.

VFW_S_VIDEO_NOT_RENDERED 	Cannot play back the video stream: no suitable decompressor could be found.


Reserved Identifiers

When compiling programs that include the Microsoft® ActiveMovie™ header files, it is important to be aware of the following identifiers and their meanings if they are defined before the ActiveMovie headers are included.

These identifiers are, in effect, reserved except as listed below.

DEBUG 	Indicates a debug build. This enables many debug facilities, including message logging and assertion checking.

PERF 	Indicates a performance (measurement) build.

VFWROBUST 	Enables some pointer validation macros in a build of any kind. See ValidateReadPtr and related macros for more specifics.

Build Types

A retail build is the smallest and fastest build, although perhaps not as robust as a debug build. A retail build is the default if neither a debug build nor a performance build is requested.

A debug build is generally the largest and slowest build. However, it provides better facilities for debugging new code and tracking problems. Defining the DEBUG identifier requests a debug build.

A performance build adds measurement capabilities to a retail build. Defining the PERF identifier requests a performance build. The performance build requires one additional file: Measure.dll.

Caveat: Mixing Build Types

If debug and retail binaries are mixed, the results are undefined.


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 	Returns the item specified by the index into the collection.


Count Property (IAMCollection Object)

Returns the number of items in the collection. Read-only. Long.

Syntax

objCollection.Count

Parts

objCollection

Required. An object expression that evaluates to an IAMCollection object.


Item Method (IAMCollection Object)

Retrieves the item specified by the index into the collection. Read-only.

Syntax

 objCollection.Item lItem, objNew

Parts

objCollection

An object expression that evaluates to an IAMCollection object.

lItem

Required. Long. The index of the contained item.

objNew

Required. An object expression that can evaluate to an IFilterInfo, IPinInfo, or IMediaTypeInfo object depending on the collection type.

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)

Sets or returns the balance of the audio channel. Long.

Syntax

objAudio.Balance [= lValue ]

Parts

objAudio

Required. An object expression that evaluates to an IBasicAudio object.

lValue

Long. Specifies the 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.

When you try to set the balance property to values outside this range, the IBasicAudio object raises an error (VFW_E_INVALIDARG).


Volume Property (IBasicAudio Object)

Sets or returns the volume of the audio channel. Long.

Syntax

objAudio.Volume [= lValue]

Parts

objAudio

Required. An object expression that evaluates to an IBasicAudio object.

lValue

Long. Specifies the new value for the volume property.

Remarks

The allowable input range is -10,000 to 0. Values outside this range will return an VFW_E_INVALIDARG error. Full volume is 0; -10,000 is silence. The scale is linear.

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 IBasicVideo object methods require only that the video renderer be connected. If it is not connected, all methods return an VFW_E_NOT_CONNECTED error. 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 may 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 the rectangles that IBasicVideo uses employ top, left, width, and height, as in other Visual Basic® programming. 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 (ns) 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.

IsUsingDefaultDestination 	Indicates whether the default destination is being used.

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)

Retrieves the average time between successive frames in 100-nanosecond (ns) units. Read-only. Double.

Syntax

objVideo.AvgTimePerFrame

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.


BitErrorRate Property (IBasicVideo Object)

Retrieves a bit error rate for the video stream (one error for approximately this many bits). Read-only. Long.

Syntax

objVideo.BitErrorRate

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.


BitRate Property (IBasicVideo Object)

Retrieves an approximate bit rate for the video stream (in bits per second). Read-only. Long.

Syntax

objVideo.BitRate

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.


DestinationHeight Property (IBasicVideo Object)

Retrieves or sets the height of the destination rectangle. Long.

Syntax

objVideo.DestinationHeight [= lValue]

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

lValue

Specifies the new value for the destination rectangle height.

Remarks

Setting this coordinate does not affect the destination rectangle y-axis origin.


DestinationLeft Property (IBasicVideo Object)

Retrieves or sets the destination x-axis origin coordinate.

Syntax

objVideo.DestinationLeft [= lValue]

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

lValue

Optional. Specifies the new value of the destination x-axis origin.

Remarks

Setting this coordinate does not affect the destination rectangle width.


DestinationTop Property (IBasicVideo Object)

Retrieves or sets the destination y-axis origin coordinate.

Syntax

objVideo.DestinationTop [= lValue]

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

lValue

Optional. Specifies the new value of the y-axis origin.

Remarks

Setting this coordinate does not affect the destination rectangle height.


DestinationWidth Property (IBasicVideo Object)

Retrieves or sets the width of the destination rectangle.

Syntax

objVideo.DestinationWidth [= lValue]

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

lValue

Specifies the new width value.

Remarks

Setting this coordinate does not affect the destination rectangle x-axis origin.


GetCurrentImage Method (IBasicVideo Object)

Retrieves the image currently waiting at the renderer.

Syntax

objVideo.GetCurrentImage BufferSize, DIBImage

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

BufferSize

Long. Specifies the size of the buffer the caller is passing in. Returns the actual number of bytes in the buffer.

DIBImage

Long. Returns the buffer where the complete image will be stored in device-independent bitmap (DIB) format.

Remarks

Pause the video renderer before calling this method; calling this method in any other state returns VFW_E_NOT_PAUSED. 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.

An application can use this method to get a copy of the current image the video renderer holds when paused. The size of the buffer required to hold the image can be obtained by calling the 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.

When called successfully, 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-, 16-, or 8-bit palettized image.


GetDestinationPosition Method (IBasicVideo Object)

Retrieves the position of the destination rectangle in window coordinates.

Syntax

objVideo.GetDestinationPosition Left, Top, Width, Height

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

Left

Long. Returns the x-axis origin of the destination window.

Top

Long. Returns the y-axis origin of the destination window.

Width

Long. Returns the width of the destination window.

Height

Long. Returns the height of the destination window.

Remarks

This method has the same effect as individually retrieving the DestinationLeft, DestinationTop, DestinationWidth, and DestinationHeight properties.


GetSourcePosition Method (IBasicVideo Object)

Retrieves the source position that is clipped to the available video.

Syntax

objVideo.GetSourcePosition Left, Top, Width, Height

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

Left

Long. Returns the x-axis origin of the source window.

Top

Long. Returns the y-axis origin of the source window.

Width

Long. Returns the width of the source window.

Height

Long. Returns the height of the source window.

Remarks

This method has the same effect as retrieving the values of the SourceLeft, SourceTop, SourceWidth, and SourceHeight properties.


GetVideoPaletteEntries Method (IBasicVideo Object)

Retrieves the palette colors for the video.

Syntax

objVideo.GetVideoPaletteEntries StartIndex, Entries, Retrieved, Palette

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

StartIndex

Long. Specifies the start index for the palette.

Entries

Long. Specifies the number of palette entries required.

Retrieved

Long. Returns the number of entries actually returned in Palette.

Palette

Returns a pointer to an array of Microsoft Win32 PALETTEENTRY structures.

Remarks

An application can query the colors required by the video with this method. An application can pass in a NULL Palette parameter, and the Retrieved parameter is filled in with the number of colors currently in use. The Palette 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.

This method was modeled on the Win32 GetSystemPaletteEntries function.


GetVideoSize Method (IBasicVideo Object)

Retrieves the native video dimensions.

Syntax

objVideo.GetVideoSize Width, Height

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

Width

Long. Returns the width of the video window.

Height

Long. Returns the height of the video window.

Remarks

Retrieves the native video width and height, disregarding any source rectangle that may have been set. ActiveX™ controls or other applications may use this information to negotiate space in compound documents.


IsUsingDefaultDestination Method (IBasicVideo Object)

Returns a Boolean value. True indicates that the IBasicVideo object is using the default destination; False indicates that it is not.

Syntax

objVideo.IsUsingDefaultDestination

Remarks

Returns a flag value.


IsUsingDefaultSource Method (IBasicVideo Object)

Returns a Boolean value. True indicates that the IBasicVideo object is using the default source; False indicates that it is not.

Syntax

objVideo.IsUsingDefaultSource

Remarks

Returns a flag value.


SetDefaultDestinationPosition Method (IBasicVideo_Object)

Sets the default destination position of the video window so that the renderer uses the entire window for playback.

Syntax

objVideo.SetDefaultDestinationPosition


SetDefaultSourcePosition Method (IBasicVideo Object)

Informs the renderer to use the default source rectangle.

Syntax

objVideo.SetDefaultSourcePosition


SetDestinationPosition Method (IBasicVideo Object)

Sets the destination rectangle in window coordinates.

Syntax

objVideo.SetDestinationPosition Left, Top, Width, Height

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

Left

Required. Long. Specifies the x-axis origin of the destination window.

Top

Required. Long. Specifies the y-axis origin of the destination window.

Width

Required. Long. Specifies the width of the destination window.

Height

Required. Long. Specifies the height of the destination window.

Remarks

This method has the same effect as setting the DestinationLeft, DestinationTop, DestinationWidth, and DestinationHeight properties individually.


SetSourcePosition Method (IBasicVideo Object)

Sets the source rectangle and is clipped against the available video.

Syntax

objVideo.SetSourcePosition Left, Top, Width, Height

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

Left

Required. Long. Specifies the x-axis origin of the source window.

Top

Required. Long. Specifies the y-axis origin of the source window.

Width

Required. Long. Specifies the width of the source window.

Height

Required. Long. Specifies 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)

Retrieves or sets the height of the source rectangle. Long.

Syntax

objVideo.SourceHeight [= lValue]

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

lValue

Long. Returns the current rectangle height.

Remarks

Setting the height of the source rectangle has no effect on the width and other source values.


SourceLeft Property (IBasicVideo Object)

Retrieves or sets the source rectangle x coordinate. Long.

Syntax

objVideo.SourceLeft [= lValue]

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

lValue

Specifies the 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)

Retrieves or sets the source rectangle y-axis origin coordinate. Long.

Syntax

objVideo.SourceTop [= lValue]

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

lValue

Long. Returns the new top coordinate.

Remarks

Setting this method has no effect on the source rectangle height.


SourceWidth Property (IBasicVideo Object)

Retrieves or sets the source rectangle width.

Syntax

objVideo.SourceWidth [= lValue]

Parts

objVideo

Required. An object expression that evaluates to an IBasicVideo object.

lValue

Long. Returns the current width.

Remarks

This method has no effect on the source rectangle x-axis coordinate.


VideoHeight Property (IBasicVideo Object)

Retrieves the native height of the video. Read-only. Long.

Syntax

objVideo.VideoHeight

Parts

objVideo

Required. An 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 may be used by applications to negotiate size requirements with in-place OLE documents.


VideoWidth Property (IBasicVideo Object)

Retrieves the native width of the video. Read-only. Long.

Syntax

objVideo.VideoWidth

Parts

objVideo

Required. An 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 may be used by applications to negotiate size requirements with in-place OLE 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)

Retrieves or sets the name of the file containing the filter.

Syntax

objFilterInfo.Filename [= string]

Parts

objFilterInfo

Required. An object expression that evaluates to an IFilterInfo object.

string

Contains a string expression that specifies the new name of the file.


Filter Property (IFilterInfo Object)

Retrieves the filter object.

Syntax

Set objFilter = objFilterInfo.Filter

Parts

objFilterInfo

Required. An object expression that evaluates to an IFilterInfo object.

objFilter

Returns an IFilter object.

Remarks

No programmable object interface is offered for the IFilter interface. However, Visual Basic® programmers can use the returned object as a parameter in calls to functions that take the IFilter interface pointer as a parameter.


FindPin Method (IFilterInfo Object)

Locates a pin, given an identifier, and returns an IPinInfo object.

Syntax

objFilterInfo.FindPin string, objPin

Parts

objFilterInfo

Required. An object expression that evaluates to an IFilterInfo object.

string

Evaluates to a string expression that identifies the pin that is to be found and returned in the objPin object.

objPin

Returns the IPin object.

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)

Determines if the file contains the source video. Read-only. Boolean.

Syntax

objFilterInfo.IsFileSource

Parts

objFilterInfo

Required. An object expression that evaluates to an IFilterInfo object.

Return Values

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)

Retrieves the filter name. Read-only. String.

Syntax

objFilterInfo.Name

Parts

objFilterInfo

Required. An object expression that evaluates to an IFilterInfo object.

Remarks

The vendor specifies the filter name.


Pins Property (IFilterInfo Object)

Retrieves an IAMCollection object containing the IPinInfo objects for this filter.

Syntax

Set objPinCollection = objFilterInfo.Pins

Parts

objPinCollection

Returns the IAMCollection object.

objFilterInfo

Required. An object expression that evaluates to an IFilterInfo object.

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)

Retrieves a string containing optional information supplied by a vendor about the specified filter. Read-only. String.

Syntax

objFilterInfo.VendorInfo

Parts

objFilterInfo

Required. An 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)

Adds to the graph the source filter that can read the given file name, and returns the created IFilterInfo object.

Syntax

objMediaControl.AddSourceFilter string, objFilterInfo

Parts

objMediaControl

Required. An object expression that evaluates to an IMediaControl object.

string

The name of the file containing the source media.

objFilterInfo

The IFilterInfo object; the source filter created for the specified source file.


FilterCollection Property (IMediaControl Object)

Retrieves a collection of IFilterInfo objects representing the filters in the graph. Returns an IAMCollection object. Read-only.

Syntax

Set objCollection = objMediaControl.FilterCollection

Parts

objCollection

The IAMCollection object that represents the collection of filters currently present in the filter graph.

objMediaControl

Required. An object expression that evaluates to an IMediaControl object. Read-only.


GetState Method (IMediaControl Object)

Returns a long integer indicating the current state value.

Syntax

objMediaControl.GetState msTimeout, State

Parts

objMediaControl

Required. An object expression that evaluates to an IMediaControl object.

msTimeout

Duration of the time-out, in milliseconds. To block indefinitely, pass INFINITE.

State

Long. Returns the current state. The following values are defined.

Value	Description

State_Stopped 	The media source is currently stopped.

State_Paused 	The media source is currently paused.

State_Running 	The media source is currently running.

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 S_OK 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 VFW_S_STATE_INTERMEDIATE, and the returned state will be the state into which the graph is transitioning (either State_Stopped, State_Paused, or State_Running).

If you specify an infinite time-out, the method does not return VFW_S_STATE_INTERMEDIATE. A call on another thread to change the state while this method is blocked will result in this method returning an error.


RegFilterCollection Property (IMediaControl Object)

Retrieves a collection of IRegFilterInfo objects representing the filters available in the registry. Returns an IAMCollection object. Read-only.

Syntax

Set objCollection = objMediaControl.RegFilterCollection

Parts

objCollection

The IAMCollection object that contains IRegFilterInfo objects.

objMediaControl

Required. An object expression that evaluates to an IMediaControl object.


Pause Method (IMediaControl Object)

Pauses all the filters in the filter graph.

Syntax

objMediaControl.Pause

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 paused state cues the graph for immediate rendering when put into running state.


RenderFile Method (IMediaControl Object)

Adds and connects filters needed to play the specified file.

Syntax

objMediaControl.RenderFile string

Parts

objMediaControl

Required. An object expression that evaluates to an IMediaControl object.

string

The 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)

Switches the entire filter graph into a running state.

Syntax

objMediaControl.Run

Parts

objMediaControl

Required. An object expression that evaluates to an IMediaControl object.

Remarks

In a running state, data is pushed down the filter graph and rendered. The graph remains in a running state until it is stopped by the Pause or Stop method. The graph remains in a running state even after notifying the application of completion (that is, the EC_COMPLETE notification is sent to the application). This allows the application to determine whether to pause or stop after completion.

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 may have successfully entered the running state. In a multistream graph, entire streams may be playing successfully. The application must determine whether to stop execution or not.


Stop Method (IMediaControl Object)

Switches all filters in the filter graph to a stopped state.

Syntax

objMediaControl.Stop

Parts

objMediaControl

Required. An 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 DWORD 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 running state on any filter, an error value is returned by the Run method. In this case, some filters within the graph may 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 graph's operation has completed.


CancelDefaultHandling Method (IMediaEvent Object)

Cancels default handling by the filter graph of the specified event and ensures that the event is passed to the application.

Syntax

objMediaEvent.CancelDefaultHandling lEvCode

Parts

objMediaEvent

Required. An object expression that evaluates to an IMediaEvent object.

lEvCode

Long. Event code for which to cancel default handling. The following values are valid.

Event notification 	Meaning

EC_COMPLETE 	The operation completed successfully.

EC_DURATION_CHANGED 	The duration exposed by a pin has changed.

EC_ERRORABORT 	The operation was terminated because of an error.

EC_PALETTE_CHANGED 	The video palette has changed.

EC_REPAINT 	The display needs painting in stopped state. This is sent from the filter to the filter graph.

EC_USERABORT 	The operation was terminated by an application-based command.

Return Values

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)

Retrieves the next notification event.

Syntax

objMediaEvent.GetEvent lEventCode, lParam1, lParam2, msTimeout

Parts

objMediaEvent

Required. An object expression that evaluates to an IMediaEvent object.

IEventCode

Long. Returns the next event notification. The following table lists the system-defined event notifications.

Event notification 	Meaning

EC_COMPLETE 	The operation completed successfully.

EC_DURATION_CHANGED 	The duration exposed by a pin has changed.

EC_ERRORABORT 	The operation was terminated because of an error.

EC_PALETTE_CHANGED 	The video palette has changed.

EC_REPAINT 	The display needs painting in stopped state. This is sent from the filter to the filter graph.

EC_USERABORT 	The operation was terminated by an application-based command.

lParam1

Required. Long. Returns the first parameter of the event.

lParam2

Required. Long. Returns the second parameter of the event.

msTimeout

Required. Long. Time, in milliseconds, to wait before assuming that there are no events. To block until an event occurs, specify a time-out value of INFINITE. 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 millisecs if there are no events.

If the time-out is zero and there is no event waiting, or if the time-out elapses before an event appears, this method raises the error E_ABORT and the event code and parameters are undefined.


GetEventHandle Method (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

Required. An object expression that evaluates to an IMediaEvent object.

hEvent

Long. Returns 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)

Reinstates the normal default handling by a filter graph for the specified event if there is one.

Syntax

objMediaEvent.RestoreDefaultHandling lEvCode

Parts

objMediaEvent

Required. An object expression that evaluates to an IMediaEvent object.

lEvCode

The event to restore. The following table lists system-defined event notifications.

Event notification 	Meaning

EC_COMPLETE 	The operation completed successfully.

EC_DURATION_CHANGED 	The duration exposed by a pin has changed.

EC_ERRORABORT 	The operation was terminated because of an error.

EC_PALETTE_CHANGED 	The video palette has changed.

EC_REPAINT 	The display needs painting in stopped state. This is sent from the filter to the filter graph.

EC_USERABORT 	The operation was terminated by an application-based command.

Remarks

Events that have default handling in place, such as EC_REPAINT, are not typically passed to the application.


WaitForCompletion Method (IMediaEvent Object)

Waits until the filter graph's operation has completed.

Syntax

objMediaEvent.WaitForCompletion msTimeout, EvCode

Parts

objMediaEvent

Required. An object expression that evaluates to an IMediaEvent object.

msTimeout

Long. Duration of the time-out, in milliseconds. To block indefinitely, pass INFINITE. To return immediately, pass zero.

EvCode

Long. Returns 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 event notification EC_COMPLETE, EC_ERRORABORT, or EC_USERABORT is received, or until the time-out period is reached, whichever comes first.

If the time-out value is reached, the method returns a completion code value of 0 and raises the error E_ABORT.

Upon return, the filter graph is still in 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 communicating with the filter graph can call methods on this interface to set or retrieve properties such as the duration of the stream, 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 REFTIME 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.


CurrentPosition Property (IMediaPosition Object)

Retrieves or sets the current position in terms of the total length of the media stream. Double.

Syntax

objMediaPosition.CurrentPosition [=dblValue]

Parts

objMediaPosition

Required. An object expression that evaluates to an IMediaPosition object.

dblValue

Double. Specifies the new value for the 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, execute 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)

Retrieves the total duration of the media stream. Read-only. Double.

Syntax

objMediaPosition.Duration

Parts

objMediaPosition

Required. An 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)

Retrieves or sets the time prior to the start position that devices should start rolling.

Syntax

objMediaPosition.PrerollTime [=dblValue]

Parts

objMediaPosition

Required. An object expression that evaluates to an IMediaPosition object.

dblValue

Double. Specifies the new 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)

Retrieves or sets the rate of playback relative to normal playback speed. Double.

Syntax

objMediaPosition.Rate [= dblValue]

Parts

objMediaPosition

Required. An object expression that evaluates to an IMediaPosition object.

dblValue

Double. Specifies the new value for the rate.

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 samples. A rate of 0.5 indicates half speed.

Negative rates indicate reverse play. Negative rate values are not supported by all media types.


StopTime Property (IMediaPosition Object)

Retrieves or sets the time at which the media stream stops. Double.

Syntax

objMediaPosition.StopTime [ = dblValue]

Parts

objMediaPosition

Required. An object expression that evaluates to an IMediaPosition object.

dblValue

Specifies the 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.


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)

Retrieves the subtype GUID. Read-only. String.

Syntax

objMediaTypeInfo.Subtype

Parts

objMediaTypeInfo

Required. An object expression that evaluates to an IMediaTypeInfo object.

Return Values

Returns a string that contains the subtype GUID.


Type Property (IMediaTypeInfo Object)

Retrieves the major type GUID as a string.

Syntax

objMediaTypeInfo.Type

Parts

objMediaTypeInfo

Required. An object expression that evaluates to an IMediaTypeInfo object.

Return Values

Returns a string containing the major type GUID.


IPinInfo Object

The filter graph manager exposes IPinInfo, which allows access to pin information such as the 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 IPin object 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)

Connects to the pin using other transform filters as necessary.

Syntax

objPinInfo.Connect objPin

Parts

objPinInfo

Required. An object expression that evaluates to an IPinInfo object.

objPin

Specifies the pin to connect with. Can be either an IPin or an IPinInfo object.

Remarks

The objPin parameter can be either an IPin or an IPinInfo object.


ConnectDirect Method (IPinInfo Object)

Connects directly to the given pin, not using any intermediate filters.

Syntax

objPinInfo.ConnectDirect objPin

Parts

objPinInfo

Required. An object expression that evaluates to an IPinInfo object.

objPin

The pin to connect directly to. Can be either an IPin or an IPinInfo object.


ConnectedTo Property (IPinInfo Object)

Retrieves the IPinInfo object for the pin to which the filter is connected. Read-only.

Syntax

Set objConnectedPinInfo = objPinInfo.ConnectedTo

Parts

objConnectedPinInfo

The IPinInfo object for the pin.

objPinInfo

Required. An object expression that evaluates to an IPinInfo object.


ConnectionMediaType Property (IPinInfo Object)

Retrieves the IMediaTypeInfo object for this connection.

Syntax

Set objMediaTypeInfo = objPinInfo.ConnectionMediaType

Parts

objMediaTypeInfo

Returns an IMediaTypeInfo object.

objPinInfo

An object expression that evaluates to an IPinInfo object.

Remarks

The IMediaTypeInfo object contains information about the major type and subtype that this pin supports.


ConnectWithType Method (IPinInfo Object)

Connects directly to the specified pin using the specified media type.

Syntax

objPinInfo.ConnectWithType objPin, objMediaType

Parts

objPinInfo

Required. An object expression that evaluates to an IPinInfo object.

objPin

Specifies the pin to connect to. The objPin object must support either IPin or IPinInfo.

objMediaType

Specifies the media type the pin is connecting with. The objMediaType object must support IPinInfo.

Remarks

The Connect and ConnectDirect methods also connect this pin to another.


Direction Property (IPinInfo Object)

Retrieves the pin direction. Read-only. Long.

Syntax

objPinInfo.Direction

Parts

objPinInfo

Required. An object expression that evaluates to an IPinInfo object.

Remarks

The value 0 indicates input, and the value 1 indicates output.


Disconnect Method (IPinInfo Object)

Disconnects this pin and the corresponding connected pin from each other.

Syntax

objPinInfo.Disconnect

Parts

objPinInfo

Required. An 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)

Retrieves the IFilterInfo object for the filter to which this pin belongs.

Syntax

Set objFilterInfo = objPinInfo.FilterInfo

Parts

objFilterInfo

Required. An object expression that evaluates to an IFilterInfo object.

objPinInfo

Required. An object expression that evaluates to an IPinInfo object.

Remarks

For more information, see the reference entry for IFilterInfo.


MediaTypes Property (IPinInfo Object)

Retrieves IAMCollection objects of preferred media types.

Syntax

Set objCollection = objPinInfo.MediaTypes

Parts

objCollection

The IAMCollection object that is returned.

objPinInfo

Required. An object expression that evaluates to an IPinInfo object.


Name Property (IPinInfo Object)

Retrieves the name of this pin. Read-only. String.

Syntax

objPinInfo.Name

Parts

objPinInfo

Required. An object expression that evaluates to an IPinInfo object.


Pin Property (IPinInfo Object)

Returns the IPin object. Read-only.

Syntax

Set objPin = objPinInfo.Pin

Parts

objPin

Returns the IPin object.

objPinInfo

Required. An 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)

Retrieves the pin identifier. Read-only. String.

Syntax

objPinInfo.PinID

Parts

objPinInfo

Required. An 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)

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

Required. An 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. Read-only.

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)

Creates an instance of this filter and adds it to the graph.

Syntax

objRegFilterInfo.Filter objFilterInfo

Parts

objRegFilterInfo

Required. An object expression that evaluates to an IRegFilterInfo object.

objFilterInfo

Returns the IFilterInfo object for the filter that was just added to the graph.


Name Property (IRegFilterInfo Object)

Retrieves the name of the filter. Read-only. String.

Syntax

objRegFilterInfo.Name

Parts

objRegFilterInfo

Required. An object expression that evaluates to an IRegFilterInfo object.

Return Values

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 Visual Basic® and 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. If it is not connected, property access and method calls return the error VFW_E_NOT_CONNECTED.

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 iconizing.

GetWindowPosition 	Retrieves the video window position.

NotifyOwnerMessage 	Passes palette and color change messages on the filter graph.

SetWindowForeground 	Tells the renderer filter to become the foreground window.

SetWindowPosition 	Sets the video window position on the display.


AutoShow Property (IVideoWindow Object)

Retrieves or sets information about whether the window will be automatically shown. Boolean.

Syntax

objVideoWindow.AutoShow [= boolean]

Parts

objVideoWindow

Required. An 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. This can be done by setting the visible property.


BackgroundPalette Property (IVideoWindow Object)

Determines whether any palette required will be realized in the background.

Syntax

objVideoWindow.BackgroundPalette [= boolean]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

boolean

Flag that indicates whether the palette will be realized.

Remarks

If this is OATRUE (-1), 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 0, or False.


BorderColor Property (IVideoWindow Object)

Retrieves the border color for the video window.

Syntax

objVideoWindow.BorderColor [= Color]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

Color

Specifies the new border color.

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 non-system 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)

Retrieves the textual title string for the video window. String.

Syntax

objVideoWindow.Caption [= string]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

string

Specifies the new value for the window title caption.


FullScreenMode Property (IVideoWindow Object)

Retrieves or sets a flag indicating whether to use full-screen mode for the video window. Boolean.

Syntax

objVideoWindow.FullScreenMode [= boolean]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

boolean

Specifies the new flag value. True means use full-screen mode; False means do not use full-screen mode.

Remarks

True indicates that the video window uses full-screen mode; False indicates that it does not.


GetMaxIdealImageSize Method (IVideoWindow Object)

Gets the ideal maximum image size for the video image playback (client) area.

Syntax

objVideoWindow.GetMaxIdealImageSize Width, Height

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

Width

Long. Returns the image width.

Height

Long. Returns the image height.


GetMinIdealImageSize Method (IVideoWindow Object)

Gets the ideal minimum image size for the video image playback (client) area.

Syntax

objVideoWindow.GetMinIdealImageSize Width, Height

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

Width

Long. Returns the image width.

Height

Long. Returns the image height.


GetRestorePosition Method (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

Required. An object expression that evaluates to an IVideoWindow object.

Left

Long. Returns the x-axis origin of the video window.

Top

Long. Returns the y-axis origin of the video window.

Width

Long. Returns the width of the video window.

Height

Long. Returns the height of the video window.


GetWindowPosition Method (IVideoWindow Object)

Retrieves the current window rectangle (not the client rectangle) in device coordinates.

Syntax

objVideoWindow.GetWindowPosition Left, Top, Width, Height

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

Left

Long. Returns the x-axis origin of the window.

Top

Long. Returns the y-axis origin of the window.

Width

Long. Returns the width of the window.

Height

Long. 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)

Retrieves or sets the height of the video window. Long.

Syntax

objVideoWindow.Height [= lValue]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

lValue

Long. Specifies the 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).


Left Property (IVideoWindow Object)

Retrieves or sets the x coordinate for the video window. Long.

Syntax

objVideoWindow.Left [= lValue]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

lValue

Long. Specifies the new value for the x-axis coordinate.

Remarks

Calling this method does not affect the width of the video window.


MessageDrain Property (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

Required. An object expression that evaluates to an IVideoWindow object.

handle

Specifies the new value for the window handle.


NotifyOwnerMessage Method (IVideoWindow Object)

Forwards messages that have been received by a parent window to a child window that is owned by a filter.

Syntax

objVideoWindow.NotifyOwnerMessage hwnd, uMsg, wParam, lParam

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

hwnd

Long. The window handle.

uMsg

Long. The message being sent.

wParam

Long. The message's wParam.

lParam

Long. The message's lParam.

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_SYSCOLOURCHANGE

WM_PALETTECHANGED

WM_QUERYNEWPALETTE

WM_PALETTEISCHANGING

WM_DEVMODECHANGE

WM_DISPLAYCHANGE

WM_MOVE


Owner Property (IVideoWindow Object)

Retrieves or sets the owning parent for the video window. Long, representing a window handle.

Syntax

objVideoWindow.Owner [= handle]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

handle

Long. Specifies the new value for the window handle.

Remarks

This property 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 but does not set the WS_CHILD style for the video window. If the window should become a true child window, the application should change the style using WindowStyle.


SetWindowForeground Method (IVideoWindow Object)

Tells the renderer to grab the window foreground.

Syntax

objVideoWindow.SetWindowForeground Focus

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

Focus

Long. Specifies the value for the window focus.

Remarks

The caller can optionally give the window the input focus.


SetWindowPosition Method (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

Required. An object expression that evaluates to an IVideoWindow object.

Left

Long. Specifies the x-axis origin of the window.

Top

Long. Specifies the y-axis origin of the window.

Width

Long. Specifies the width of the window.

Height

Long. 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)

Retrieves or sets the y-axis coordinate of the video window. Long.

Syntax

objVideoWindow.Top [= lValue]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

lValue

Long. Specifies the new value for the y-axis origin.

Remarks

Calling this method does not affect the height of the video window.


Visible Property (IVideoWindow Object)

Retrieves or sets the visibility of the video window. Boolean.

Syntax

objVideoWindow.Visible [= boolean]

Parts

objVideoWindow

Required. An 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)

Retrieves or sets the width of the video window. Long.

Syntax

objVideoWindow.Width [= lValue]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

lValue

Long. Specifies the new value of the width.

Remarks

The Width property is independent of the Height property (the x coordinate) of the video window.


WindowState Property (IVideoWindow Object)

Returns or sets the state of the video window. Long.

Syntax

objVideoWindow.WindowState [= lValue]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

lValue

Long. Specifies the new value for the WindowState property.

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 for the Microsoft Win32 ShowWindow function.

This is a fairly thin wrapper on the Win32 ShowWindow function. Use this method to change the window state. The lValue parameter accepts such ShowWindow properties as SW_MINIMIZE, SW_MAXIMIZE, and SW_HIDE.


WindowStyle Property (IVideoWindow Object)

Retrieves or sets the style parameters for the video window. Long.

Syntax

objVideoWindow.WindowStyle [= lValue]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

lValue

Long. Specifies the new value for the WindowStyle property. The values can include a subset of the flags that can be set by the GWL_STYLE value of the Microsoft Win32 GetWindowLong function.

Remarks

For a complete list of window styles, see the CreateWindow function in the Microsoft Win32 Software Development Kit (SDK).


WindowStyleEx Property (IVideoWindow Object)

Changes the style parameters for the video window.

Syntax

objVideoWindow.WindowStyleEx [= lValue]

Parts

objVideoWindow

Required. An object expression that evaluates to an IVideoWindow object.

lValue

Long. Specifies the 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.

Remarks

This property uses EX window styles. For a complete list of extended window styles, see the CreateWindowEx function in the Microsoft Win32 Software Development Kit (SDK).


ActiveMovie Event Notification Codes

Microsoft® ActiveMovie™ supports system-defined events, which are passed to the filter graph manager from filters in the filter graph. These events are passed through methods located on the IMediaEventSink::Notify method on the filter graph manager; they are retrieved by the application through the IMediaEvent::GetEvent method.

The following system-defined event notification codes are available. These codes are listed in the evcode.h file.

EC_ACTIVATE

Description: Sent by audio and video renderers when they lose or gain activation. (Used for sound-follows-focus and full-screen switching.)

lParam1: 1 if gained or 0 if lost.

lParam2: Pointer to the IFilter interface.

EC_BUFFERING_DATA

Description: Changing buffering status.

lParam1: 1 means starting to buffer data, 0 means not buffering any more.

lParam2: 0

EC_CLOCK_CHANGED

Description: The reference clock has changed.

lParam1: 0

lParam2: 0

EC_COMPLETE

Description: The video has finished rendering.

lParam1: HRESULT

lParam2: 0

EC_DISPLAY_CHANGED

Description: Sent by renderers when they detect a display change.

lParam1: Pointer to the IPin interface that should be reconnected by the graph.

lParam2: 0

EC_ERROR_STILLPLAYING

Description: A playback error has occurred, but the graph is still playing.

lParam1: HRESULT

lParam2: 0

EC_ERRORABORT

Description: An error forced the termination of a requested operation.

lParam1: HRESULT

lParam2: 0

EC_FULLSCREEN_LOST

Description: Sent by full renderers when switched away from.

lParam1: 0

lParam2: 0

EC_NEED_RESTART

Description: Sent when the current graph needs to be stopped and restarted.

lParam1: 0

lParam2: 0

EC_OLE_EVENT

Description: Sent by a filter to pass a text string to the application.

lParam1: The BSTR for the message. You must free the BSTR by calling IMediaEvent::FreeEventParams.

lParam2: 0

EC_OPENING_FILE

Description: Changing open file status.

lParam1: 1 means starting to open file, 0 means not opening any more.

lParam2: 0

EC_PALETTE_CHANGED

Description: The video palette has changed.

lParam1: 0

lParam2: 0

EC_QUALITY_CHANGE

Description: The quality of the playback has changed. This occurs only once if a quality message has been responded to.

lParam1: 0

lParam2: 0

EC_REPAINT

Description: Repaint required.

lParam1: Pointer to the IPin interface that needs the data to be sent again.

lParam2: 0

EC_SHUTTING_DOWN

Description: The shutdown of the filter graph is starting.

lParam1: 0

lParam2: 0

EC_STARVATION

Description: Sent by a filter when it detects starvation.

lParam1: 0

lParam2: 0

EC_STREAM_ERROR_STILL_PLAYING

Description: The stream is still playing, but should not be playing.

lParam1: Major code.

lParam2: Minor code.

EC_STREAM_ERROR_STOPPED

Description: The stream has stopped, but should not have stopped.

lParam1: Major code.

lParam2: Minor code.

EC_TIME

Description: The requested reference time occurred.

lParam1: Reference time, low-order DWORD.

lParam2: Reference time, high-order DWORD.

EC_USERABORT

Description: A user has forced the termination of a requested operation.

lParam1: 0

lParam2: 0

EC_VIDEO_SIZE_CHANGED

Description: The size of the native video has changed.

lParam1: Low-order WORD is the width; high-order WORD is the height.

lParam2: 0

EC_WINDOW_DESTROYED

Description: Sent by video renderer when window is destroyed; used to ensure that the focus is correctly reassigned in the Resource Manager.

lParam1: Pointer to the IFilter interface.

lParam2: 0


Introduction

This article provides the specifications for all Microsoft® ActiveMovie™ sample code and binaries that are part of the Microsoft ActiveMovie Software Development Kit (SDK).

These samples illustrate how to write ActiveMovie filters and applications that use them.

The following sections describe the purpose and functionality of each filter or application. Each section also describes the use of the corresponding base classes for the following filters or samples:

Source Filters

•	Audio Synthesizer Filter (Synth.ax)

•	Bouncing Ball Source Filter (Ball.ax)

•	AVICap-based Video Capture Source Filter (VidCap.ax)

Transform Filters

•	Contrast Filter (Contrast.ax)

•	Time-based Video Effects Filter (Effect.ax)

•	Simple Audio Processing Filter (Gargle.ax)

•	Null Inplace Filter (NullIP.ax)

•	Null Null Filter (NullNull.ax)

•	Tee Filter (InfTee.ax)

•	Simple Video Mixing Filter (VideoMix.ax)

•	Easy RGB 24 Video Effect Filter (EzRGB24.ax)

Renderer Filters

•	File Dump Filter (Dump.ax)

•	Oscilloscope Filter (Scope.ax)

•	Sample Video Renderer Filter (SampVid.ax)

•	Text Renderer Filter (TextOut.ax)

C/C++-based Sample Applications

•	C/COM-based Media Player (CPlay.exe)

•	C++/COM-based Media Player (MFCPlay.exe)

•	Indeo Player (IPlay.exe)

Visual Basic-based Sample Applications

•	Visual Basic-based Filter Graph Builder (Builder.exe)

•	Visual Basic-based Filter Graph Player (VBDemo.exe)

•	Visual Basic-based ActiveX Player (OCXVB01.exe)

•	Visual Basic-based Player (Player.exe)

Plug-in Distributor Sample

•	IAMovie Sample PID (IAMovie.dll)

Helper Functions

•	IOStream Helper Library (SampIOS.lib)


Source Filters

This section details sample source filters: two are video and one is audio. Each of these source filter samples provides at least one output pin.

Audio Synthesizer Filter (Synth.ax)

The audio synthesizer filter, Synth, demonstrates usage of the CSource and CSourceStream classes in an environment that derives its source from audio. You can use the Synth filter as a source filter to synthesize audio waveforms such as sine waveforms, square waveforms, sawtooth waveforms, and swept frequency waveforms.

The Synth source filter allows the user to set the waveform, frequency, number of channels, and other properties. The user can set these properties through the property page. To set either the upper or lower end point of the swept frequency range, hold down the SHIFT key while adjusting the frequency slider. The property page only enables the controls that affect the audio format — for example, channels, bits per sample, and sampling frequency — while the filter is in a stopped state.

Bouncing Ball Source Filter (Ball.ax)

The bouncing ball source filter, Ball, illustrates format negotiation. Ball also illustrates the use of the source filter base classes CSource and CSourceStream, and the CBasePropertyPage class. The code in fball.h and fball.cpp manages the filter interfaces. Those two files contain approximately the minimum required for a source filter. (Property pages are not required.) The ballprop.h and ballprop.cpp files provide the property page object, and ball.h and ball.cpp contain the code that bounces the ball.

The Ball filter also accepts quality-management requests from the downstream graph which illustrates a simple quality-management strategy.

This filter has a single output pin, which provides a video stream that shows a ball bouncing around in the frame.

AVICap-based Video Capture Source Filter (VidCap.ax)

The AVICap-based video capture source filter, VidCap, uses the source filter base classes, CSource and CSourceStream, in a more sophisticated way because it provides a custom thread procedure for its worker thread. The VidCap filter wraps the application programming interfaces (API) of the AVI capture window for use in ActiveMovie™ streams. It creates a hidden capture window and then uses callback functions to pass the video frames downstream.

The VidCap filter supports a custom interface to allow applications to configure the underlying AVI capture window.

The VidCap filter does not provide optimal capture performance because it must buffer frames from the AVI capture window internally. You can obtain optimum performance by writing a source filter that works with the APIs internally.


Transform Filters

This section details sample transform filters. The sample transform filters include 1 audio effect, 3 video effects, a video mixer, some MPEG codecs, an infinite tee connection, and various "null" (pass-through) filters. (A note on terminology: transform filters are sometimes called "effects.")

Contrast Filter (Contrast.ax)

The Contrast filter illustrates how to define and implement a simple custom interface within the structure provided by the ActiveMovie™ base classes. This filter demonstrates how to use the CTransformFilter class to implement a simple effects filter.

The Contrast filter also provides a good example of the flexibility of the filter graph architecture; this flexibility is demonstrated when the filter is used in conjunction with a tee filter to produce "before and after" video streams.

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.

Note  The Contrast filter should perform the transformation inplace, if it can. However, this functionality was not available in ActiveMovie when the sample was written.

Time-based Video Effects Filter (Effect.ax)

The time-based video effects filter, Effect, illustrates the use of the CBaseVideoMixer base class in implementing some video effects.

The Effect filter demonstrates a simple video effect with two input pins and one output pin. Four simple examples of video effects are provided, including top-to-bottom and left-to-right simple wipes, a band wipe, and an iris effect. This filter only operates on RGB data, so video streams must be decompressed before entering the filter.

The filter allows the user to set a start time and a duration over which the wipe should take place.

Simple Audio Processing Filter (Gargle.ax)

The audio processing filter, Gargle, illustrates how to do a simple sound effect. Echo, flanging, band-pass filtering, and other effects can be carried out in a way similar to that demonstrated by the Gargle filter.

The Gargle filter modulates the waveform passing through the filter by multiplying it by another waveform that is mathematically generated within the filter. The modulating waveform is, by default, a triangular wave. The property sheet allows the alternative of a square wave. You can set the frequency of the modulating wave through the property sheet of the filter. At low frequencies (near 1 Hz), the sound grows and diminishes. At medium frequencies (5 to 15 Hz), the sound has a tremolo quality, which is why it is referred to as gargling. At higher frequencies (100 Hz and up), the filter generates extra frequencies in the original sound. If a 500 Hz sound is played at 100 Hz, then it produces additional frequencies of 400 Hz, 600 Hz, 200 Hz, 800 Hz, and so on.

Null Inplace Filter (NullIP.ax)

The null inplace filter, NullIP, is an example of a transform-inplace filter. It illustrates how a transform filter can behave in a relatively transparent manner. NullIP is a simple filter which passes all data from its input pin to its output pin. No transformations are performed on the data.

The NullIP filter provides an example of using the CTransInPlaceInputPin class. It also lets a user select the media types through which it can pass. This filter has one input pin, one output pin, and performs its transform inplace on the push thread (that is, without copying the data). That is, it is called with a buffer, which it transforms and delivers to the next filter downstream. It is then blocked until that filter returns; it subsequently returns to its own calling member function.

Null Null Filter (NullNull.ax)

The NullNull filter illustrates a truly minimal filter. It does not support the media type selection that NullIP does.

Tee Filter (InfTee.ax)

The tee filter, InfTee, illustrates how to structure a filter with multiple output pins and passing through type enumerators from source filters. The InfTee filter demonstrates the use of the COutputQueue base class.

The InfTee filter has one input pin and two output pins. It accepts data samples through the IMemInputPin transport which it implements. All data samples sent to the filter are delivered down both output paths simultaneously, therefore teeing the input into two separate output streams. The data samples are not type-specific, so the input, for example, can be text lyrics, video images, or audio buffers.

The connection mechanism is fairly intelligent. When considering two output pins, the tee filter sends the same data down both of the pins; therefore the pins must have negotiated the same media type during connection. The InfTee filter handles this negotiation so that the input pin and both output pins will converge when using the same media type. If a suitable media type cannot be found, then the connection will be rejected.

The InfTee filter will always use the suggested allocator. The filter that provides the data suggests the allocator. There is no technical reason why the filter cannot negotiate to use one of either of the downstream filters but it made for unnecessary complications in the sample implementation. The data arriving at the input pin is not copied before it is sent to the output pins. The InfTee 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 this was not carried out, then the thread that delivers the sample to the tee input pin could pass the data to a downstream filter at which point it could block, keeping data from the other downstream filter for long periods of time.

Simple Video Mixing Filter (VideoMix.ax)

The video mixing filter, VideoMix, illustrates the use of the CBaseVideoMixer base class to implement a video effect. This filter also uses the CBasePropertyPage class for property pages.

The video mixer mixes two input videos by overlaying one on the other. The technique is similar to the blue/green screen techniques used in filmmaking. The difference is that the video mixer tests for black, rather than blue or green, as the transparent color.

Easy RGB 24 Video Effect Filter (EzRGB24.ax)

The RGB 24 video effect filter, EzRGB24, illustrates a filter supporting red, green, blue, darken, XOR, blur, gray, and emboss image-processing effects. It provides fast and single stream effects. The EzRGB24 filter also shows how to build plug-in image processing effects using ActiveMovie. You can use this filter as a component of an ActiveMovie video editor. Some applications may provide more sophisticated effects than these. Effects with fast execution were selected in order to help demonstrate the power of ActiveMovie in enabling real-time effects—the idea was to show something that could not have been built using Microsoft Video for Windows. Developers should see this sample and be motivated to create their own image effects.

MPEG Framework Audio Codec (MPGAudio.ax)

The MPEG framework audio codec, MPGAudio, provides a prototype for an MPEG audio decoder. It uses the CTransformFilter class.

As supplied, this framework just consumes the passed-in audio frames.

MPEG Framework Video Codec (MPGVideo.ax)

The MPEG framework video codec, MPGVideo, provides a prototype for an MPEG video decoder. It uses the CTransformFilter class. The MPGVideo filter also shows the processing of quality-management messages.

As supplied, this framework just consumes the passed-in video frames.


Renderer Filters

This section describes sample renderer filters. The filters render video output, audio output, text output, and raw file output.

File Dump Filter (Dump.ax)

The file dump filter, Dump, illustrates the use of the base filter class CBaseFilter and the rendered input pin class CRendererInputPin. 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 filter is also a 'Renderer' of its input stream. It delivers the EC_COMPLETE message to the filter graph when it receives a call to 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 using the Filter Graph Editor and hook the Dump filter on to the output of a transform or any other pin. You can also hook up 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 filename when it is instantiated and closes the file when it is freed.

Oscilloscope Filter (Scope.ax)

Other than the video renderer sample, the Oscilloscope filter, Scope, is the only sample filter that has a constantly active window. (Incidentally, the scope window is implemented as a dialog box, not as an actual window, which makes it unique.) Developers creating control panels to alter filter parameters in real time may 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 filter demonstrates how to apply ActiveMovie™ outside the rather narrow domain of multimedia playback. ActiveMovie may have wide application in the diverse areas of:

•	Process control

•	Factory automation

•	Image processing and analysis

•	Virtual lab instrumentation

All of these areas have semi real-time requirements, but additionally emphasize user interaction and the display of gauges, monitors, signal generators, alarms, and other forms of graphical display of analyzed results.

The Scope filter also lets you monitor audio output to determine if you are clipping so you can adjust the gain.

Sample Video Renderer Filter (SampVid.ax)

The sample video renderer filter, SampVid, displays video in a window. The SampVid filter demonstrates the implementation of a special memory allocator which uses buffers based on the Microsoft Win32 DIBSECTION structure. This sample shows use of the CBaseVideoRenderer class and the use of the property page interface IQualProp that addresses quality management

Text Renderer Filter (TextOut.ax)

The text renderer filter, TextOut, serves as an example of a renderer filter that is for a user-defined type. It can render text data found in an avi file or other source. The TextOut filter demonstrates the use of the CBaseRenderer class.


C/C++-based Sample Applications

This section details sample applications that are written in C and C++. The sample applications each implement media players. The differences between them are mainly the different programming languages or APIs/frameworks used.

Some of these samples rely on the Microsoft® Foundation Classes (MFC).

C/COM-based Media Player (CPlay.exe)

This C/COM-based media player sample, CPlay, is a simple application that renders multimedia files using ActiveMovie from within the C language. (This sample, CPlay, is in contrast to MFCPlay, which is written in C++ and uses MFC.) The CPlay sample shows how to interface to the ActiveMovie™ components without using the base classes provided with ActiveMovie. The sample creates a filter graph (by calling CoCreateInstance to get a pointer to the IGraphBuilder interface), and requests the filter graph to render a file. The filter graph is then controlled using the IMediaControl interface. This sample also uses the IMediaEvent and IMediaPosition interfaces.

The CPlay application only implements 5 menu options: file-open, play, pause, stop, help-about, and file-exit.

C++/COM-based Media Player (MFCPlay.exe)

The C++/COM-based media player sample, MFCPlay, is a simple application that renders multimedia files using ActiveMovie from within C++ and the Microsoft Foundation Classes (MFC). It demonstrates how to interface to the ActiveMovie components by using the interfaces provided with ActiveMovie and the Microsoft Foundation Classes (MFC). The sample creates a filter graph (by calling CoCreateInstance to get a pointer to the IGraphBuilder interface), and requests the filter graph to render a file. The filter graph is then controlled using the IMediaControl interface. This sample also uses the IMediaEvent and IMediaPosition interfaces.

Like CPlay, the MFCPlay application only implements 5 menu options: file-open, play, pause, stop, help-about, and file-exit.

Indeo Player (IPlay.exe)

The Indeo player sample, IPlay, renders multimedia files using ActiveMovie and demonstrates the Indeo Video Interactive application programming interfaces (API). The IPlay sample demonstrates how to access the advanced features of the Indeo Video Interactive (IVI) codec. It is a simple application written in C++ using the Microsoft Foundation Classes (MFC). If the file is an IVI format file, it enables controls for the IVI advanced features. The advanced features include local decoding, a decoding time limit, and the ability to adjust brightness, saturation, and contrast.

The ax_spec.h file defines the interfaces of the IVI codec. The CIPlayDoc::OnOpenDocument function demonstrates how to determine if a file is an IVI format file. The CIPlayDoc::Getxxx and CIPlayDoc::Setxxx functions demonstrates how to get and set the IVI playback parameters for the advanced features.

This sample makes use of the following interfaces:

•	IBasicVideo

•	IFilterGraph

•	IGraphBuilder

•	IIndeoDecode

•	IMediaControl

•	IMediaEvent

•	IMediaPosition

•	IVideoWindow


Visual Basic-based Samples

This section describes the Microsoft® Visual Basic® samples in the Microsoft ActiveMovie™ Software Development Kit (SDK). All samples that are based inVisual Basic are located in the samples\vb directory. Samples that are referenced in articles in the ActiveMovie SDK documentation can be found in the samples\vb\doc directory.

Visual Basic-based Filter Graph Builder (Builder.exe)

The filter graph builder sample, Builder, demonstrates how a Visual Basic-based application uses the collection interfaces that are exposed by the filter graph manager to build and connect a custom filter graph. The collection interfaces are composed of the following interfaces:

•	IAMCollection

•	IRegFilterInfo

•	IFilterInfo

•	IPinInfo

•	IMediaTypeInfo

These interfaces appear as objects in the ActiveMovie control type library in the Visual Basic development environment and allow the registry to be searched, filters to be added, and pins to be connected, among other things. This sample is described in detail in the article Constructing Filter Graphs Using Visual Basic.

The Builder sample presents a form that allows the user to see a list of filters in the registry and add filters to the filter graph. It also lets the user examine the names and properties of pins on the filter, the media types on the pins, and to connect the pins. The sample has an additional sample routine, accessed by a menu, that automatically builds a filter graph. The filter graph is built using the collection interface objects to better demonstrate the more typical use of these objects in a Visual Basic-based application. The sample also lets you run the constructed filter graph.

There are two versions of the Builder application. The version in the samples\vb\doc\builder directory is the one referenced by the documentation and is a superset of the sample in the samples\vb\builder directory.

Visual Basic-based Filter Graph Player (VBDemo.exe)

The filter graph player, VBDemo, demonstrates the objects in the ActiveMovie Object Library interface that control the playback of video and that adjust properties of various components. This sample is described in detail in the article Controlling Filter Graphs Using Visual Basic.

The VBDemo sample has a File menu that allows the opening of a video file. The sample also has three buttons to play, pause, and stop the video. It positions the video window as a child window of the main form and displays the length and elapsed time of the movie. It also lets the user set the start position and the rate. Two sliders are implemented to adjust the volume and balance of the audio renderer.

The VBDemo sample is in the samples\vb\doc\builder directory.

Visual Basic-based ActiveX Player (OCXVB01.exe)

This ActiveX sample, OCXVB01, demonstrates an application that uses the ActiveMovie ActiveX™ video control. It has a form that contains menus and controls to demonstrate the access of various properties of the video control. This sample is described in detail in the article Using the ActiveMovie Control in Visual Basic.

The sample has a menu command that allows you to create the control by opening a video file, and Run, Pause, Stop commands to programmatically control the ActiveMovie control. All of the ActiveMovie Control Panel features, such as selection controls, position controls, and the tracker slider, can be made visible selectively, and enabled or disabled from menu commands in the sample application. Other properties, such as the rate and current position, can also be changed from the application, and the image in the video control can be set to various sizes such as half, default, double, and fullscreen.

The OCXVBO1 sample is in the samples\vb\doc\ocx directory.

Visual Basic-based Player (Player.exe)

The sample player, Player, is a short Visual Basic-based program that demonstrates the absolute minimum requirements for playing back an ActiveMovie media file without using the ActiveX control. It uses the same ActiveMovie object library as the VBDemo sample, but provides only three buttons (Open, Play, and Stop) and a slider for indicating position.

The Player sample is in the samples\vb\player directory.


Plug-in Distributor Sample

IAMovie Sample PID (IAMovie.dll)

The IAMovie sample shows the implementation of the IAMovie interface for a plug-in distributor (PID). (Yes, the sample and the interface both have exactly the same name.) Most of the interface is delegated to methods on other interfaces.


Helper Functions

IOStream Helper Library (SampIOS.lib)

The IOStream helper library, SampIOS, provides text output of the IFilter interface and other ActiveMovie™ objects. This sample code is provided as a header file (SampIOS.h) and a library (SampIOS.lib). These functions may be used in your ActiveMovie filters and applications. They are designed to help retrieve information in text format about the objects in the filter graph. The text output is intended to aid in debugging.

SampIOS.h declares debug output functions that you can call from C. For example, DumpFilterInfo outputs information on the given filter interface. These DumpXxx functions are included in the following list. See the header file (SampIOS.h) for the syntax of each call. The DumpXxx functions require the cout output stream to be valid in the environment in which you are working, as they implicitly output to cout.

•	DumpFilterInfo

•	DumpPinInfo

•	DumpAllPins

•	DumpAllFilters

•	DumpFilterGraph

Extensions to the C++ IOStream library are included, so you can write code like the following:

   cout << piFilterGraph << endl;

The C++ callable functions declared by SampIOS.h include the following ostream output abilities. See the header file (SampIOS.h) for the syntax of each call.

•	Output a wide string.

•	Build and output a textual version of a GUID.

•	Output filter information.

•	Output filter information for all filters left in an enumerator.

•	Output filter and connection details.

•	Output pin details (including connection information).

•	Output pin details (including connection information) for all pins left in the enumerator.

•	Output the pin info for all pins on supplied filter.


Build Information

Required and Optional Tools

You will need various tools to build the sample filters and applications. The tools (required and optional) include the following:

1	Microsoft® ActiveMovie™ Software Development Kit (SDK)

2	ANSI-compatible C/C++ compiler, such as Microsoft Visual C++® version 4.0 or later

3	Microsoft Win32® headers and libraries

4	Microsoft nmake (supplied with Visual C++), if you want to use the supplied makefiles

5	Microsoft Foundation Classes (MFC), if you want to build the two sample applications that use MFC

Building the Samples

All samples in the SDK have been provided with a makefile that is compatible with nmake and, in some cases, a Visual C++ project makefile (.mak).

To build the samples using the standard makefiles, you must first set up your build tools (for example, Microsoft Visual C++), the Win32 headers and libraries, and the ActiveMovie SDK. The ActiveMovie SDK makefiles expect to locate the standard Windows® and Win32 include files and libraries on the INCLUDE and LIB paths. The makefiles handle all ActiveMovie specific files on a project-by-project basis.

The makefiles provided for each individual sample use ActiveX.mak, which is provided with the ActiveMovie SDK.

If you are using ActiveX.mak to build for any machine, other than the default x86, you must set the CPU environment variable to indicate which kind of machine. The allowable values for the CPU are i386, MIPS, ALPHA, and PPC.

Performance Note  If you copy any sample makefile to create any new dynamic-link library (DLL) (including filters and PIDs) ensure you change the base address to avoid collisions with other DLLs. A collision of DLL load address results in one of the DLLs having to be relocated during load time, thereby increasing the duration of load time. In the sample makefiles, the base address is set in DLL_BASE, which is used in ActiveX.mak. Do not let ActiveX.mak use the default value for DLL_BASE, as this almost certain to cause collisions.

A makefile is provided (in the samples directory), which builds all the samples.

Setting Up the Registry

With the source for each sample, registry files are provided for each sample to register each filter. The samples also use the self-registration capabilities provided by the IAMovieSetup interface.

A regall.bat file is provided that will register all the samples.


ActiveMovie Filter Reference

The following filters are provided with the ActiveMovie™ SDK:

•	ACM Wrapper

•	ActiveMovie Streaming Filter

•	Audio Renderer

•	AVI Decompressor

•	AVI Splitter

•	AVI/WAV File Source

•	Colour Space Transform

•	File Source (async)

•	Full Screen Renderer

•	IV41 Compression

•	IV41 Decompression

•	MOV File Parser (async)

•	MPEG Audio Codec

•	MPEG Video Codec

•	MPEG-1 Stream Splitter

•	Video Renderer

•	WAVE Parser


ACM Wrapper

This transform filter acts as a wrapper for the Audio Compression Manager (ACM), integrating ACM with the ActiveMovie architecture.

Pin Name	Direction
XForm In	Input. Major type: Audio.
XForm Out	Output. Major type: Audio.
Property Page

XForm In tab

•	Lists the major type, subtype, and format of the input pin.

XForm Out tab

•	Lists the major type, subtype, and format of the output pin.


ActiveMovie Streaming Filter

This filter acts as the source input filter for ActiveMovie streaming media source files.

Pin Name	Direction
Output	Output. Major type: Stream.
Property Page

File tab

•	Current file. Lists the ActiveMovie streaming media source file.


Audio Renderer

This filter represents a generic audio render filter that can be connected to the output of the AVI/WAV source filter (if the source file contains WAV audio), the WAVE parser filter, or any audio transform filter.

Pin Name	Direction
Audio Input pin (rendered)	Input. Major type: Audio.
Property Page

Audio Input Pin (rendered) tab

•	Lists the major type, subtype, and format of the input pin.


AVI Decompressor

This transform filter decompresses AVI input and generates suitable output for the video renderer or an intervening video transform filter.

Pin Name	Direction
XForm In	Input. Major type: Video.
XForm Out	Output. Major type: Video.
Property Page

XForm In tab

•	Lists the major type, subtype, and format of the input pin.

XForm Out tab

•	Lists the major type, subtype, and format of the output pin.


AVI Splitter

This filter parses AVI-compressed video source input and splits it into separate video and audio streams. It can be connected to either the asynchronous file source filter or the URL moniker filter supplied with ActiveMovie 1.0, or a third party filter that delivers a compressed AVI stream and can interface with an asynchronous parser.

Pin Name	Direction
input pin	Input. Major type: Stream.
Stream 00	Output. Major type: Video.
Stream 01	Output: Major type: Audio.
Property Page

Stream00 tab

•	Lists the major type, subtype, and format for the video output.

Stream01 tab

•	Lists the major type, subtype, and format for the audio output.

Input Pin tab

•	Lists the major type, subtype, and format for the AVI source.


AVI/WAV File Source

This source filter reads AVI and WAV source files and generates the appropriate output pins for the file type.

For WAV files, one output pin is created, which produces an audio stream that can be connected to the audio renderer or an intervening audio transform filter.

For AVI files, the filter creates a video output pin, which produces a compressed AVI stream suitable for the AVI codec filter, and an audio output pin, which produces an audio stream suitable for the audio renderer filter or an intervening audio transform filter.

Pin Name	Direction
Output	Output. Major type: Stream.
Property Page

File tab

•	Lists the name of the AVI or WAV source file.

Output tab

•	Lists the major type, subtype, and format that appears on the output pin or pins.


Colour Space Transform

This transform filter converts from one RGB color type to another, such as between 24-bit and 8-bit RGB color. This filter can be used to convert to the color space used by the video render filter, such as between the AVI decompressor filter and the full screen renderer filter.

Pin Name	Direction
Input	Input. Major type: Video.
XForm Out	Output. Major type: Video.
Property Page

Input tab

•	Lists the major type, subtype, and format for the video input.

XForm Out tab

•	Lists the major type, subtype, and format for the video output.


File Source (async)

This generic asynchronous source filter works with any ActiveMovie source file that contains media with a major media type of Stream (MEDIATYPE_Stream). This includes AVI, MOV, MPEG, and WAV files. It requires the downstream filter to be a parser filter such as the MPEG-1 stream splitter, the AVI splitter, or the QuickTime MOV parser.

Pin Name	Direction
Output	Output. Major type: Stream.
Property Page

File tab

•	Lists the name of the ActiveMovie source file.

Output tab

•	Lists the major type, subtype, and format that appears on the output pin.


Full Screen Renderer

The full-screen renderer is a "modex" renderer that occupies the entire screen while displaying video.

Full-screen rendering is enabled from the filter graph manager, which automatically switches between the filter graph's video renderer and the full-screen renderer when required. It is not necessary to include the full-screen video renderer in the filter graph beforehand.

Pin Name	Direction
Input	Input. Major type: Video.
Property Page

Quality tab

•	Frames played. Read-only.

•	Frames dropped in renderer. Read-only.

•	Average frame rate achieved. Read-only.

•	Jitter (standard deviation frame rate, in milliseconds). Read-only.

•	Average sync offset (milliseconds). Read-only.

•	Standard deviation sync offset (milliseconds). Read-only.

Input tab

•	Preferred media types. Read-only.


IV41 Compression

This transform filter compresses video source to Indeo 4 format. This is typically used in a video capture filter graph. Note that ActiveMovie 1.0 does not support a complete video capture solution with the filters it provides.

Pin Name	Direction
XForm In	Input. Major type: Video.
XForm Out	Output. Major type: Video.
Property Page

Compression Properties tab

•	Key Frame Interval. Read-write.

•	Data Rate. Read-write.

•	Frame Rate. Read-write.

•	Quality. Read-write.

•	CD-ROM padding. Read-write. (Can set on or off.)

Sequence Properties tab

•	Scalability. Read-write. (Can set on or off.)

•	Bi-directional prediction. Read-write. (Can set on or off.)

•	Transparency. Can select none, first frame analysis, or alpha channel.

•	Target platform. Can select good, better, or best.

•	Access key enable. Read-write. (Can set on or off.)

•	Min viewport size height and width. Read-write.

XForm In tab

•	Preferred media types. Read-only.

XForm Out tab

•	Preferred media types. Read-only.


IV41 Decompression

This transform filter decompresses Indeo 4-compressed video source.

Pin Name	Direction
XForm In	Input. Major type: Video.
XForm Out	Output. Major type: Video.
Property Page

Sequence Properties tab

•	Transparency fill. Read-write. (Can set on or off.)

•	Scalability. Read-write. (Can set on or off.)

•	Alt line. Read-write. (Can set on or off.)

•	Access key enable. Read-write. (Can set on or off.)

Frame Properties tab

•	Decode rectangle x, y, width, height. Read-write.

•	View rectangle x, y, width, height. Read-write.

•	Brightness. Read-write.

•	Saturation. Read-write.

•	Contrast. Read-write.

•	Decode time. Read-write.

XForm In tab

•	Preferred media types. Read-only.

XForm Out tab

•	Preferred media types. Read-only.


MOV File Parser (async)

This filter parses QuickTime MOV files and splits the data into audio and video streams. The input pin connects to a source filter such as the asynchronous file source filter or the URL moniker filter. The filter creates one output pin for the video stream and one output pin for the audio stream.

Pin Name	Direction
input pin	Input. Major type: Stream.
Video 0	Output. Major type: Video.
Audio 1	Output. Major type: Audio.
Property Page

Input pin tab

•	Lists the major type, subtype, and format that appears on the input pin.

Video 0 tab

•	Lists the major type, subtype, and format that appears on the pin.

Audio 1 tab

•	Lists the major type, subtype, and format that appears on the pin.


MPEG Audio Codec

This filter decompresses MPEG-1 audio input. It is usually connected to the audio output of the MPEG splitter filter. It produces an audio stream suitable for input to the audio renderer or an intervening audio transform filter.

Pin Name	Direction
XForm In	Input. Major type: Audio. Subtype: MPEG-1 Payload.
XForm Out	Output. Major type: Audio.
Property Page

MPEG Audio Decoder tab

•	Sound quality. Can select either CD Audio, FM Radio, AM Radio, Integer Decode.

•	Sound channels. Can select Stereo or Mono.

XForm In tab

•	Lists the major type, subtype, and format.

XForm Out tab

•	Lists the major type, subtype, and format.


MPEG Video Codec

This transform filter decompresses MPEG-1 video input. Usually, its input comes from the MPEG splitter filter and its output goes to the video renderer filter or an intervening video transform filter.

Pin Name	Direction
Input	Input. Major type: Video. Subtype: MPEG-1 Payload.
Output	Output. Major type: Video.
Property Page

MPEG Video Decoder tab

•	Picture. Can select either monochrome or color.

•	Displays the picture size, bit rate, and frame rate. Read-only.

Input tab

•	Lists the major type, subtype, and format.

Output tab

•	Lists the major type, subtype, and format.


MPEG-1 Stream Splitter

This transform filter parses MPEG-1 data and splits MPEG input into separate audio and video streams. Its input requires either the asynchronous file source filter or the URL Moniker filter, or a compatible third party asynchronous source filter. Its output is compressed video and audio so, typically, the video output will be connected to the MPEG video codec filter and the audio will be connected to the MPEG audio codec filter.

Pin Name	Direction
Input	Input. Major type: Stream. Subtype: MPEG-1 Video.
Video	Output. Major type: Video. Subtype: MPEG-1 payload.
Audio	Output. Major type: Audio. Subtype: MPEG-1 payload.
Property Page

Input tab

•	Lists the major type, subtype, and format.

Video tab

•	Lists the major type, subtype, and format.

Audio tab

•	Lists the major type, subtype, and format.


Video Renderer

This renderer filter acts as a generic video renderer that can be connected to any video transform filter. Its input requires decompressed video. This filter has its own plug-in distributor in the filter graph manager so that applications can set and retrieve properties on the filter by calling the corresponding interface methods on the filter graph manager (most other filters are not visible to applications in this manner).

The video renderer filter uses DirectX™ services if the video card supports them. Full-screen rendering is enabled from the filter graph manager, which automatically switches between this renderer and the FullScreen Video Renderer when required (it is not necessary to include the FullScreen Video Renderer in the filter graph beforehand).

Pin Name	Direction
Input	Input. Major type: Video.
Property Page

Video Renderer Properties tab

•	Frames played. Read-write.

•	Frames dropped in renderer. Read-write.

•	Average frame rate achieved. Read-write.

•	Jitter. Read-write.

•	Average sync offset. Read-write.

•	Standard deviation sync offset. Read-write.

Direct Draw Input tab

•	YUV Flipping. (Can turn on or off.)

•	YUV Overlays. (Can turn on or off.)

•	YUV Offscreen. (Can turn on or off.)

•	RGB Flipping. (Can turn on or off.)

•	RGB Overlays. (Can turn on or off.)

•	RGB Offscreen. (Can turn on or off.)

•	DDraw Primary. (Can turn on or off.)

•	DCI Primary. (Can turn on or off.)

•	Hardware Capabilities. Displays settings.

•	Emulation Capabilities. Displays settings.

•	Surface Capabilities. Displays settings.

Input tab

•	Lists the major type, subtype, and format.


WAVE Parser

This transform filter can parse audio WAV input. Its input pin must be connected to either the asynchronous file source filter or the URL moniker filter (for Internet access). Its output is uncompressed audio, which can be connected directly to an audio renderer filter or to an intervening audio transform filter.

Pin Name	Direction
input pin	Input. Major type: Audio.
Output	Output. Major type: Stream.
Property Page

Input pin tab

•	Lists the major type, subtype, and format.

Output tab

•	Lists the major type, subtype, and format.


MPEG-1 Media Types

The following information summarizes the media types used by ActiveMovie™ 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: A set of Video CD sectors containing MPEG-1 video or audio; sector-aligned

MPEG-1 Audio Packet

Major type: MEDIATYPE_Audio

Minor type: MEDIASUBTYPE_ MPEG1Packet or MEDIASUBTYPE_MPEG1Payload

Format: MPEG1WAVEFORMAT

Sample contents: Single MPEG-1 packet including packet header

MPEG-1 Video Packet

Major type: MEDIATYPE_Video

Minor type: MEDIASUBTYPE_ MPEG1Packet or MEDIASUBTYPE_MPEG1Payload

Format: VIDEOINFO + Video sequence header1

Sample contents: Single MPEG-1 packet including packet header

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
System layer splitter	Output	MPEG-1 Video packet
Software Audio CODEC	Input	MPEG-1 Audio packet
Software Video CODEC	Input	MPEG-1 Video packet
Software Audio CODEC	Input	MPEG-1 Native audio stream
Software Video CODEC	Input	MPEG-1 Native video stream
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).


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 one 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 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.

Note that a sample labeled as Preroll need not have a valid time stamp unless the Sync property is set.

It is assumed that packet and payload data without time stamps can be successfully prerolled by the handling filters.


Sample Properties

MPEG samples have the following properties or notifications:

Preroll 	A sample labeled as Preroll must be rendered silently. The property is propagated to samples generated from this sample. (Note that if a sample is generated from several samples, the Preroll property of the last sample used is the one used.)

Samples labeled as Preroll need not have valid time stamps, unless the Sync property is set.

Note that preroll is currently ignored.

Sync 	The Sync property is set if the sample time stamp is to be used for synchronization. Samples without the Sync property may not have a time stamp as accurate as what can be determined from the sample data. Thus, MPEG packet or payload data samples will have the Sync property 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 Discontiniuty property.


File Formats

The format of a saved ActiveMovie™ graph file is as follows:

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 (using StgOpenStorage).

2	Query the filter graph manager for IPersistStream.

3	Open the L"ActiveMovieGraph" stream (using IStorage::OpenStream).

4	Pass the stream to the filter graph (using IPersistStream::Load).

The syntax of the graph within the stream is shown below.

<graph> ::= <version><filters><connections>END

<version> ::= 0002\r\n

<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. Note that 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, nulls, and so on.

The following approximates what it 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.


Registering a Custom File Type

This topic describes how to register a new file type so that it can be recognized by file-reader source filters. 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. ActiveMovie™ 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 an ActiveMovie 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 four 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 may or may not have a RIFF header.


MCI Quick Reference

The Active Movie MCI driver supports MPEG-video, AVI, and WAV files. The following table summarizes the MCI commands supported by the ActiveMovie version 1.0 MCI driver for each of these file types:

MCI command	MPEG-video	AVI	WAV
break	Not required	Full	Full
capability	Full	Full	Does not support the can stretch, has video, and uses palettes flags
capture	Not required	Not applicable	Not applicable
close	Full	Full	Full
configure	Not required	Not applicable	Not applicable
copy	Not required	Not applicable	Not applicable
cue	Does not support the noshow flag	Does not support the noshow flag	Does not support the noshow flag
freeze	Not required	Not applicable	Not applicable
info	Full	Full	Full
open	Does not support the VideoCD flag	Full	Does not support the style types
pause	Full	Full	Full
play	Full	Full	Full
put	The source flag is not required	The source flag is not required	The source flag is not required
realize	Not required	Not applicable	Not applicable
resume	Full	Full	Full
seek	Full	Full	Full
set	The speed and audio flags are not required	Full	The speed flag is not applicable
setaudio	Does not support the stream to flag	Does not support the stream to flag	Does not support the stream to flag
setvideo	Does not support the stream to flag; the key color to and key index to flags are not required	Does not support the stream to flag; the key color to and key index to flags are not required	Does not support the stream to flag; the key color to and key index to flags are not required
signal	No	No	No
status	Does not support the audio streams and video streams flags; the video key index and video key color flags are not required	Does not support the audio streams, samplespersec, and video streams flags	Does not support the audio streams, samplespersec, video streams, video, and video stream flags
step	Full	Full	Full
stop	Full	Full	Full
sysinfo	Not required	Not applicable	Not applicable
unfreeze	Not required	Not applicable	Not applicable
update	Full	Full	Full
where	Full	Full	Full
window	Full	Full	The state flag is not applicable
The mpegvideo device type controls MPEG-video files.