Click here to Skip to main content
Click here to Skip to main content

DirectX.Capture Class Library

By , 29 Mar 2008
 
Sample Image - DirectXCapture.jpg

Introduction

This article presents a class library for capturing audio and video to AVI files in .NET. Some of the features of this library:

  • List and select hardware devices
  • Access to common audio and video settings (e.g. frame rate, size)
  • Support audio and video compression codecs
  • Support video preview
  • Support TV tuners
  • Support crossbars and audio mixers
  • Retrieve device capabilities
  • Show property pages exposed by drivers
  • MSDN-style documentation included

Using the Code

The Capture class is the core of this library. Here is a simple example:

// Remember to add a reference to DirectX.Capture.dll
using DirectX.Capture

// Capture using the first video
// and audio devices available
Capture capture = new Capture( Filters.VideoInputDevices[0],
                               Filters.AudioInputDevices[0] );

// Start capturing
capture.Start();

// Stop capturing
capture.Stop();

Remember to add a reference in your project to DirectX.Capture.dll. This DLL requires DShowNET.dll, so make sure they are both in the same directory. Once you add the reference, Visual Studio .NET should take care of the copying for you.

This example will capture video and audio using the first video and audio devices installed on the system. To capture video only, pass a null as the second parameter to the constructor.

The class is initialized to a valid temporary file in the Windows temp folder. To capture to a different file, set the Capture.Filename property before you begin capturing.

A Second Example

This next example shows how to change video and audio settings. Properties such as Capture.FrameRate and Capture.AudioSampleSize allow you to programmatically adjust the capture. Use Capture.VideoCaps and Capture.AudioCaps to determine valid values for these properties.

Capture capture = new Capture( Filters.VideoInputDevices[0],
                               Filters.AudioInputDevices[1] );

capture.VideoCompressor = Filters.VideoCompressors[0];
capture.AudioCompressor = Filters.AudioCompressors[0];

capture.FrameRate = 29.997;                 // NTSC
capture.FrameSize = new Size( 640, 480 );   // 640x480
capture.AudioSamplingRate = 44100;          // 44.1 kHz
capture.AudioSampleSize = 16;               // 16-bit
capture.AudioChannels = 1;                  // Mono

capture.Filename = "C:\MyVideo.avi";

capture.Start();
...
capture.Stop();

The example above also shows the use of video and audio compressors. In most cases, you will want to use compressors. Uncompressed video can easily consume over 1GB of disk space per minute. Whenever possible, set the Capture.VideoCompressor and Capture.AudioCompressor properties as early as possible. Changing them requires the internal filter graph to be rebuilt which often causes most of the other properties to be reset to default values.

Behind the Scenes

This project uses 100% DirectShow to capture video. Once a capture is started, DirectShow spawns another thread and handles retrieving/moving all the video and audio data itself. That means you should be able to capture at the same speed and quality as an application written in C.

DirectShow is implemented as a set of COM components and we use .NET Interop to access them. The pioneering work on this was done by NETMaster with the DShowNET project. This Capture library uses DShowNET for the interop layer with only a few extensions. This is the DShowNET.dll mentioned earlier.

Sitting on top of all of this is the Capture class library. The center of any DirectShow app is the filter graph and the filter graph manager. For a good overview, see The Filter Graph and Its Components from the MSDN.

The Least Work Possible

The library tries at all times to do the least amount of work possible. The problem is: DirectShow is very flexible, but has few firm standards for driver developers and I have limited hardware to test with. As a result, the class tries to avoid doing any work that may not be necessary, hopefully avoiding potential incompatibilities in the process.

One example is video preview. You can start and stop preview with:

// Start preview
capture.PreviewWindow = myPanelControl;

// Stop preview
capture.PreviewWindow = null;

Hopefully this is simple to use. Internally, DirectShow does a lot of work: add required upstream filters for WDM devices, search for preview pins, use the Overlay Manager for video ports (hardware overlays), insert SmartTee filters when a separate preview pin is not available and more. Instead of rendering the preview stream as soon as the class is created, the class waits until the PreviewWindow property is set.

For developers who don't need preview, none of this work will ever be done. That means your application is more likely to work on a wider range of hardware. For developers that do need preview, this makes it easier to locate the cause of the problem and fix it or handle it gracefully.

Performance Tips

Many of the properties on the Capture class are retrieved directly from the underlying DirectShow COM components. If you need to refer to the property repeatedly in a block of code, take a copy of the value and use your copy.

// AudioSampleSize is retrieved from DirectShow each iteration
for ( int c = 0; c < 32; c++ )
{
    if ( c == capture.AudioSampleSize )
        MessageBox.Show( "Found!" );
}

// A faster solution
int x = capture.AudioSampleSize;
for ( int c = 0; c < 32; c++ )
{
    if ( c == x )
        MessageBox.Show( "Found!" );
}

Why doesn't the class simply cache the value internally? We don't know when the filter (device driver) will change this value, so we have to retrieve the value every time. This means you will always get the real value of the property.

Credits

The DirectShow interop layer was developed by NETMaster in the DShowNET project. The MDSN-style documentation was generated from the source code using nDoc.

