CSDN博客

img cpdp

DirectX.Capture

发表于2004/7/3 20:01:00  1264人阅读

分类: 视频技术

DirectX.Capture

Capabilities of the audio device such as min/max sampling rate and number of channels available. Minimum number of audio channels. Maximum number of audio channels. Granularity of the channels. For example, channels 2 through 4, in steps of 2. Minimum number of bits per sample. Maximum number of bits per sample. Granularity of the bits per sample. For example, 8 bits per sample through 32 bits per sample, in steps of 8. Minimum sample frequency. Maximum sample frequency. Granularity of the frequency. For example, 11025 Hz to 44100 Hz, in steps of 11025 Hz. Retrieve capabilities of an audio device Represents a physical connector or source on an audio device. This class is used on filters that support the IAMAudioInputMixer interface such as source cards. Represents a physical connector or source on an audio/video device. Obtains the String representation of this instance. Release unmanaged resources. Release unmanaged resources. The name of the source. Read-only. Is this source enabled. Constructor. This class cannot be created directly. Retrieve the friendly name of a connectorType. Release unmanaged resources. Enable or disable this source. For audio sources it is usually possible to enable several sources. When setting Enabled=true, set Enabled=false on all other audio sources. 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 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 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 and allow you to programmatically adjust the capture. Use and 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 and 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 collection to list video capture devices installed on the system.

foreach ( Filter f in Filters.VideoInputDevices ) { Debug.WriteLine( f.Name ); }

The class also provides collections for audio capture devices, video compressors and audio compressors.


Preview

