/// <summary>
/// Worker thread that captures the images
/// </summary>
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 retryException)
{
// 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();
}
}