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

 
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 
GeneralError while selecting a video device twice. Pin
Jack987323-Jun-09 19:23
memberJack987323-Jun-09 19:23 
GeneralRe: Error while selecting a video device twice. Pin
Rolf Szomor9-Jul-09 9:25
memberRolf Szomor9-Jul-09 9:25 
QuestionRe: Error while selecting a video device twice. Pin
hollyever28-Jul-09 21:20
memberhollyever28-Jul-09 21:20 
AnswerRe: Error while selecting a video device twice. Pin
Jack98733-Sep-09 19:57
memberJack98733-Sep-09 19:57 
GeneralRe: Error while selecting a video device twice - Now it works. Pin
Member 432874114-Oct-09 6:56
memberMember 432874114-Oct-09 6:56 
QuestionDirectShow TvTuner "cold start" Pin
Rolf Szomor10-Jun-09 1:25
memberRolf Szomor10-Jun-09 1:25 
Hi Everyone!

I have a strange problem. I develop a TvTuner application, and successfully build/use/modify/dispose/rebuild my filter graph, everything works fine, however just after I started my original (vendor's) tv application. If I try to render my graph I see only the blue rectangle. Once started the vendor's application my application renders the correct Tv stream. I think I am missing something, some settings... My application is working fine until I restart my computer. Thus I think the original application turns something on in my tuner card which I don't do in my code. I noticed another strange thing: I can save my own built filter graph by doing this:

IGraphBuilder graphBuilder = (IGraphBuilder) new FilterGraph();
//BUILDING MY GRAPH HERE

private void SaveGraph(string graphFileName)
{
IPersistStream per = (IPersistStream) graphBuilder;
string fileName = @"C:\Temp\" + graphFileName;

IStorage storage = null;
IStream stream = null;

//if (NativeMethods.StgIsStorageFile(fileName) != 0)return;

int hr = NativeMethods.StgCreateDocfile(
fileName,
STGM.Create | STGM.Transacted | STGM.ReadWrite | STGM.ShareExclusive,
0,
out storage
);
DsError.ThrowExceptionForHR(hr);

hr = storage.CreateStream(
@"ActiveMovieGraph",
STGM.Write | STGM.Create | STGM.ShareExclusive,
0,
0,
out stream
);
DsError.ThrowExceptionForHR(hr);

hr = per.Save(stream, true);
DsError.ThrowExceptionForHR(hr);

stream.Commit(0);
hr = storage.Commit(STGC.Overwrite);
DsError.ThrowExceptionForHR(hr);


Marshal.ReleaseComObject(storage);
Marshal.ReleaseComObject(stream);
}

After that I can load my saved graph with this code:

private void LoadGraph(string graphFileName)
{
IPersistStream per = (IPersistStream)graphBuilder;
string fileName = @"C:\Temp\" + graphFileName;

IStorage storage = null;
IStream stream = null;

if (NativeMethods.StgIsStorageFile(fileName) != 0)
return;

int hr = NativeMethods.StgOpenStorage(
fileName,
null,
STGM.Transacted | STGM.Read | STGM.ShareDenyWrite,
IntPtr.Zero,
0,
out storage
);
DsError.ThrowExceptionForHR(hr);

hr = storage.OpenStream(
@"ActiveMovieGraph",
IntPtr.Zero,
STGM.Read | STGM.ShareExclusive,
0,
out stream
);
DsError.ThrowExceptionForHR(hr);


hr = per.Load(stream);
DsError.ThrowExceptionForHR(hr);
}

And there is the magic: after loading my own built graph it works fine also after computer restart (cold start).

Thus shortly:

After my computer restarts:
- building my graph and running does not work.
- loading my built and saved (did not made with graphedit!) graph turns something on, and it works.

After one successful rendering (with loading .grf file in my code, or starting vendor's Tv software), my built graph starts working fine.


I tried to put the correct country code (IAMTVTuner.put_CountryCode) on my tuner object, correct input source (IAMTVTuner.put_ConnectInput), fine tuned the channel, setted input type to antenna (IAMTVTuner.put_InputType), setted mode to television (IAMTVTuner.put_Mode)... Nothing helpedFrown | :(

Anyone has any idea, what could be the problem?

(I have WinFast Pvr2000)

Many Thanks!

Rolf

AnswerRe: DirectShow TvTuner "cold start" Pin
Rolf Szomor9-Jul-09 9:17
memberRolf Szomor9-Jul-09 9:17 
AnswerRe: DirectShow TvTuner "cold start" Pin
RobstaHendricks16-Nov-09 5:23
memberRobstaHendricks16-Nov-09 5:23 
GeneralRe: DirectShow TvTuner "cold start" Pin
RobstaHendricks16-Nov-09 23:17
memberRobstaHendricks16-Nov-09 23:17 
GeneralRe: DirectShow TvTuner "cold start" Pin
SanShark18-Nov-09 21:36
memberSanShark18-Nov-09 21:36 
GeneralRe: DirectShow TvTuner "cold start" Pin
RobstaHendricks18-Nov-09 22:20
memberRobstaHendricks18-Nov-09 22:20 
QuestionICaptureGraphBuilder2::RenderStream method take lot off time to return Pin
Bhushan Badhe26-May-09 18:29
memberBhushan Badhe26-May-09 18:29 
GeneralBlack Images Pin
Jack987319-May-09 22:55
memberJack987319-May-09 22:55 
QuestionVideo from a Streaming server?? Pin
iFarhan29-Apr-09 20:08
memberiFarhan29-Apr-09 20:08 
Questionwhat to do after capturing pointer of data using DirectShow.NET Pin
Khurram Shakoor10-Apr-09 2:21
memberKhurram Shakoor10-Apr-09 2:21 
GeneralManage colors during Capturing Pin
anki12310-Mar-09 1:42
memberanki12310-Mar-09 1:42 
GeneralWatermark Videos Pin
anki1231-Mar-09 20:04
memberanki1231-Mar-09 20:04 
GeneralDshownet and x64 Pin
carle25725-Feb-09 19:37
membercarle25725-Feb-09 19:37 
QuestionCapturing Video and Image at the same time using DShowNet Pin
shankarsangoli26-Dec-08 9:07
membershankarsangoli26-Dec-08 9:07 
QuestionFlipping the subtitles in a Dvd Pin
GrizzlyDoug2-Dec-08 6:11
memberGrizzlyDoug2-Dec-08 6:11 
GeneralRecompressing files Pin
_malf28-Nov-08 2:39
member_malf28-Nov-08 2:39 
GeneralVC++ code Pin
islamicsoft8-Oct-08 1:32
memberislamicsoft8-Oct-08 1:32 
QuestionAudio... with CaptureNET Pin
deching5-Oct-08 12:47
memberdeching5-Oct-08 12:47 

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.

Layout: fixed | fluid

Article Copyright 2002 by NETMaster
Everything else Copyright © CodeProject, 1999-2019

Server Web01
Version 2.8.190619.2