Video preview is controled with the 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 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 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 and user it later to recreate the Filter object. To save a user's choices from a property page use . 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 property. If the device does not have a TV tuner, this property will be null. See , and 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 mportobello@hotmail.com. If the the topic may be of interest to others, post your question on the www.codeproject.com page for DirectX.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 class to list available devices. Destructor. Dispose of resources. 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. Begin capturing. Stop the current capture capture. If there is no current capture, this method will succeed. Calls Stop, releases all references. If a capture is in progress it will be stopped, but the CaptureComplete event will NOT fire. Create a new filter graph and add filters (devices, compressors, misc), but leave the filters unconnected. Call renderGraph() to connect the filters. 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. Setup and start the preview window if the user has requested it (by setting PreviewWindow). 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. 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. Completely tear down a filter graph and release all associated resources. Resize the preview when the PreviewWindow is resized Get a valid temporary filename (with path). We aren't using Path.GetTempFileName() because it creates a 0-byte file 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. 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. Assert that the class is in a Stopped state. Is the class currently capturing. Read-only. Has the class been cued to begin capturing. Read-only. Is the class currently stopped. Read-only. Name of file to capture to. Initially set to a valid temporary file. If the file does not exist, it will be created. If it does exist, it will be overwritten. An overwritten file will not be shortened if the captured data is smaller than the original file. The file will be valid, it will just contain extra, unused, data after the audio/video data. A future version of this class will provide a method to copy only the valid audio/video data to a new file. This property cannot be changed while capturing or cued. The control that will host the preview window. Setting this property will begin video preview immediately. Set this property after setting all other properties to avoid unnecessary changes to the internal filter graph (some properties like FrameSize require the internal filter graph to be stopped and disconnected before the property can be retrieved or set). To stop video preview, set this property to null. The capabilities of the video device. It may be required to cue the capture (see ) before all capabilities are correctly reported. If you have such a device, the developer would be interested to hear from you. The information contained in this property is retrieved and cached the first time this property is accessed. Future calls to this property use the cached results. This was done for performance. However, this means you may get different results depending on when you access this property first. If you are experiencing problems, try accessing the property immediately after creating the Capture class or immediately after setting the video and audio compressors. Also, inform the developer. The capabilities of the audio device. It may be required to cue the capture (see ) before all capabilities are correctly reported. If you have such a device, the developer would be interested to hear from you. The information contained in this property is retrieved and cached the first time this property is accessed. Future calls to this property use the cached results. This was done for performance. However, this means you may get different results depending on when you access this property first. If you are experiencing problems, try accessing the property immediately after creating the Capture class or immediately after setting the video and audio compressors. Also, inform the developer. The video capture device filter. Read-only. To use a different device, dispose of the current Capture instance and create a new instance with the desired device. The audio capture device filter. Read-only. To use a different device, dispose of the current Capture instance and create a new instance with the desired device. The video compression filter. When this property is changed the internal filter graph is rebuilt. This means that some properties will be reset. Set this property as early as possible to avoid losing changes. This property cannot be changed while capturing. The audio compression filter. When this property is changed the internal filter graph is rebuilt. This means that some properties will be reset. Set this property as early as possible to avoid losing changes. This property cannot be changed while capturing. The current video source. Use Capture.VideoSources to list available sources. Set to null to disable all sources (mute). The current audio source. Use Capture.AudioSources to list available sources. Set to null to disable all sources (mute). Collection of available video sources/physical connectors on the current video device. In most cases, if the device has only one source, this collection will be empty. The information contained in this property is retrieved and cached the first time this property is accessed. Future calls to this property use the cached results. This was done for performance. However, this means you may get different results depending on when you access this property first. If you are experiencing problems, try accessing the property immediately after creating the Capture class or immediately after setting the video and audio compressors. Also, inform the developer. Collection of available audio sources/physical connectors on the current audio device. In most cases, if the device has only one source, this collection will be empty. For audio there are 2 different methods for enumerating audio sources an audio crossbar (usually TV tuners?) or an audio mixer (usually sound cards?). This class will first look for an audio crossbar. If no sources or only one source is available on the crossbar, this class will then look for an audio mixer. This class does not support both methods. The information contained in this property is retrieved and cached the first time this property is accessed. Future calls to this property use the cached results. This was done for performance. However, this means you may get different results depending on when you access this property first. If you are experiencing problems, try accessing the property immediately after creating the Capture class or immediately after setting the video and audio compressors. Also, inform the developer. Available property pages. These are property pages exposed by the DirectShow filters. These property pages allow users modify settings on the filters directly. The information contained in this property is retrieved and cached the first time this property is accessed. Future calls to this property use the cached results. This was done for performance. However, this means you may get different results depending on when you access this property first. If you are experiencing problems, try accessing the property immediately after creating the Capture class or immediately after setting the video and audio compressors. Also, inform the developer. The TV Tuner or null if the current video device does not have a TV Tuner. Gets and sets the frame rate used to capture video. Common frame rates: 24 fps for film, 25 for PAL, 29.997 for NTSC. Not all NTSC capture cards can capture at exactly 29.997 fps. Not all frame rates are supported. When changing the frame rate, the closest supported frame rate will be used. Not all devices support getting/setting this property. If this property is not supported, accessing it will throw and exception. This property cannot be changed while capturing. Changing this property while preview is enabled will cause some fickering while the internal filter graph is partially rebuilt. Changing this property while cued will cancel the cue. Call Cue() again to re-cue the capture. Gets and sets the frame size used to capture video. To change the frame size, assign a new Size object to this property capture.Size = new Size( w, h ); rather than modifying the size in place (capture.Size.Width = w;). Not all frame rates are supported. Not all devices support getting/setting this property. If this property is not supported, accessing it will throw and exception. This property cannot be changed while capturing. Changing this property while preview is enabled will cause some fickering while the internal filter graph is partially rebuilt. Changing this property while cued will cancel the cue. Call Cue() again to re-cue the capture. Get or set the number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels. Not all devices support getting/setting this property. If this property is not supported, accessing it will throw and exception. This property cannot be changed while capturing. Changing this property while preview is enabled will cause some fickering while the internal filter graph is partially rebuilt. Changing this property while cued will cancel the cue. Call Cue() again to re-cue the capture. Get or set the number of audio samples taken per second. Common sampling rates are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. Not all sampling rates are supported. Not all devices support getting/setting this property. If this property is not supported, accessing it will throw and exception. This property cannot be changed while capturing. Changing this property while preview is enabled will cause some fickering while the internal filter graph is partially rebuilt. Changing this property while cued will cancel the cue. Call Cue() again to re-cue the capture. Get or set the number of bits recorded per sample. Common sample sizes are 8 bit and 16 bit. Not all samples sizes are supported. Not all devices support getting/setting this property. If this property is not supported, accessing it will throw and exception. This property cannot be changed while capturing. Changing this property while preview is enabled will cause some fickering while the internal filter graph is partially rebuilt. Changing this property while cued will cancel the cue. Call Cue() again to re-cue the capture. Fired when a capture is completed (manually or automatically). Possible states of the interal filter graph Represents a physical connector or source on an audio/video device. This class is used on filters that support the IAMCrossbar interface such as TV Tuners. Constructor. This class cannot be created directly. Retrieve the friendly name of a connectorType. Release unmanaged resources. Enabled or disable this source. Exception thrown when the device cannot be rendered or started. Property pages for a DirectShow filter (e.g. hardware device). These property pages do not support persisting their settings. A base class for representing property pages exposed by filters. Name of property page. This name may not be unique Does this property page support saving and loading the user's choices. Constructor Show the property page. Some property pages cannot be displayed while previewing and/or capturing. This method will block until the property page is closed by the user. Release unmanaged resources Get or set the state of the property page. This is used to save and restore the user's choices without redisplaying the property page. After showing this property page, read and store the value of this property. At a later time, the user's choices can be reloaded by setting this property with the value stored earlier. Note that some property pages, after setting this property, will not reflect the new state. However, the filter will use the new settings. When reading this property, copy the entire array at once then manipulate your local copy (e..g byte[] myState = propertyPage.State). When setting this property set the entire array at once (e.g. propertyPage = myState). Not all property pages support saving/loading state. Check the property to determine if this property page supports it. COM ISpecifyPropertyPages interface Constructor Show the property page. Some property pages cannot be displayed while previewing and/or capturing. Release unmanaged resources Represents a DirectShow filter (e.g. video capture device, compression codec). To save a chosen filer for later recall save the MonikerString property on the filter:

