Click here to Skip to main content
14,210,255 members
Click here to Skip to main content
Article
Posted 21 Jul 2002

Stats

3.5M views
32.5K downloads
450 bookmarked

DirectShow.NET

,
Rate this:
4.94 (191 votes)
Please Sign up or sign in to vote.
4.94 (191 votes)
22 Jul 2002     Public 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

 
GeneralRe: Loading a GRF file Pin
maggik1-Sep-10 1:50
membermaggik1-Sep-10 1:50 
GeneralFYI, using a different audio device / different sound card for playback Pin
rnendel12-Aug-10 15:30
memberrnendel12-Aug-10 15:30 
GeneralRe: FYI, using a different audio device / different sound card for playback Pin
MikePelton27-Jul-11 23:39
memberMikePelton27-Jul-11 23:39 
GeneralWindows 7 64bit Pin
divyesh14322-Aug-10 20:09
memberdivyesh14322-Aug-10 20:09 
GeneralCapture DVD frames. [modified] Pin
Member 472252317-Jul-10 22:07
memberMember 472252317-Jul-10 22:07 
GeneralShow the selected button in the DVD-Menu. Pin
Hugo_Gray16-Feb-10 12:05
memberHugo_Gray16-Feb-10 12:05 
Generalpreview video stream with controlled capture Pin
John Mealing2-Feb-10 17:02
memberJohn Mealing2-Feb-10 17:02 
QuestionIncluding audio in video recording Pin
Member 657713931-Jan-10 19:27
memberMember 657713931-Jan-10 19:27 
Hi,

Is there any way I could include in audio as I record video? I tried putting this code, but it cant work.

hr = capGraph.SetFiltergraph(graphBuilder);<br />
                if (hr < 0)<br />
                    Marshal.ThrowExceptionForHR(hr);<br />
<br />
                hr = graphBuilder.AddFilter(capFilter, "Ds.NET Video Capture Device");<br />
                if (hr < 0)<br />
                    Marshal.ThrowExceptionForHR(hr);<br />
<br />
                DsUtils.ShowCapPinDialog(capGraph, capFilter, this.Handle);<br />
<br />
                Guid sub = MediaSubType.Avi;<br />
                hr = capGraph.SetOutputFileName(ref sub, fileName, out mux, out sink);<br />
                if (hr < 0)<br />
                    Marshal.ThrowExceptionForHR(hr);<br />
<br />
                cat = PinCategory.Capture;<br />
                med = MediaType.Audio;<br />
                hr = capGraph.RenderStream(ref cat, ref med, capFilter, null, mux);<br />
                if (hr < 0) <br />
                    Marshal.ThrowExceptionForHR(hr);<br />
<br />
                cat = PinCategory.Capture;<br />
                med = MediaType.Video;<br />
                hr = capGraph.RenderStream(ref cat, ref med, capFilter, null, mux); // stream to file <br />
                if (hr < 0)<br />
                    Marshal.ThrowExceptionForHR(hr);<br />
<br />
                cat = PinCategory.Preview;<br />
                med = MediaType.Video;<br />
                hr = capGraph.RenderStream(ref cat, ref med, capFilter, null, null); // preview window<br />
                if (hr < 0)<br />
                    Marshal.ThrowExceptionForHR(hr);

GeneralClsid Pin
Jazko Uhricka28-Jan-10 0:58
memberJazko Uhricka28-Jan-10 0:58 
Questionimplementing snapshot button/capture button Pin
rahuluttekar23-Dec-09 3:06
memberrahuluttekar23-Dec-09 3:06 
GeneralBlack frame Pin
falkevich15-Dec-09 23:32
memberfalkevich15-Dec-09 23:32 
GeneralSetting Properties of a DirectShow source filter (not DMO filter) in code (no GUI) Pin
RobstaHendricks12-Nov-09 2:48
memberRobstaHendricks12-Nov-09 2:48 
GeneralRe: Setting Properties of a DirectShow source filter (not DMO filter) in code (no GUI) Pin
RobstaHendricks18-Nov-09 22:21
memberRobstaHendricks18-Nov-09 22:21 
Questionhow can i set default resolution (in code)? Pin
booyeeka29-Oct-09 19:30
memberbooyeeka29-Oct-09 19:30 
QuestionCan I capture video to a MemoryStream? Pin
jimnox28-Oct-09 0:13
memberjimnox28-Oct-09 0:13 
QuestionHow can I change the audio sound track? Pin
ericmacau26-Oct-09 5:46
memberericmacau26-Oct-09 5:46 
GeneralImage is not grabbed if the grabber form is not the main form. Pin
Member 432874114-Oct-09 7:17
memberMember 432874114-Oct-09 7:17 
Generalno audio on some mp3s Pin
gl_media13-Oct-09 6:09
membergl_media13-Oct-09 6:09 
QuestionCustomize resolution Pin
Zeeshan Ahsan11-Sep-09 1:48
memberZeeshan Ahsan11-Sep-09 1:48 
GeneralDsDevice.Name not full name Pin
Danielku152-Sep-09 10:00
memberDanielku152-Sep-09 10:00 
Generaldfg Pin
deepak ghimire1-Sep-09 22:52
memberdeepak ghimire1-Sep-09 22:52 
QuestionAny one tryed to capture a "LiveView" video from a Codac EOS camera?? Pin
Kjelle P27-Aug-09 13:06
memberKjelle P27-Aug-09 13:06 
QuestionCan I used this lib for commercial purpose ? Pin
Koushik27-Jul-09 14:50
memberKoushik27-Jul-09 14:50 
QuestionHow to start capturing in composite video mode? Pin
sameh_serag24-Jul-09 19:24
membersameh_serag24-Jul-09 19:24 
GeneralGood Pin
wise.bear20-Jul-09 23:35
memberwise.bear20-Jul-09 23:35 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190618.1 | Last Updated 23 Jul 2002
Article Copyright 2002 by NETMaster
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid