Use DirectShow in Windows Mobile 5 to control camera-Rotation

Source: Internet
Author: User

By Amit Ranjan
July 21,200 6

A number of windows mobile 5.0 APIs (for example, shcameracapture) Make it trivial for a mobile application developer to access a camera, but their versions of use comes at a price-flexibility. most of the time, using the API directly wocould offer a solution, but sometimes you need more control and flexibility. that's where Microsoft's DirectShow framework comes in. this article shows how to use DirectShow to access a camera. it demonstrates how to build a filter graph manually and how to handle graph events in the application message handler. having some prior knowledge of DirectShow and com will be helpful, but it's not necessary.

Figure 1Depicts the components in the filter graph you will use to capture video.

Figure 1:Filter graph for Video Capture

The camera is the hardware component. for an application to interact with the camera, it wowould need To talk to its drivers. next, the video capture filter enables an application to capture video. after capture, you encode the data using wmv9encmediaobject, A DirectX Media object (DMO ). you can use a DMO inside a filter graph with the help of a DMO wrapper filter. next, the encoded video data needs to be multiplexed. you use a Windows Media ASF writer filter for this task. the ASF writer multiplexes the video data and writes it to. ASF file. with that, your filter graph is ready. now, it's just a matter of running it. as you will see, building the graph is pretty easy too.

Set the Build Environment

First, you need to set the Build Environment. Add the following libraries in the linker setting of a Visual Studio 2005 smart device project:

    • Dmoguids. Lib
    • Strmiids. Lib
    • Strmbase. Lib
    • UUID. Lib

Also include the following header files in your project:

    • Atlbase. h
    • Dmodshow. h
    • Dmoreg. h
    • Wmcodecids. h

 

Note:For the sake of clarity, this example doesn't show error handling. However, a real world application wowould require error handling.

Building the Graph

A filter graph that performs audio or video capture is known as a capture graph. directShow provides a capture graph builder object that exposes an interface called icapturegraphbuilder2; it exposes methods to help build and control a capture graph.

First, create instances of igraphbuilder and icapturegraphbuilder2 by using the com function cocreateinstance:

Hresult = s_ OK;

Igraphbuilder * pfiltergraph;

Icapturegraphbuilder2 * pcapturegraphbuilder;

Hresult = cocreateinstance (clsid_filtergraph, null, clsctx_inproc,

Iid_igraphbuilder, (void **) & pfiltergraph );

Hresult = cocreateinstance (clsid_capturegraphbuilder, null,

Clsctx_inproc, iid_icapturegraphbuilder2,

(Void **) & pcapturegraphbuilder );

Cocreateinstance takes five parameters:

    1. The first is a class ID.
    2. The second decides whether the object created is part of an aggregator.
    3. The third specifies the context in which the newly created object wocould run.
    4. The fourth parameter is a reference to the identifier of the interface you will use to communicate with the object.
    5. The last parameter is the address of the variable that matches es the interface pointer requested.

Once you have created the igraphbuilder and icapturegraphbulder2 instances, you need to call the setfiltergraph method of the icapturegraphbuilder2 interface:

Hresult = m_pcapturegraphbuilder-> setfiltergraph (pfiltergraph );

The setfiltergraph method takes a pointer to the igraphbuilder interface. this specifies which filter graph the capture graph builder will use. if you don't call the setfiltergraph method, the capture graph Builder automatically creates a graph when it needs it.

Now, you're ready to create an instance of the video capture filter. The following code initializes a video capture filter, the pointer of which is returned by the cocreateinstance:

Ibasefilter * pvideocapturefilter;

Hresult = cocreateinstance (clsid_videocapture, null, clsctx_inproc,

Iid_ibasefilter, (void **) & pvideocapturefilter );

You then need to get a pointer to ipersistpropertybag from the video capture filter. you use this pointer to set the capture device (in other words, the camera) that the capture filter will use, as follows:

Ipersistpropertybag * ppropertybag;

Hresult = pvideocapturefilter-> QueryInterface (& ppropertybag );

Now, you need to get a handle on the camera you will use to capture video. you can enumerate the available camera devices by using the findfirstdevice and findnextdevice functions. you can have multiple cameras present on a device. (HTC universal is one example .) to keep the code simple for this example, use findfirstdevice to get the first available camera on the device as follows:

Devmgr_device_information DevInfo;

Ccomvariant camname;

Cpropertybag propbag;

Guid guidcamera = {0xcb998a05, 0x122c, 0x4166, 0x84, 0x6a, 0x93,

0x3e, 0x4d, 0x7e, 0x3c, 0x86 };

DevInfo. dwsize = sizeof (DevInfo );

Findfirstdevice (devicesearchbyguid, & guidcamera, & DevInfo );

Camname = Devinfo. szlegacyname

Propbag. Write (_ T ("vcapname"), & camname );

Ppropertybag-> load (& propbag, null );

Hresult = pfiltergraph-> addfilter (pvideocapturefilter,

_ T ("video capture filter "));

Ppropertybag. Release ();

Note the first parameter in the findfirstdevice, devicesearchbyguid. it specifies the search type. other options are devicesearchbylegacyname, devicesearchbydevicename, and so forth. devicesearchbyguid is the most reliable way to find a capture device. the information regarding the device is returned in the devmgr_device_information structure. you store the szlegacyname value in the ccomvariant variable, and you need an object that has implemented ipropertybag interface.

In the code sample, cpropertybag is a custom class that has implemented ipropertybag. this object is needed to pass the capture device name to the filter. the string vcapname identifies the filter property for the name of the video capture device. once you have set the capture device, you can add the video capture filter to the filter graph. you use the addfilter method of the graph manager for this. this method takes two parameters: the first is the pointer to the filter that is to be added, and the second is the name of the filter. the second parameter can be null; in this case, the filter graph manager generates a unique name for the filter. if you have provided a name that conflicts with some other filter, the Manager will modify the name to make it unique.

You then need to instantiate the wmv9 Encoder:

Ibasefilter * pvideoencoder;

Idmowrapperfilter * pwrapperfilter;

Hresult = cocreateinstance (clsid_dmowrapperfilter, null, clsctx_inproc,

Iid_ibasefilter, (void **) & pvideoencoder );

Hresult = pvideoencoder-> QueryInterface (& pwrapperfilter );

Hresult = pwrapperfilter-> Init (clsid_cwmv9encmediaobject,

Dmocategory_video_encoder );

Hresult = pfiltergraph-> addfilter (pvideoencoder, l "wmv9dmo encoder ");

Because the wmv9 encoder is a DMO, You can't add/use it like other filters. but DirectShow provides a wrapper filter that enables you want to use a DMO like any other filter. you first create an instance of the DMO wrapper filter and then initialize the wmv9 encoder DMO with it. after initializing the DMO, you add it into the filter graph as follows:

Ibasefilter * pasfmultiplexer;

Ifilesinkfilter * pfilesinkfilter;

Hresult = pcapturegraphbuilder-> setoutputfilename (& mediasubtype_asf, T ("\ test. ASF"), & pasfmultiplexer, & pfilesinkfilter );

You have added the source and the transform filter in the filter graph, so the last thing remaining is adding a sink filter in the graph. for this, you call the setoutputfilename method of icapturegraphbuilder2. the first parameter is a media subtype; the second parameter is the name of the file in which you want to save the video; the third parameter is the address of a pointer that matches es the multiplexer's interface; and the fourth parameter parameters es the file writers 'interface.

With that, your filter graph is ready. all you need to do is connect the source filter, encoder, and multiplexer. you can achieve this by using the renderstream method of the graph builder, as follows:

Hresult = pcapturegraphbuilder-> renderstream (& pin_category_capture,

& Mediatype_video,

M_pvideocapturefilter,

Pvideoencoder,

Pasfmultiplexer );

 

The first parameter is the pin category, which can be null to match any category. the second parameter specifies the media type. the third, fourth, and th Parameters specify a starting filter, an intermediate filter, and a sink filter, respectively. the method connects the source filter to the transform filter and then the transform filter to the sink filter.

Now your graph is ready, and you can start capturing the video.

Controlling the Graph

before capturing video, you need two more things: the imediaeventex and imediacontrol pointers. imediaeventex derives from imediaevent, which supports event notification from the filter graph and individual filters to the application. imediaeventex provides a method to the Register window that contains es a message when any event occurs.

