Add a Filter by CLSID

[The feature associated with this page, DirectShow, is a legacy feature. It has been superseded by MediaPlayer, IMFMediaEngine, and Audio/Video Capture in Media Foundation. Those features have been optimized for Windows 10 and Windows 11. Microsoft strongly recommends that new code use MediaPlayer, IMFMediaEngine and Audio/Video Capture in Media Foundation instead of DirectShow, when possible. Microsoft suggests that existing code that uses the legacy APIs be rewritten to use the new APIs if possible.]

The following function creates a filter with a specified class identifier (CLSID) and adds it to the filter graph:

// Create a filter by CLSID and add it to the graph.

HRESULT AddFilterByCLSID(
    IGraphBuilder *pGraph,      // Pointer to the Filter Graph Manager.
    REFGUID clsid,              // CLSID of the filter to create.
    IBaseFilter **ppF,          // Receives a pointer to the filter.
    LPCWSTR wszName             // A name for the filter (can be NULL).
    )
{
    *ppF = 0;

    IBaseFilter *pFilter = NULL;
    
    HRESULT hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, 
        IID_PPV_ARGS(&pFilter));
    if (FAILED(hr))
    {
        goto done;
    }

    hr = pGraph->AddFilter(pFilter, wszName);
    if (FAILED(hr))
    {
        goto done;
    }

    *ppF = pFilter;
    (*ppF)->AddRef();

done:
    SafeRelease(&pFilter);
    return hr;
}

Note

This example uses the SafeRelease function to release the IBaseFilter pointer.

 

The function calls CoCreateInstance to create the filter, and then calls IFilterGraph::AddFilter to add the filter to the graph. The following code example uses this function to add the AVI Mux filter to the graph:

IBaseFilter *pMux;
hr = AddFilterByCLSID(pGraph, CLSID_AviDest, L"AVI Mux", &pMux, NULL); 
if (SUCCEEDED(hr))
{
    /* ... */
   pMux->Release();
}

Note that some filters cannot be created with CoCreateInstance. This is often the case with filters that manage other software components. For example, the AVI Compressor filter is a wrapper for video codecs, and the WDM Video Capture filter is a wrapper for WDM capture drivers. These filters must be created using either the System Device Enumerator or the Filter Mapper. For more information, see Enumerating Devices and Filters.

General Graph-Building Techniques