private void RunWorker()
{
try
{
// Create the main graph
Graph = Activator.CreateInstance(Type.GetTypeFromCLSID(FilterGraph)) as IGraphBuilder;
// Create the webcam source
SourceObject = FilterInfo.CreateFilter(_monikerString);
// Create the grabber
Grabber = Activator.CreateInstance(Type.GetTypeFromCLSID(SampleGrabber)) as ISampleGrabber;
GrabberObject = Grabber as IBaseFilter;
// Add the source and grabber to the main graph
Graph.AddFilter(SourceObject, "source");
Graph.AddFilter(GrabberObject, "grabber");
using (AMMediaType mediaType = new AMMediaType())
{
mediaType.MajorType = MediaTypes.Video;
mediaType.SubType = MediaSubTypes.RGB32;
Grabber.SetMediaType(mediaType);
if (
Graph.Connect(SourceObject.GetPin(PinDirection.Output, 0),
GrabberObject.GetPin(PinDirection.Input, 0)) >= 0)
{
if (Grabber.GetConnectedMediaType(mediaType) == 0)
{
// During startup, this code can be too fast, so try at least 3 times
int retryCount = 0;
bool succeeded = false;
while ((retryCount < 3) && !succeeded)
{
// Tried again
retryCount++;
try
{
// Retrieve the grabber information
VideoInfoHeader header =
(VideoInfoHeader)
Marshal.PtrToStructure(mediaType.FormatPtr, typeof (VideoInfoHeader));
CapGrabber.Width = header.BmiHeader.Width;
CapGrabber.Height = header.BmiHeader.Height;
// Succeeded
succeeded = true;
}
catch (Exception)
{
// Trace
Trace.TraceInformation(
"Failed to retrieve the grabber information, tried {0} time(s)", retryCount);
// Sleep
Thread.Sleep(50);
}
}
}
}
Graph.Render(GrabberObject.GetPin(PinDirection.Output, 0));
Grabber.SetBufferSamples(false);
Grabber.SetOneShot(false);
Grabber.SetCallback(CapGrabber, 1);
// Get the video window
IVideoWindow wnd = (IVideoWindow) Graph;
wnd.put_AutoShow(false);
wnd = null;
// Create the control and run
Control = (IMediaControl) Graph;
Control.Run();
// Wait for the stop signal
while (!StopSignal.WaitOne(0, true))
{
Thread.Sleep(10);
}
// Stop when ready
Control.StopWhenReady();
}
}
catch (Exception ex)
{
// Trace
Trace.WriteLine(ex);
}
finally
{
// Clean up
Release();
}
}