C# Class DirectX.Capture.Capture

Use the Capture class to capture audio and video to AVI files.
This is the core class of the Capture Class Library. The following sections introduce the Capture class and how to use this library.

Basic Usage

The Capture class only requires a video device and/or audio device to begin capturing. The Filters class provides lists of the installed video and audio devices.

// Remember to add a reference to DirectX.Capture.dll using DirectX.Capture ... Capture capture = new Capture( Filters.VideoInputDevices[0], Filters.AudioInputDevices[0] ); capture.Start(); ... capture.Stop();

This 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 of 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. Remember to add DirectX.Capture.dll to your project references.


Setting Common Properties

The example below shows how to change video and audio settings. Properties such as Capture.FrameRate and 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; capture.FrameSize = new Size( 640, 480 ); capture.AudioSamplingRate = 44100; capture.AudioSampleSize = 16; 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 a 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.


Listing Devices

Use the Filters.VideoInputDevices collection to list video capture devices installed on the system.

foreach ( Filter f in Filters.VideoInputDevices ) { Debug.WriteLine( f.Name ); }
The Filters class also provides collections for audio capture devices, video compressors and audio compressors.

Preview

Video preview is controled with the Capture.PreviewWindow property. Setting this property to a visible control will immediately begin preview. Set to null to stop the preview.

// Enable preview capture.PreviewWindow = myPanel; // Disable preview capture.PreviewWindow = null;

The control used must have a window handle (HWND), good controls to use are the Panel or the form itself.

Retrieving or changing video/audio settings such as FrameRate, FrameSize, AudioSamplingRate, and AudioSampleSize will cause the preview window to flash. This is beacuse the preview must be temporarily stopped. Disable the preview if you need to access several properties at the same time.


Property Pages

Property pages exposed by the devices and compressors are available through the Capture.PropertyPages collection.

// Display the first property page capture.PropertyPages[0].Show();

The property pages will often expose more settings than the Capture class does directly. Some examples are brightness, color space, audio balance and bass boost. The disadvantage to using the property pages is the user's choices cannot be saved and later restored. The exception to this is the video and audio compressor property pages. Most compressors support the saving and restoring state, see the PropertyPage.State property for more information.

Changes made in the property page will be reflected immediately in the Capture class properties (e.g. Capture.FrameSize). However, the reverse is not always true. A change made directly to FrameSize, for example, may not be reflected in the associated property page. Fortunately, the filter will use requested FrameSize even though the property page shows otherwise.


Saving and Restoring Settings

To save the user's choice of devices and compressors, save Filter.MonikerString and user it later to recreate the Filter object.

To save a user's choices from a property page use PropertyPage.State. However, only the audio and video compressor property pages support this.

The last items to save are the video and audio settings such as FrameSize and AudioSamplingRate. When restoring, remember to restore these properties after setting the video and audio compressors.

// Disable preview capture.PreviewWindow = null; // Save settings string videoDevice = capture.VideoDevice.MonikerString; string audioDevice = capture.AudioDevice.MonikerString; string videoCompressor = capture.VideoCompressor.MonikerString; string audioCompressor = capture.AudioCompressor.MonikerString; double frameRate = capture.FrameRate; Size frameSize = capture.FrameSize; short audioChannels = capture.AudioChannels; short audioSampleSize = capture.AudioSampleSize; int audioSamplingRate = capture.AudioSamplingRate; ArrayList pages = new ArrayList(); foreach ( PropertyPage p in capture.PropertyPages ) { if ( p.SupportsPersisting ) pages.Add( p.State ); } // Restore settings Capture capture = new Capture( new Filter( videoDevice), new Filter( audioDevice) ); capture.VideoCompressor = new Filter( videoCompressor ); capture.AudioCompressor = new Filter( audioCompressor ); capture.FrameRate = frameRate; capture.FrameSize = frameSize; capture.AudioChannels = audioChannels; capture.AudioSampleSize = audioSampleSize; capture.AudioSamplingRate = audioSamplingRate; foreach ( PropertyPage p in capture.PropertyPages ) { if ( p.SupportsPersisting ) { p.State = (byte[]) pages[0] pages.RemoveAt( 0 ); } } // Enable preview capture.PreviewWindow = myPanel;

TV Tuner

To access the TV Tuner, use the Capture.Tuner property. If the device does not have a TV tuner, this property will be null. See DirectX.Capture.Tuner.Channel, DirectX.Capture.Tuner.InputType and DirectX.Capture.Tuner.SignalPresent for more information.

// Change to channel 5 capture.Tuner.Channel = 5;

Troubleshooting

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.

Try the AMCap sample from the DirectX SDK (DX9\Samples\C++\DirectShow\Bin\AMCap.exe) or Virtual VCR from http://www.DigTV.ws