Imediacontrol is an interface exposed by the filter graph that allows an application to control the streaming media through the graph. the application can use this to start, stop, or pause the running graph. the following code sample first queries the filter graph for its imediaeventex interface. once it gets the pointer to the imediaeventex interface, it then callits method setpolicywindow, passing it the handle to the window that handles the message. the second parameter is the message that will be passed as notification to the Windows message handler. the third parameter is the instance data (this can be 0 ):

Imediaeventex * pmediaevent;

Imediacontrol * pmediacontrol;

# Define wm_graphnotify wm_app + 1

Hresult = pfiltergraph-> QueryInterface (iid_imediaeventex, (void **) & pmediaevent );

Hresult = pmediaevent-> setpolicywindow (oahwnd) hwnd, wm_graphnotify, 0 );

Hresult = pfiltergraph-> QueryInterface (& pmediacontrol );

Hresult = pmediacontrol-> Run ();

When an event occurs, DirectShow will send wm_graphnotify to the specified Windows.

Note:Wm_graphpolicy is used here as an example. This can be any application-defined message.

Next, you get the pointer to the imediacontrol interface. you'll use this interface to control the graph. call its run method to put the entire graph into a running state. the following code shows how to start and stop capture by throwing

Controlstream method of capturegraphbuilder:

Longlong dwstart = 0, dwend = 0;

Word wstartcookie = 1, wendcookie = 2;

Dwend = maxlonglong;

 

// Start capturing

Hresult = pcapturegraphbuilder-> controlstream (& pin_category_capture, & mediatype_video, pvideocapturefilter, & dwstart, & dwend, wstartcookie, wendcookie );

 

// Stop capturing

Dwstart = 0;

Hresult = pfiltergraph-> QueryInterface (& pmediaseeking );

Hresult = pmediaseeking-> getcurrentposition (& dwend );

Hresult = pcapturegraphbuilder-> controlstream (

& Pin_category_capture, & mediatype_video, pvideocapturefilter,

& Dwstart, & dwend, wstartcookie, wendcookie );

The Code uses the search criteria supplied in the method call to locate an output pin on the capture filter. controlstream enables an application to control streams without it needing to enumerate filters and pins in the graph. start and end specify the start and stop times (max_longlong is the largest possible reference time value ). when you start, the end is set to maxlonlong. when you want to stop, you first get the current position of the stream by using the getcurrentposition method of the imediaseeking interface. you then call the controlstream method with start set at 0 and end set at the current position. you now have the graph ready and running. you can start using it to capture and save in. ASF file.

Handling the graph events

Because an application will control the graph, you need to write the code to facilitate that. you already have registered the window and message with the filter graph, so the only thing remaining is to handle the message in the window's message handler as follows:

Bool callback vidcapdlgproc (hwnd hdlg, uint MSG, wparam, lparam)

{

............

Case wm_graphpolicy:

{

Processgraphmessage ();

}

............

}

Processgraphmessage ()

{

Hresult = s_ OK;

Long leventcode, param1, param2;

While (hresult = pevent-> getevent (& leventcode, & param1, & param2, 0 ),

Succeeded (hresult ))

{

Hresult = pevent-> freeeventparams (leventcode, param1, param2 );

If (ec_stream_control_stopped = leventcode)

{

Pmediacontrol-> stop ();

 Break;

}

Else if (ec_cap_file_completed = leventcode)

{

// Handle the file capture completed event

}

Else if (ec_cap_file_write_error = leventcode)

{

// Handle the file write error event

}

}

}

You handle the wm_graphpolicy message in the Windows handler. directShow sends this message to the application when any event arises. the application calla user-defined method to process the events. the getevent method of the imediaevent interface retrieves the Event code and two event parameters from the queue. because the message loop and Event Notification are asynchronous, the queue might hold More then one event. hence, the getevent code is called in a loop until it returns a failure code. also, whenever you call getevent, it's important to call freeevent to free the resource associated with the event parameter. and, being the good programmer that you are, you won't forget to release the resources afterwards, will you? Call release on every object that you have created, as follows:

Pvideocapturefilter-> release ();

Pvideoencoder-> release ();

Pmediaevent-> release ();

Pmediaseeking-> release ();

Pasfmultiplexer-> release ();

Pfilesinkfilter-> release ();

Pwrapperfilter-> release ();

Pfiltergraph-> release ();

Pcapturegraphbuilder-> release ();

 

What have you learned?

You now understand how to create, run, and control a filter graph manually. By using the DirectShow framework to capture from a camera, you gain good control with limits.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.