Click here to Skip to main content
14,271,317 members

DirectShow.NET

Rate this:
4.94 (191 votes)
Please Sign up or sign in to vote.
4.94 (191 votes)
22 Jul 2002Public Domain
DirectShow for DVD and file playback, capture and sample grabber

Sample Image - directshownet.jpg

Disclaimer: Experimental code using DirectShow with the .NET Framework 1.0

Abstract

This experimental code shows how to use DirectShow with .NET and C#. This includes simple media playback, playing DVD discs, capturing video streams to disk and a sample picture grabber.

Note, this article doesn't save you from reading the detailed DirectShow SDK documentation! I will not explain DirectShow, only some of the used .NET Interop technologies!

DirectShow

DirectShow is a standardized Microsoft Win32 API to use any compliant movie or video device from your application. DirectShow is available with the current DirectX version 8.1(b) for Windows 98/ME/2000 and included in XP. Please install the latest version, this article doesn't support anything except 8.1 :

Again, I will not describe any DirectShow interfaces, you have to know them by installing the SDK for C++, reading the SDK documentation and understanding the SDK samples!

DirectShow is exposed as COM components and interfaces, at these two 'levels':

  • DirectShow custom interfaces - mainly for C++ programmers.
  • DirectShow VB components - designed for VB6, provides a type library.
You can use the DirectShow playback components for VB6 with .NET, as described in this CodeProject article: DirectShow MediaPlayer in C# (Daniel Strigl)

.NET Interop

While using the VB6 components with the provided type library is easy with .NET, there is no direct way to access the custom DirectShow interfaces. We have to use Interop with one of this approaches:

  • Use 'Managed Extensions for C++', as done e.g. by DirectX.NET
  • Rewrite all the interfaces from IDL to e.g. C# !