Credits

This class library would not be possible without the DShowNET project by NETMaster: http://www.codeproject.com/useritems/directshownet.asp

Documentation is generated by nDoc available at http://ndoc.sourceforge.net


Feedback

Feel free to send comments and questions to me at [email protected]. If the the topic may be of interest to others, post your question on the www.codeproject.com page for DirectX.Capture.
Inheritance: ISampleGrabberCB
Show file Open project: parhansson/KMotionX Class Usage Examples

Public Properties

Property Type Description
dxUtils DirectX.Capture.DxUtils

Protected Properties

Property Type Description
audioCaps AudioCapabilities
audioCompressor Filter
audioCompressorFilter IBaseFilter
audioDevice Filter
audioDeviceFilter IBaseFilter
audioSources SourceCollection
audioStreamConfig IAMStreamConfig
captureGraphBuilder ICaptureGraphBuilder2
fileWriterFilter IFileSinkFilter
filename string
graphBuilder IGraphBuilder
graphState GraphState
isCaptureRendered bool
isPreviewRendered bool
mediaControl IMediaControl
muxFilter IBaseFilter
previewCaps DirectX.Capture.VideoCapabilities
previewStreamConfig IAMStreamConfig
previewWindow System.Windows.Forms.Control
propertyPages PropertyPageCollection
recFileMode RecFileModeType
rotCookie DsROTEntry
rotCookie int
sampGrabber ISampleGrabber
tuner Tuner
tvAudio IAMTVAudio
videoCaps DirectX.Capture.VideoCapabilities
videoCompressor Filter
videoCompressorFilter IBaseFilter
videoDevice Filter
videoDeviceFilter IBaseFilter
videoSources SourceCollection
videoStreamConfig IAMStreamConfig
videoWindow IVideoWindow
wantCaptureRendered bool
wantPreviewRendered bool

Public Methods

Method Description
Capture ( Filter videoDevice, Filter audioDevice, bool audioViaPci ) : System

Create a new Capture object. videoDevice and audioDevice can be null if you do not wish to capture both audio and video. However at least one must be a valid device. Use the Filters class to list available devices.

Cue ( ) : void

Prepare for capturing. Use this method when capturing must begin as quickly as possible.

This will create/overwrite a zero byte file with the name set in the Filename property.

This will disable preview. Preview will resume once capture begins. This problem can be fixed if someone is willing to make the change.

This method is optional. If Cue() is not called, Start() will call it before capturing. This method cannot be called while capturing.

DisableEvent ( ) : void

Disable grabbing next frame

Dispose ( ) : void

Calls Stop, releases all references. If a capture is in progress it will be stopped, but the CaptureComplete event will NOT fire.

DisposeSampleGrabber ( ) : void

Dispose Sample Grabber specific data

GrapImg ( ) : void

Allocate memory space and set SetCallBack

ShowPropertyPage ( int filter, Control o ) : bool

Show property page of object

Start ( ) : void

Begin capturing.

Stop ( ) : void

Stop the current capture capture. If there is no current capture, this method will succeed.

Protected Methods

Method Description
assertStopped ( ) : void

Assert that the class is in a Stopped state.

createGraph ( ) : void

Create a new filter graph and add filters (devices, compressors, misc), but leave the filters unconnected. Call renderGraph() to connect the filters.

derenderGraph ( ) : void

Disconnect and remove all filters except the device and compressor filters. This is the opposite of renderGraph(). Soem properties such as FrameRate can only be set when the device output pins are not connected.

destroyGraph ( ) : void

Completely tear down a filter graph and release all associated resources.

getStreamConfigSetting ( IAMStreamConfig streamConfig, string fieldName ) : object

Retrieves the value of one member of the IAMStreamConfig format block. Helper function for several properties that expose video/audio settings from IAMStreamConfig.GetFormat(). IAMStreamConfig.GetFormat() returns a AMMediaType struct. AMMediaType.formatPtr points to a format block structure. This format block structure may be one of several types, the type being determined by AMMediaType.formatType.

getTempFilename ( ) : string

Get a valid temporary filename (with path). We aren't using Path.GetTempFileName() because it creates a 0-byte file

onPreviewWindowResize ( object sender, EventArgs e ) : void

Resize the preview when the PreviewWindow is resized

removeDownstream ( IBaseFilter filter, bool removeFirstFilter ) : void

Removes all filters downstream from a filter from the graph. This is called only by derenderGraph() to remove everything from the graph except the devices and compressors. The parameter "removeFirstFilter" is used to keep a compressor (that should be immediately downstream of the device) if one is begin used.

renderGraph ( ) : void

Connects the filters of a previously created graph (created by createGraph()). Once rendered the graph is ready to be used. This method may also destroy streams if we have streams we no longer want.

setStreamConfigSetting ( IAMStreamConfig streamConfig, string fieldName, object newValue ) : object

Set the value of one member of the IAMStreamConfig format block. Helper function for several properties that expose video/audio settings from IAMStreamConfig.GetFormat(). IAMStreamConfig.GetFormat() returns a AMMediaType struct. AMMediaType.formatPtr points to a format block structure. This format block structure may be one of several types, the type being determined by AMMediaType.formatType.

startPreviewIfNeeded ( ) : void

Setup and start the preview window if the user has requested it (by setting PreviewWindow).

Private Methods

Method Description
AddDeInterlaceFilter ( ) : bool
ISampleGrabberCB ( double SampleTime, IMediaSample pSample ) : int
ISampleGrabberCB ( double SampleTime, IntPtr pBuffer, int BufferLen ) : int
InitSampleGrabber ( ) : bool
InitVideoRenderer ( ) : bool
SetMediaSampleGrabber ( ) : void
getMediaSubType ( IAMStreamConfig streamConfig ) : DxUtils.ColorSpaceEnum
setMediaSubType ( IAMStreamConfig streamConfig, DirectX.Capture.DxUtils newValue ) : void

Method Details

Capture() public method

Create a new Capture object. videoDevice and audioDevice can be null if you do not wish to capture both audio and video. However at least one must be a valid device. Use the Filters class to list available devices.
public Capture ( Filter videoDevice, Filter audioDevice, bool audioViaPci ) : System
videoDevice Filter
audioDevice Filter
audioViaPci bool
return System

Cue() public method

Prepare for capturing. Use this method when capturing must begin as quickly as possible.
This will create/overwrite a zero byte file with the name set in the Filename property.

This will disable preview. Preview will resume once capture begins. This problem can be fixed if someone is willing to make the change.

This method is optional. If Cue() is not called, Start() will call it before capturing. This method cannot be called while capturing.

public Cue ( ) : void
return void

DisableEvent() public method

Disable grabbing next frame
public DisableEvent ( ) : void
return void

Dispose() public method

Calls Stop, releases all references. If a capture is in progress it will be stopped, but the CaptureComplete event will NOT fire.
public Dispose ( ) : void
return void

DisposeSampleGrabber() public method

Dispose Sample Grabber specific data
public DisposeSampleGrabber ( ) : void
return void

GrapImg() public method

Allocate memory space and set SetCallBack
public GrapImg ( ) : void
return void

ShowPropertyPage() public method

Show property page of object
public ShowPropertyPage ( int filter, Control o ) : bool
filter int
o System.Windows.Forms.Control
return bool

Start() public method

Begin capturing.
public Start ( ) : void
return void

Stop() public method

Stop the current capture capture. If there is no current capture, this method will succeed.
public Stop ( ) : void
return void

assertStopped() protected method

Assert that the class is in a Stopped state.
protected assertStopped ( ) : void
return void

createGraph() protected method

Create a new filter graph and add filters (devices, compressors, misc), but leave the filters unconnected. Call renderGraph() to connect the filters.
protected createGraph ( ) : void
return void

derenderGraph() protected method

Disconnect and remove all filters except the device and compressor filters. This is the opposite of renderGraph(). Soem properties such as FrameRate can only be set when the device output pins are not connected.
protected derenderGraph ( ) : void
return void

destroyGraph() protected method

Completely tear down a filter graph and release all associated resources.
protected destroyGraph ( ) : void
return void

getStreamConfigSetting() protected method

Retrieves the value of one member of the IAMStreamConfig format block. Helper function for several properties that expose video/audio settings from IAMStreamConfig.GetFormat(). IAMStreamConfig.GetFormat() returns a AMMediaType struct. AMMediaType.formatPtr points to a format block structure. This format block structure may be one of several types, the type being determined by AMMediaType.formatType.
protected getStreamConfigSetting ( IAMStreamConfig streamConfig, string fieldName ) : object
streamConfig IAMStreamConfig
fieldName string
return object

getTempFilename() protected method

Get a valid temporary filename (with path). We aren't using Path.GetTempFileName() because it creates a 0-byte file
protected getTempFilename ( ) : string
return string

onPreviewWindowResize() protected method

Resize the preview when the PreviewWindow is resized
protected onPreviewWindowResize ( object sender, EventArgs e ) : void
sender object
e System.EventArgs
return void

removeDownstream() protected method

Removes all filters downstream from a filter from the graph. This is called only by derenderGraph() to remove everything from the graph except the devices and compressors. The parameter "removeFirstFilter" is used to keep a compressor (that should be immediately downstream of the device) if one is begin used.
protected removeDownstream ( IBaseFilter filter, bool removeFirstFilter ) : void
filter IBaseFilter
removeFirstFilter bool
return void

renderGraph() protected method