string savedMonikerString = myFilter.MonikerString;
To recall the filter create a new Filter class and pass the string to the constructor:
Filter mySelectedFilter = new Filter( savedMonikerString );
Human-readable name of the filter Unique string referencing this filter. This string can be used to recreate this filter. Create a new filter from its moniker string. Create a new filter from its moniker Retrieve the a moniker's display name (i.e. it's unique string) Retrieve the human-readable name of the filter Get a moniker's human-readable name based on a moniker string. This method gets a UCOMIMoniker object. HACK: The only way to create a UCOMIMoniker from a moniker string is to use UCOMIMoniker.ParseDisplayName(). So I need ANY UCOMIMoniker object so that I can call ParseDisplayName(). Does anyone have a better solution? This assumes there is at least one video compressor filter installed on the system. Compares the current instance with another object of the same type. A collection of Filter objects (DirectShow filters). This is used by the class to provide lists of capture devices and compression filters. This class cannot be created directly. Populate the collection with a list of filters from a particular category. Populate the InnerList with a list of filters from a particular category Get the filter at the specified index. Provides collections of devices and compression codecs installed on the system. Devices and compression codecs are implemented in DirectShow as filters, see the class for more information. To list the available video devices:
Filters filters = new Filters(); foreach ( Filter f in filters.VideoInputDevices ) { Debug.WriteLine( f.Name ); }
Collection of available video capture devices. Collection of available audio capture devices. Collection of available video compressors. Collection of available audio compressors. A collection of available PropertyPages in a DirectShow filter graph. It is up to the driver manufacturer to implement a property pages on their drivers. The list of supported property pages will vary from driver to driver. Initialize collection with no property pages. Initialize collection with property pages from existing graph. Destructor. Release unmanaged resources. Empty the collection. Release unmanaged resources Populate the collection by looking for commonly implemented property pages. Returns the object as an ISpecificPropertyPage if the object supports the ISpecificPropertyPage interface and has at least one property page. Get the filter at the specified index. A collection of sources (or physical connectors) on an audio or video device. This is used by the class to provide a list of available sources on the currently selected audio and video devices. This class cannot be created directly. This class assumes there is only 1 video and 1 audio crossbar and all input pins route to a single output pin on each crossbar. Initialize collection with no sources. Initialize collection with sources from graph. Destructor. Release unmanaged resources. Empty the collection. Release unmanaged resources. Populate the collection from a filter graph. Retrieve a list of crossbar filters in the graph. Most hardware devices should have a maximum of 2 crossbars, one for video and another for audio. Populate the internal InnerList with sources/physical connectors found on the crossbars. Each instance of this class is limited to video only or audio only sources ( specified by the isVideoDevice parameter on the constructor) so we check each source before adding it to the list. Get the source at the specified index. Gets or sets the source/physical connector currently in use. This is marked internal so that the Capture class can control how and when the source is changed. Specify the frequency of the TV tuner. Cable frequency Antenna frequency Control and query a hardware TV Tuner. Initialize this object with a DirectShow tuner Get or set the TV Tuner channel. Get or set the tuner frequency (cable or antenna). Indicates whether a signal is present on the current channel. If the signal strength cannot be determined, a NotSupportedException is thrown. The property page to configure a Video for Windows compliant compression codec. Most compressors support this property page rather than a DirectShow property page. Also, most compressors do not support the IAMVideoCompression interface so this property page is the only method to configure a compressor. Video for Windows compression dialog interface Constructor Show the property page. Some property pages cannot be displayed while previewing and/or capturing. Get or set the state of the property page. This is used to save and restore the user's choices without redisplaying the property page. This property will be null if unable to retrieve the property page's state. After showing this property page, read and store the value of this property. At a later time, the user's choices can be reloaded by setting this property with the value stored earlier. Note that some property pages, after setting this property, will not reflect the new state. However, the filter will use the new settings. Capabilities of the video device such as min/max frame size and frame rate. Native size of the incoming video signal. This is the largest signal the filter can digitize with every pixel remaining unique. Read-only. Minimum supported frame size. Read-only. Maximum supported frame size. Read-only. Granularity of the output width. This value specifies the increments that are valid between MinFrameSize and MaxFrameSize. Read-only. Granularity of the output height. This value specifies the increments that are valid between MinFrameSize and MaxFrameSize. Read-only. Minimum supported frame rate. Read-only. Maximum supported frame rate. Read-only. Retrieve capabilities of a video device
0 0

相关博文

我的热门文章

img
取 消
img