I chose the second strategy for this reasons :
  • Uses only one (managed) language (C#)
  • Most DirectShow interfaces are not very complex
  • DirectShow methods for simple playback/capturing are not time-critical
  • We can directly use the (documented) interfaces without limitations, no 'wrapper classes'
Sure, this has some drawbacks:
  • Much of initial work for rewriting the interfaces
  • You have to understand Interop to use it correctly
  • Not very .NET/OO-like
One typical rewrite of an IDL interface in C# looks like this :
// ======== IDL of ICaptureGraphBuilder2 (AXExtend.idl) ======
[
    object,
    uuid(93E5A4E0-2D50-11d2-ABFA-00A0C9C6E38D),
    pointer_default(unique)
]
interface ICaptureGraphBuilder2 : IUnknown {

    // Use this filtergraph
    HRESULT SetFiltergraph( [in] IGraphBuilder *pfg );

    // what filtergraph are you using?
    // *ppfg->Release() when you're done with it
    HRESULT GetFiltergraph( [out] IGraphBuilder **ppfg);
    ....
... using Interop attributes with C# will be translated to :
// ======== C# version of ICaptureGraphBuilder2 (DsExtend.cs) ======

   [ComVisible(true), ComImport,
    Guid("93E5A4E0-2D50-11d2-ABFA-00A0C9C6E38D"),
    InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
public interface ICaptureGraphBuilder2
{
        [PreserveSig]
   int SetFiltergraph( [In] IGraphBuilder pfg );

        [PreserveSig]
   int GetFiltergraph( [Out] out IGraphBuilder ppfg );
   ....

Once we have all this interface definitions in C#, we can start calling DirectShow just like we did in C++:

// ======== C++ code to create the COM instance of Filter Graph ========

    JIF(CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, 
                         IID_IGraphBuilder, (void **)&pGB));

    // Have the graph builder construct its the <BR>    // appropriate graph automatically
    JIF(pGB->RenderFile(wFile, NULL));

    // QueryInterface for DirectShow interfaces
    JIF(pGB->QueryInterface(IID_IMediaControl, (void **)&pMC));
    ....
... we replace CoCreateInstance with Activator.CreateInstance, and QueryInterface just is a simple cast in C#:
// ======== C# code to create the COM instance of Filter Graph ========

    Type comtype = null;
    object comobj = null;
    try {
        comtype = Type.GetTypeFromCLSID( Clsid.FilterGraph );
        if( comtype == null )
            throw new NotSupportedException( <BR>                "DirectX (8.1 or higher) not installed?" );
        comobj = Activator.CreateInstance( comtype );
        graphBuilder = (IGraphBuilder) comobj; comobj = null;
        
        int hr = graphBuilder.RenderFile( clipFile, null );
        if( hr < 0 )
            Marshal.ThrowExceptionForHR( hr );

        mediaCtrl    = (IMediaControl)  graphBuilder;
     ....

Projects Structure

The download contains all this C# source code:

\DirectShow\
     \DShowNET\              // the DirectShow interface definitions :
              \DsBugWO.cs      // workaround for a bug 
              \DsControl.cs    // ported from control.odl 
              \DsCore.cs       // ported from axcore.idl 
              \DsDevice.cs     // device enumerator, helper functions 
              \DsDVD.cs        // DVD interfaces from dvdif.idl 
              \DsExtend.cs     // ported from axextend.idl 
              \DsUtils.cs      // utility classes, SDK Common sources 
              \DsUuids.cs      // UUIDs and CLSIDs from uuids.h 
              \QEdit.cs        // grabber interfaces from qedit.idl 

     \CaptureNET\            // video stream capture sample 
     \DVDPlayerNET\          // DVD player sample 
     \PlayWndNET\            // simple media file playback 
     \SampleGrabberNET\      // picture grabber 

Playback

The first sample included in the download is PlayWndNET. It plays the known video and audio file formats of DirectShow like avi, mpg, wav, mid etc.

DirectShow playback

DVD Player

For the next sample, DVDPlayerNET you must have a third-party DVD codec installed, like WinDVD or PowerDVD. Then, the C# sample uses the DirectShow DVD interfaces to watch the movie. It also supports menu navigation.

DirectShow DVD

Grab Picture

The most complex sample provided is SampleGrabberNET. It shows a live video stream from a capture device like DV cam, web cam or TV card in a preview window. By pressing the 'Grab' toolbar-button, you can capture a still picture to a 24-Bit RGB bitmap file!

DirectShow picture grabber

The sample also supports the IAMTVTuner interface of a TV card, so you can switch the TV tuner channel.

Capturing

The last sample, CaptureNET can be used to capture a live video stream to disk. Note, the few settings can only be done once at startup, and writing to the AVI file starts immediately.

DirectShow Capturing

Limitations

  • EXPERIMENTAL! don't use it in production quality code.
  • The samples only provide partial and very basic functionality.
  • I did most tests on Windows XP and few on Windows ME.
  • Tested only on a very limited set of devices with only few media formats.
    I used a Logitech QuickCam, Sony DV camcorder, Hauppauge WinTV PCI and WinDVD.
  • Get the latest driver (WDM) from manufacturer.
  • Some devices fail if you select unsupported settings in the dialogs.
  • This code will NOT help to solve any DirectShow/WDM configuration problems.
  • Get >128MB RAM, >400MHz CPU, fast & huge harddisk.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

Share

About the Author

NETMaster
Web Developer
Switzerland Switzerland
No Biography provided

Comments and Discussions

 
Questionhow to create source filter for rgb video frame datas. Pin
billqu_developer15-Sep-08 0:03
memberbillqu_developer15-Sep-08 0:03 
GeneralCodecs Pin
VCSKicks9-Sep-08 9:17
memberVCSKicks9-Sep-08 9:17 
GeneralProblem with mms-stream on second monitor Pin
PeterWalther9-Sep-08 9:13
memberPeterWalther9-Sep-08 9:13 
GeneralDoubleClick on VideoWindow in PlayWndNET-Project Pin
tabor2514-Aug-08 20:20
membertabor2514-Aug-08 20:20 
Generalvideo playing problem Pin
Member 469378711-Aug-08 21:25
memberMember 469378711-Aug-08 21:25 
Generalto capture image through web cam in web application and save in hard drive Pin
Member 27161587-Aug-08 23:52
memberMember 27161587-Aug-08 23:52 
GeneralCapture a Image from Video File Pin
ananduk764-Aug-08 7:58
memberananduk764-Aug-08 7:58 
QuestionHow to find out Video Bit rate of SourceFile using directshow/Windows media interfaces Pin
shilpadhamal26-Jul-08 2:35
membershilpadhamal26-Jul-08 2:35 
I am working on one project which transcodes file.Transcoding is working fine. But I need to find out BitRate of Video stream of INPUT file. I am able to find out Audio/Video
Bitrate of OUTPUT file using DirectShow IMediaDet interface. The coding snippets are as follows,

bool MediaInfo(Filename)
{
IMediaDet *obj;
...
...
obj.put_Filename(Filename);
obj.get_OutputStreams(pVal);
for(index=0;index<pval;index++>
{
obj.put_CurrentStream(index);
obj.get_StreamType(guid);

//here checking whether current stream is VIDEO stream
//collecting information in VIDEOINFOHEADER structure


//here checking whether current stream is AUDIO stream
//collecting information in VIDEOINFOHEADER structure

}
}

Here I am getting all the info. of output file/destination file after build graph is render.
pBuildGraph->RenderFile(InputFileName);
pMediaControl->Run();
MediaInfo(Filename);

but when I call the same function i.e.MediaInfo(Filename) *before* building the graph, just to fetch all info of input file/source file, it gives me all info like Audio bit rate,lengthofStream,DurationOfstremIn bytes etc. but VideoBitRate is coming as 0 (ZERO). Please help me out to find out this info.
Thanks in advance for your co-operation. Smile | :)
QuestionVideo FrameSize doesn't getting effective on capturing the frame Pin
lokesh_1710-Jul-08 3:26
memberlokesh_1710-Jul-08 3:26 
QuestionHow to render Digital video file(.dv) using directshow Pin
san07617-Jun-08 19:32
membersan07617-Jun-08 19:32 
QuestionCompact framework Pin
fmfmffllflflff17-Jun-08 11:41
memberfmfmffllflflff17-Jun-08 11:41 
QuestionPlay big files Pin
jjdelgado17-Jun-08 6:25
memberjjdelgado17-Jun-08 6:25 
AnswerRe: Play big files Pin
erax dan2-Feb-09 2:25
membererax dan2-Feb-09 2:25 
Questionhow to configure output sampling rate and number of channels?? Pin
wzefzaf15-Jun-08 2:21
memberwzefzaf15-Jun-08 2:21 
AnswerRe: how to configure output sampling rate and number of channels?? Pin
AlexMartins25-Aug-08 0:02
memberAlexMartins25-Aug-08 0:02 
GeneralAleatory Error "Could Not setup grahp" Pin
lazartefederico9-Jun-08 13:12
memberlazartefederico9-Jun-08 13:12 
QuestionWhy all the applications alert a message like "No video capture devices found!" during runtime Pin
rzzfch5205-Jun-08 18:25
memberrzzfch5205-Jun-08 18:25 
Questionwhy not just use tlbimp.exe to generate .NET wrapper interfaces for DirectShow? Pin
Member 27098052-Jun-08 6:01
memberMember 27098052-Jun-08 6:01 
AnswerRe: why not just use tlbimp.exe to generate .NET wrapper interfaces for DirectShow? [modified] Pin
NETMaster2-Jun-08 7:04
memberNETMaster2-Jun-08 7:04 
GeneralThanks Pin
divyesh143225-May-08 20:35
memberdivyesh143225-May-08 20:35 
GeneralSave avi without open mediacontrol window Pin
jotache15-May-08 8:10
memberjotache15-May-08 8:10 
AnswerRe: Save avi without open mediacontrol window Pin
Jasper Gielen26-May-08 4:15
memberJasper Gielen26-May-08 4:15 
GeneralRe: Save avi without open mediacontrol window Pin
jotache26-May-08 17:10
memberjotache26-May-08 17:10 
QuestionWhat I need to install Pin
kiquenet.com6-May-08 4:48
professionalkiquenet.com6-May-08 4:48 
QuestionHow Can I start Programming for CaptureCard ? Pin
en.Mahdi26-Apr-08 21:30
memberen.Mahdi26-Apr-08 21:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 21 Jul 2002

Stats

3.5M views
32.6K downloads
450 bookmarked