Connects the filters of a previously created graph (created by createGraph()). Once rendered the graph is ready to be used. This method may also destroy streams if we have streams we no longer want.
protected renderGraph ( ) : void
return void

setStreamConfigSetting() protected method

Set the value of one member of the IAMStreamConfig format block. Helper function for several properties that expose video/audio settings from IAMStreamConfig.GetFormat(). IAMStreamConfig.GetFormat() returns a AMMediaType struct. AMMediaType.formatPtr points to a format block structure. This format block structure may be one of several types, the type being determined by AMMediaType.formatType.
protected setStreamConfigSetting ( IAMStreamConfig streamConfig, string fieldName, object newValue ) : object
streamConfig IAMStreamConfig
fieldName string
newValue object
return object

startPreviewIfNeeded() protected method

Setup and start the preview window if the user has requested it (by setting PreviewWindow).
protected startPreviewIfNeeded ( ) : void
return void

Property Details

audioCaps protected property

protected AudioCapabilities,DirectX.Capture audioCaps
return AudioCapabilities

audioCompressor protected property

protected Filter,DirectX.Capture audioCompressor
return Filter

audioCompressorFilter protected property

protected IBaseFilter audioCompressorFilter
return IBaseFilter

audioDevice protected property

protected Filter,DirectX.Capture audioDevice
return Filter

audioDeviceFilter protected property

protected IBaseFilter audioDeviceFilter
return IBaseFilter

audioSources protected property

protected SourceCollection,DirectX.Capture audioSources
return SourceCollection

audioStreamConfig protected property

protected IAMStreamConfig audioStreamConfig
return IAMStreamConfig

captureGraphBuilder protected property

protected ICaptureGraphBuilder2 captureGraphBuilder
return ICaptureGraphBuilder2

dxUtils public property

Interface to DirectShow utilities for controlling video
public DxUtils,DirectX.Capture dxUtils
return DirectX.Capture.DxUtils

fileWriterFilter protected property

protected IFileSinkFilter fileWriterFilter
return IFileSinkFilter

filename protected property

protected string filename
return string

graphBuilder protected property

protected IGraphBuilder graphBuilder
return IGraphBuilder

graphState protected property

protected GraphState graphState
return GraphState

isCaptureRendered protected property

protected bool isCaptureRendered
return bool

isPreviewRendered protected property

protected bool isPreviewRendered
return bool

mediaControl protected property

protected IMediaControl mediaControl
return IMediaControl

muxFilter protected property

protected IBaseFilter muxFilter
return IBaseFilter

previewCaps protected property

Property Backer: preview capabilities of video device
protected VideoCapabilities,DirectX.Capture previewCaps
return DirectX.Capture.VideoCapabilities

previewStreamConfig protected property

IAMStreamConfig interface of preview pin. It is not really common that the preview has such interface, but if it has such interface it can be used "independent" from the capture pin interface.
protected IAMStreamConfig previewStreamConfig
return IAMStreamConfig

previewWindow protected property

protected Control,System.Windows.Forms previewWindow
return System.Windows.Forms.Control

propertyPages protected property

protected PropertyPageCollection,DirectX.Capture propertyPages
return PropertyPageCollection

recFileMode protected property

Recording file mode (e.g. Windows Media Audio)
protected RecFileModeType recFileMode
return RecFileModeType

rotCookie protected property

Special variable for debugging purposes Cookie into the Running Object Table
protected DsROTEntry rotCookie
return DsROTEntry

rotCookie protected property

protected int rotCookie
return int

sampGrabber protected property

Sample Grabber interface
protected ISampleGrabber sampGrabber
return ISampleGrabber

tuner protected property

protected Tuner,DirectX.Capture tuner
return Tuner

tvAudio protected property

IAMTVAudio property
protected IAMTVAudio tvAudio
return IAMTVAudio

videoCaps protected property

protected VideoCapabilities,DirectX.Capture videoCaps
return DirectX.Capture.VideoCapabilities

videoCompressor protected property

protected Filter,DirectX.Capture videoCompressor
return Filter

videoCompressorFilter protected property

protected IBaseFilter videoCompressorFilter
return IBaseFilter

videoDevice protected property

protected Filter,DirectX.Capture videoDevice
return Filter

videoDeviceFilter protected property

protected IBaseFilter videoDeviceFilter
return IBaseFilter

videoSources protected property

protected SourceCollection,DirectX.Capture videoSources
return SourceCollection

videoStreamConfig protected property

protected IAMStreamConfig videoStreamConfig
return IAMStreamConfig

videoWindow protected property

protected IVideoWindow videoWindow
return IVideoWindow

wantCaptureRendered protected property

protected bool wantCaptureRendered
return bool

wantPreviewRendered protected property

protected bool wantPreviewRendered
return bool