C# Класс 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.
Наследование: ISampleGrabberCB
Показать файл Открыть проект Примеры использования класса

Открытые свойства

Свойство Тип Описание
dxUtils DirectX.Capture.DxUtils

Защищенные свойства (Protected)

Свойство Тип Описание
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

Открытые методы

Метод Описание
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.

Защищенные методы

Метод Описание
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).

Приватные методы

Метод Описание
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

Описание методов

Capture() публичный Метод

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
Результат System

Cue() публичный Метод

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
Результат void

DisableEvent() публичный Метод

Disable grabbing next frame
public DisableEvent ( ) : void
Результат void

Dispose() публичный Метод

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
Результат void

DisposeSampleGrabber() публичный Метод

Dispose Sample Grabber specific data
public DisposeSampleGrabber ( ) : void
Результат void

GrapImg() публичный Метод

Allocate memory space and set SetCallBack
public GrapImg ( ) : void
Результат void

ShowPropertyPage() публичный Метод

Show property page of object
public ShowPropertyPage ( int filter, Control o ) : bool
filter int
o System.Windows.Forms.Control
Результат bool

Start() публичный Метод

Begin capturing.
public Start ( ) : void
Результат void

Stop() публичный Метод

Stop the current capture capture. If there is no current capture, this method will succeed.
public Stop ( ) : void
Результат void

assertStopped() защищенный Метод

Assert that the class is in a Stopped state.
protected assertStopped ( ) : void
Результат void

createGraph() защищенный Метод

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
Результат void

derenderGraph() защищенный Метод

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
Результат void

destroyGraph() защищенный Метод

Completely tear down a filter graph and release all associated resources.
protected destroyGraph ( ) : void
Результат void

getStreamConfigSetting() защищенный Метод

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
Результат object

getTempFilename() защищенный Метод

Get a valid temporary filename (with path). We aren't using Path.GetTempFileName() because it creates a 0-byte file
protected getTempFilename ( ) : string
Результат string

onPreviewWindowResize() защищенный Метод

Resize the preview when the PreviewWindow is resized
protected onPreviewWindowResize ( object sender, EventArgs e ) : void
sender object
e System.EventArgs
Результат void

removeDownstream() защищенный Метод

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
Результат void

renderGraph() защищенный Метод

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
Результат void

setStreamConfigSetting() защищенный Метод

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
Результат object

startPreviewIfNeeded() защищенный Метод

Setup and start the preview window if the user has requested it (by setting PreviewWindow).
protected startPreviewIfNeeded ( ) : void
Результат void

Описание свойств

audioCaps защищенное свойство

protected AudioCapabilities,DirectX.Capture audioCaps
Результат AudioCapabilities

audioCompressor защищенное свойство

protected Filter,DirectX.Capture audioCompressor
Результат Filter

audioCompressorFilter защищенное свойство

protected IBaseFilter audioCompressorFilter
Результат IBaseFilter

audioDevice защищенное свойство

protected Filter,DirectX.Capture audioDevice
Результат Filter

audioDeviceFilter защищенное свойство

protected IBaseFilter audioDeviceFilter
Результат IBaseFilter

audioSources защищенное свойство

protected SourceCollection,DirectX.Capture audioSources
Результат SourceCollection

audioStreamConfig защищенное свойство

protected IAMStreamConfig audioStreamConfig
Результат IAMStreamConfig

captureGraphBuilder защищенное свойство

protected ICaptureGraphBuilder2 captureGraphBuilder
Результат ICaptureGraphBuilder2

dxUtils публичное свойство

Interface to DirectShow utilities for controlling video
public DxUtils,DirectX.Capture dxUtils
Результат DirectX.Capture.DxUtils

fileWriterFilter защищенное свойство

protected IFileSinkFilter fileWriterFilter
Результат IFileSinkFilter

filename защищенное свойство

protected string filename
Результат string

graphBuilder защищенное свойство

protected IGraphBuilder graphBuilder
Результат IGraphBuilder

graphState защищенное свойство

protected GraphState graphState
Результат GraphState

isCaptureRendered защищенное свойство

protected bool isCaptureRendered
Результат bool

isPreviewRendered защищенное свойство

protected bool isPreviewRendered
Результат bool

mediaControl защищенное свойство

protected IMediaControl mediaControl
Результат IMediaControl

muxFilter защищенное свойство

protected IBaseFilter muxFilter
Результат IBaseFilter

previewCaps защищенное свойство

Property Backer: preview capabilities of video device
protected VideoCapabilities,DirectX.Capture previewCaps
Результат DirectX.Capture.VideoCapabilities

previewStreamConfig защищенное свойство

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
Результат IAMStreamConfig

previewWindow защищенное свойство

protected Control,System.Windows.Forms previewWindow
Результат System.Windows.Forms.Control

propertyPages защищенное свойство

protected PropertyPageCollection,DirectX.Capture propertyPages
Результат PropertyPageCollection

recFileMode защищенное свойство

Recording file mode (e.g. Windows Media Audio)
protected RecFileModeType recFileMode
Результат RecFileModeType

rotCookie защищенное свойство

Special variable for debugging purposes Cookie into the Running Object Table
protected DsROTEntry rotCookie
Результат DsROTEntry

rotCookie защищенное свойство

protected int rotCookie
Результат int

sampGrabber защищенное свойство

Sample Grabber interface
protected ISampleGrabber sampGrabber
Результат ISampleGrabber

tuner защищенное свойство

protected Tuner,DirectX.Capture tuner
Результат Tuner

tvAudio защищенное свойство

IAMTVAudio property
protected IAMTVAudio tvAudio
Результат IAMTVAudio

videoCaps защищенное свойство

protected VideoCapabilities,DirectX.Capture videoCaps
Результат DirectX.Capture.VideoCapabilities

videoCompressor защищенное свойство

protected Filter,DirectX.Capture videoCompressor
Результат Filter

videoCompressorFilter защищенное свойство

protected IBaseFilter videoCompressorFilter
Результат IBaseFilter

videoDevice защищенное свойство

protected Filter,DirectX.Capture videoDevice
Результат Filter

videoDeviceFilter защищенное свойство

protected IBaseFilter videoDeviceFilter
Результат IBaseFilter

videoSources защищенное свойство

protected SourceCollection,DirectX.Capture videoSources
Результат SourceCollection

videoStreamConfig защищенное свойство

protected IAMStreamConfig videoStreamConfig
Результат IAMStreamConfig

videoWindow защищенное свойство

protected IVideoWindow videoWindow
Результат IVideoWindow

wantCaptureRendered защищенное свойство

protected bool wantCaptureRendered
Результат bool

wantPreviewRendered защищенное свойство

protected bool wantPreviewRendered
Результат bool