Troubleshooting

I have tested this with an Asus v7700 (NVidia GeForce2, reference drivers) and my onboard sound card. I can't guarantee any other hardware will work. However, I expect most video capture cards and sound cards will work. You may have trouble with TV Tuner cards and DV devices (Firewire camcorders) though they should be solvable.

Try the AMCap sample from the DirectX SDK (DX9\Samples\C++\DirectShow\Bin\AMCap.exe) or Virtual VCR, a free DirectShow capture application.

This class library uses COM Interop to access the full capabilities of DirectShow, so if there is another application that can successfully use a hardware device then it should be possible to modify this class library to use the device. Please post your experiences, good or bad, in the forum below.

User Enhancements

The following enhancements have been posted to the discussion board:

Thanks to fdaupias and dauboro for their submissions. I have not had time to post a tested, updated version with these enhancements. If anyone wants to make an updated download zip, mail it to me and I will added it to this page. Keep the enhancements coming.

DirectX.Capture Wiki

A Wiki for this project is available here. This Wiki can be edited by anyone, no registration is required. I hope this Wiki will allow interested users to more easily collaborate on this project. New versions, enhancements, tips and tricks can be posted on the Wiki.

License

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

About the Author

Brian Low
Web Developer
Canada Canada
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionproblem using librarymemberTeo Ryan Hermawan14 Apr '13 - 1:30 
can you explain step by step using your class.
 
i having problem using some function like
Filters.VideoInputDevices[0]
 
i don't know why but after i type "Filters" i can't find suggestion "VideoInputDevices"
 
i have add references directx.capture.dll and DShowNET.dll but i still can't use it.
 
thx.
GeneralMy vote of 5memberMichael Röttges21 Mar '13 - 6:36 
nice!
 
in class "filtercollection.cs" you missed the catch-block, which caused an error in my programm, when a HDMI-Grabber-Device is connected, but no Audio-Device is found in the category, where the filtercollection.cs searches.
Questionframerate higher than 30?memberalejocuba5 Mar '13 - 22:11 
Hi,
 
Very nice code you have uploaded... i need a video with framerate of 50 at least... but using this program i realize i cant get the framerate up from 30. I select last option (59.999) and when i check again it is still at 30, i debuged code and capture.FrameRate when i modifie it it keeps the same 30 rate..
 
Any help?
 
Thanx
AnswerRe: framerate higher than 30?memberMichael Röttges19 Mar '13 - 1:46 
Probably your video device is not supporting framerates higher then 30 fps.
I have connected two devices: simple logitec webcam and a uEye 1240 LE-C-HQ.
If you set the framerate to 60, the logitec webcam is limited at 30.
For the uEye-device, the framerate depends on the framesize. When I set the size to 160 x 120 px, I could reach a framerate which is over 100 fps.
tip: you can get the minimum an maximum framerate when you click at "Video Capabilities"!
Questionneed help for video driver initializationmembersujoybasak1 Feb '13 - 5:09 
when i am running the application after switching on the machine video is not displayed. but if i use cyberlink power director device once and run this application then video is coming.
QuestionPreview HD VideomemberMember 959628429 Jan '13 - 23:34 
Hi everybody,
 
First of all congratulations to all the people working in this proyect. Really an awesome work.
 
The computer running the solution uses Windows 7 64 bits with an Intel Core I5-3470 3.2Ghz.
 
When i use a simple webcam all works really fine. But i only use this for testing, because the device i`m going to finally use is an Avermedia Game Broadcaster HD to capture a Go Pro camera signal (1920x1080, 25fps).
 
I have several problems with this configuration, but the biggest one is about the Preview. For example sometimes i run the program and i see the Preview Window black, in other cases the Preview is ok but when i stop the capture it becomes black or get frozen.
Curiouslly when i manually resize the program window, the Preview refreshes but it stays frozen.
 
I have another problem whith the captured video using the DV encoder filter.
When i play it, image stays frozen about 1 second at start of the video and then continues until the end with no problem.
 
Thanks in advance to all the people working in this proyect.
 
I hope your answers. Thank you.
GeneralI see HomermemberMaoChen19 Jan '13 - 18:07 
terrific!
Questiononly record 64 kbitmemberse10008 Jan '13 - 22:24 
hi
 
record video from capture device only 64 kb but cannot open file with player
please help
QuestionRecording 8bpp (black & white) from cameramemberGilelgrably8 Jan '13 - 22:04 
Hi,
 
I'm using black & white camera, therefore I want to save the AVI file with 8 bits per pixel instead of the regular output of RGB24.
 
Anyway I can do that?
 
Code sample will be appreciated.
Questionx64 solutionmemberKangerm00se18 Oct '12 - 5:47 
I tried to compile it under x64 (because my software needs to work in 64 bit), but the properties etc didn't work anymore. After a while I found a solution:
 
In "DirectShowPropertyPage.cs" and "DsUtils.cs", ther is a DllImport for "olepro32.dll". If you change this into "oleaut32.dll" it works fine.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 29 Mar 2008
Article Copyright 2003 by Brian Low
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid