Click here to Skip to main content
14,331,020 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

 
GeneralDocumentation of DirectShow.NET Pin
B!Z22-May-07 18:56
memberB!Z22-May-07 18:56 
GeneralPlease I need your help Pin
Ali Habib10-May-07 10:42
memberAli Habib10-May-07 10:42 
QuestionHow to install and run in Windows XP Embedded? Pin
xxxbltxxx26-Mar-07 0:09
memberxxxbltxxx26-Mar-07 0:09 
Generalpoor TV Graphic /picture quality problem Pin
Lalit N Dubey19-Mar-07 21:49
memberLalit N Dubey19-Mar-07 21:49 
QuestionHelp :Interesting question Pin
wild_bunch17-Mar-07 21:45
memberwild_bunch17-Mar-07 21:45 
QuestionSemi-Transparent Control Item overlaying the Video playing background???? Pin
big_boss1201115-Mar-07 15:07
memberbig_boss1201115-Mar-07 15:07 
Questioni want to know how to use DirectShow.net to Get Byte[] Pin
bryan_game12-Mar-07 6:17
memberbryan_game12-Mar-07 6:17 
QuestionNo TV sound Pin
AlexMartins9-Mar-07 7:03
memberAlexMartins9-Mar-07 7:03 
Hello! Nice article.
I'm using an inside TV/FM card. I can control TV tunning but I get no TV sound. If I use an USB TV box it works because I route the Audio_Tuner to Audio_AudioDecoder on the IAMCrossbar object. But, when I do that in the inside TV card that don´t work.
Do I have to create an Audio Filter to that? Can you help me?

Here is the main code I'm usin for that:
<br />
private bool OndeEstáOHardawredeTV()<br />
        {<br />
            object obj = null;<br />
<br />
            #region TV tuner<br />
            Guid cat = PinCategory.Capture;<br />
            Guid type = MediaType.Video;<br />
            Guid iid = typeof(IAMTVTuner).GUID;<br />
            int hr = CapturaVídeo.FindInterface(ref cat, ref type, FiltroAq, ref iid, out obj);<br />
            if (hr >= 0)<br />
            {<br />
                int ci;<br />
                televisão = (IAMTVTuner)obj;<br />
                televisão.put_Mode(AMTunerModeType.TV);<br />
                televisão.put_InputType(0, TunerInputType.Antenna);<br />
                televisão.put_CountryCode(351);<br />
                televisão.put_TuningSpace(0);<br />
                televisão.get_ConnectInput(out ci);<br />
                MessageBox.Show(string.Format(" Connect Input: {0}", ci));<br />
                televisão.put_ConnectInput(0);<br />
                obj = null;<br />
                // Seleccionar a fonte de áudio da placa de TV (Select audio source from TV card)<br />
                iid = typeof(IAMCrossbar).GUID;<br />
                type = MediaType.Video;<br />
                hr = CapturaVídeo.FindInterface(ref cat, ref type, FiltroAq, ref iid, out obj);<br />
                if (hr >= 0)<br />
                {<br />
                    crossbar = (IAMCrossbar)obj;<br />
                    int oPin, iPin;<br />
                    int oaLink, iaLink, ovLink, ivLink;<br />
                    oaLink = iaLink = ovLink = ivLink = 0;<br />
                    crossbar.get_PinCounts(out oPin, out iPin);<br />
                    int pIdxRel;<br />
                    PhysicalConnectorType tp;<br />
                    for (int i = 0; i < iPin; i++)<br />
                    {<br />
                        crossbar.get_CrossbarPinInfo(true, i, out pIdxRel, out tp);<br />
                        if (tp == PhysicalConnectorType.Audio_Tuner)<br />
                            iaLink = i;<br />
                        if (tp == PhysicalConnectorType.Video_Tuner)<br />
                            ivLink = i;<br />
                    }<br />
                    for (int i = 0; i < oPin; i++)<br />
                    {<br />
                        crossbar.get_CrossbarPinInfo(false, i, out pIdxRel, out tp);<br />
                        if (tp == PhysicalConnectorType.Audio_AudioDecoder)<br />
                            oaLink = i;<br />
                        if (tp == PhysicalConnectorType.Video_VideoDecoder)<br />
                            ovLink = i;<br />
                    }<br />
                    try<br />
                    {<br />
                        crossbar.Route(ovLink, ivLink);<br />
                        crossbar.Route(oaLink, iaLink);<br />
                        obj = null;<br />
                        return true;<br />
                    }<br />
                    catch<br />
                    {<br />
                        MessageBox.Show("NOT ROUTED");<br />
                        return false;<br />
                    }<br />
               }<br />
                else<br />
                {<br />
                    return false;<br />
                }<br />
            }<br />
            else<br />
            {<br />
                return false;<br />
            }<br />
            #endregion<br />
        }<br />
Smile | :)

Alexandre Martins
AnswerRe: No TV sound Pin
Saber00125-Aug-10 23:13
memberSaber00125-Aug-10 23:13 
Generalvideo compression Pin
Member 38231437-Mar-07 18:21
memberMember 38231437-Mar-07 18:21 
GeneralRe: video compression Pin
gan_esh20-Jun-07 19:11
membergan_esh20-Jun-07 19:11 
QuestionVideo processing Pin
Andy12422674516355-Mar-07 15:27
memberAndy12422674516355-Mar-07 15:27 
Generalmultiple sound cards Pin
venutech19-Jan-07 19:10
membervenutech19-Jan-07 19:10 
GeneralLoop problem in capturing image using webcam Pin
Norshuhada Samudin5-Jan-07 15:23
memberNorshuhada Samudin5-Jan-07 15:23 
GeneralDShowNET on .NET CF 2.0 SP1 Pin
HCunningham4-Jan-07 9:28
memberHCunningham4-Jan-07 9:28 
GeneralRe: DShowNET on .NET CF 2.0 SP1 Pin
connectpalm10-Nov-09 5:23
memberconnectpalm10-Nov-09 5:23 
GeneralGetting Error... Pin
Vishram30-Dec-06 14:41
memberVishram30-Dec-06 14:41 
GeneralGraph filter directshownet Pin
stefano.marini13-Dec-06 3:43
memberstefano.marini13-Dec-06 3:43 
Questionquestion about the sample of CaptureNET Pin
zhoulia581630-Oct-06 19:03
memberzhoulia581630-Oct-06 19:03 
GeneralLive streaming Pin
AB77715-Oct-06 0:02
memberAB77715-Oct-06 0:02 
QuestionGeneric error occured in GDI+ Pin
labby21-Sep-06 22:22
memberlabby21-Sep-06 22:22 
AnswerRe: Generic error occured in GDI+ Pin
Christian Graus1-Oct-06 12:29
protectorChristian Graus1-Oct-06 12:29 
AnswerRe: Generic error occured in GDI+ Pin
simple2_de13-Dec-06 22:25
membersimple2_de13-Dec-06 22:25 
GeneralRe: Generic error occured in GDI+ Pin
labby15-Dec-06 4:21
memberlabby15-Dec-06 4:21 
QuestionStrange Error Pin
Markus120120-Sep-06 12:59
memberMarkus120120-Sep-06 12:59 

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.7K downloads
450 bookmarked