-
Notifications
You must be signed in to change notification settings - Fork 2
/
directx_camera_server.cpp
executable file
·864 lines (754 loc) · 30.9 KB
/
directx_camera_server.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "directx_camera_server.h"
#include <vrpn_BaseClass.h>
// Libraries we need to link with to use what we're using.
#pragma comment(lib,"strmiids.lib")
//#define HACK_TO_REOPEN
//#define DEBUG
//-----------------------------------------------------------------------
// Helper functions for editing the filter graph:
static HRESULT GetPin(IBaseFilter *pFilter, PIN_DIRECTION PinDir, IPin **ppPin)
{
IEnumPins *pEnum;
IPin *pPin;
pFilter->EnumPins(&pEnum);
while(pEnum->Next(1, &pPin, 0) == S_OK)
{
PIN_DIRECTION PinDirThis;
pPin->QueryDirection(&PinDirThis);
if (PinDir == PinDirThis)
{
pEnum->Release();
*ppPin = pPin;
return S_OK;
}
pPin->Release();
}
pEnum->Release();
return E_FAIL;
}
static HRESULT ConnectTwoFilters(IGraphBuilder *pGraph, IBaseFilter *pFirst, IBaseFilter *pSecond)
{
IPin *pOut = NULL, *pIn = NULL;
HRESULT hr = GetPin(pFirst, PINDIR_OUTPUT, &pOut);
if (FAILED(hr)) return hr;
hr = GetPin(pSecond, PINDIR_INPUT, &pIn);
if (FAILED(hr))
{
pOut->Release();
return E_FAIL;
}
hr = pGraph->Connect(pOut, pIn);
pIn->Release();
pOut->Release();
return hr;
}
//-----------------------------------------------------------------------
/** The first time we are called, start the filter graph running in continuous
mode and grab the first image that comes out. Later times, grab each new
image as it comes. The "mode" parameter tells what mode we are in:
Mode 0 = Run()
Mode 1 = Pause()
*/
bool directx_camera_server::read_one_frame(unsigned minX, unsigned maxX,
unsigned minY, unsigned maxY,
unsigned exposure_millisecs)
{
HRESULT hr;
if (!_status) { return false; };
#ifdef HACK_TO_REOPEN
open_and_find_parameters();
_started_graph = false;
#endif
// If we have not yet started the media graph running, set up the callback
// handler for the sample grabber filter so that we will hear about each frame
// as it comes in. Then set the filter graph running.
if (!_started_graph) {
// Set the grabber do not do one-shot mode because that would cause
// it to stop the filter graph after a single frame is captured.
_pGrabber->SetOneShot(FALSE);
// Set the grabber to not do buffering mode, because we've not implemented
// the handler for buffered callbacks.
_pGrabber->SetBufferSamples(FALSE);
// Run the graph and wait until it captures a frame into its buffer
switch (_mode) {
case 0: // Case 0 = run
hr = _pMediaControl->Run();
break;
case 1: // Case 1 = paused
hr = _pMediaControl->Pause();
break;
default:
fprintf(stderr, "directx_camera_server::read_one_frame(): Unknown mode (%d)\n", _mode);
_status = false;
return false;
}
if ( (hr != S_OK) && (hr != S_FALSE) ){
fprintf(stderr,"directx_camera_server::read_one_frame(): Can't run filter graph\n");
_status = false;
return false;
}
_started_graph = true;
}
//XXX Should the app be allowed to set the timeout period?
const int TIMEOUT_MSECS = 500;
// Wait until there is a sample ready in the callback handler. If there is,
// copy it into our buffer and then tell it we are done processing the sample.
// If it takes too long, time out.
BYTE *imageLocation;
if (!_pCallback->imageReady) {
for (int i = 0; i < TIMEOUT_MSECS; i++) {
vrpn_SleepMsecs(1);
if (_pCallback->imageReady) { break; } // Break out of the wait if its ready
}
if (!_pCallback->imageReady) {
#ifdef DEBUG
fprintf(stderr,"directx_camera_server::read_one_frame(): Timeout when reading image\n");
#endif
return false;
}
}
// If we are in mode 2, then we pause the graph after we captured one image.
if (_mode == 2) {
_pMediaControl->Pause();
_mode = 1;
}
if (_pCallback->imageReady) {
_pCallback->imageReady = false;
if (FAILED(_pCallback->imageSample->GetPointer(&imageLocation))) {
fprintf(stderr,"directx_camera_server::read_one_frame(): Can't get buffer\n");
_status = false;
_pCallback->imageDone = true;
return false;
}
// Step through each line of the video and copy it into the buffer. We
// do one line at a time here because there can be padding at the end of
// each line on some video formats.
for (DWORD iRow = 0; iRow < _num_rows; iRow++) {
memcpy(_buffer+_num_columns*3*iRow, imageLocation+_stride*iRow, _num_columns*3);
}
_pCallback->imageDone = true;
}
#ifdef HACK_TO_REOPEN
close_device();
#endif
// Capture timing information and print out how many frames per second
// are being received.
#if 0
{ static struct timeval last_print_time;
struct timeval now;
static bool first_time = true;
static int frame_count = 0;
if (first_time) {
gettimeofday(&last_print_time, NULL);
first_time = false;
} else {
static unsigned last_r = 10000;
frame_count++;
gettimeofday(&now, NULL);
double timesecs = 0.001 * vrpn_TimevalMsecs(vrpn_TimevalDiff(now, last_print_time));
if (timesecs >= 5) {
double frames_per_sec = frame_count / timesecs;
frame_count = 0;
printf("Received frames per second = %lg\n", frames_per_sec);
last_print_time = now;
}
}
}
#endif
return true;
}
//---------------------------------------------------------------------
// Open the camera specified and determine its available features and parameters.
bool directx_camera_server::open_and_find_parameters(const int which, unsigned width, unsigned height)
{
HRESULT hr;
//-------------------------------------------------------------------
// Create COM and DirectX objects needed to access a video stream.
// Initialize COM. This must have a matching uninitialize somewhere before
// the object is destroyed.
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before CoInitialize\n");
#endif
CoInitialize(NULL);
// Create the filter graph manager
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before CoCreateInstance FilterGraph\n");
#endif
CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
IID_IGraphBuilder, (void **)&_pGraph);
if (_pGraph == NULL) {
fprintf(stderr, "directx_camera_server::open_and_find_parameters(): Can't create graph manager\n");
return false;
}
_pGraph->QueryInterface(IID_IMediaControl, (void **)&_pMediaControl);
_pGraph->QueryInterface(IID_IMediaEvent, (void **)&_pEvent);
// Create the Capture Graph Builder.
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before CoCreateInstance CaptureGraphBuilder2\n");
#endif
CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
IID_ICaptureGraphBuilder2, (void **)&_pBuilder);
if (_pBuilder == NULL) {
fprintf(stderr, "directx_camera_server::open_and_find_parameters(): Can't create graph builder\n");
return false;
}
// Associate the graph with the builder.
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before SetFilterGraph\n");
#endif
_pBuilder->SetFiltergraph(_pGraph);
//-------------------------------------------------------------------
// Go find a video device to use: in this case, we are using the first
// one we find.
// Create the system device enumerator.
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before CoCreateInstance SystemDeviceEnum\n");
#endif
ICreateDevEnum *pDevEnum = NULL;
CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
IID_ICreateDevEnum, (void **)&pDevEnum);
if (pDevEnum == NULL) {
fprintf(stderr, "directx_camera_server::open_and_find_parameters(): Can't create device enumerator\n");
return false;
}
// Create an enumerator for video capture devices.
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before CreateClassEnumerator\n");
#endif
IEnumMoniker *pClassEnum = NULL;
pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pClassEnum, 0);
if (pClassEnum == NULL) {
fprintf(stderr, "directx_camera_server::open_and_find_parameters(): Can't create video enumerator (no cameras?)\n");
pDevEnum->Release();
return false;
}
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before Loop over enumerators\n");
#endif
ULONG cFetched;
IMoniker *pMoniker = NULL;
IBaseFilter *pSrc = NULL;
// Skip (which - 1) cameras
int i;
for (i = 0; i < which-1 ; i++) {
if (pClassEnum->Next(1, &pMoniker, &cFetched) != S_OK) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't open camera (not enough cameras)\n");
pMoniker->Release();
return false;
}
}
// Take the next camera and bind it
if (pClassEnum->Next(1, &pMoniker, &cFetched) == S_OK) {
// Bind the first moniker to a filter object.
pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pSrc);
pMoniker->Release();
} else {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't open camera (not enough cameras)\n");
pMoniker->Release();
return false;
}
pClassEnum->Release();
pDevEnum->Release();
//-------------------------------------------------------------------
// Construct the sample grabber callback handler that will be used
// to receive image data from the sample grabber.
if ( (_pCallback = new directx_samplegrabber_callback()) == NULL) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't create sample grabber callback handler (out of memory?)\n");
return false;
}
//-------------------------------------------------------------------
// Construct the sample grabber that will be used to snatch images from
// the video stream as they go by. Set its media type and callback.
// Create the Sample Grabber.
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before CoCreateInstance SampleGrabber\n");
#endif
CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, reinterpret_cast<void**>(&_pSampleGrabberFilter));
if (_pSampleGrabberFilter == NULL) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't get SampleGrabber filter (not DirectX 8.1+?)\n");
return false;
}
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before QueryInterface\n");
#endif
_pSampleGrabberFilter->QueryInterface(IID_ISampleGrabber,
reinterpret_cast<void**>(&_pGrabber));
// Set the media type to video
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before SetMediaType\n");
#endif
AM_MEDIA_TYPE mt;
// Ask for video media producers that produce 8-bit RGB
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
mt.majortype = MEDIATYPE_Video; // Ask for video media producers
mt.subtype = MEDIASUBTYPE_RGB24; // Ask for 8 bit RGB
_pGrabber->SetMediaType(&mt);
//-------------------------------------------------------------------
// Ask for the video resolution that has been passed in.
// This code is based on
// intuiting that we need to use the SetFormat call on the IAMStreamConfig
// interface; this interface is described in the help pages.
// If the width and height are specified as 0, then they are not set
// in the header, letting them use whatever is the default.
if ( (width != 0) && (height != 0) ) {
_pBuilder->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, pSrc,
IID_IAMStreamConfig, (void **)&_pStreamConfig);
if (_pStreamConfig == NULL) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't get StreamConfig interface\n");
return false;
}
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
mt.majortype = MEDIATYPE_Video; // Ask for video media producers
mt.subtype = MEDIASUBTYPE_RGB24; // Ask for 8 bit RGB
mt.pbFormat = (BYTE*)CoTaskMemAlloc(sizeof(VIDEOINFOHEADER));
VIDEOINFOHEADER *pVideoHeader = (VIDEOINFOHEADER*)mt.pbFormat;
ZeroMemory(pVideoHeader, sizeof(VIDEOINFOHEADER));
pVideoHeader->bmiHeader.biBitCount = 24;
pVideoHeader->bmiHeader.biWidth = width;
pVideoHeader->bmiHeader.biHeight = height;
pVideoHeader->bmiHeader.biPlanes = 1;
pVideoHeader->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pVideoHeader->bmiHeader.biSizeImage = DIBSIZE(pVideoHeader->bmiHeader);
// Set the format type and size.
mt.formattype = FORMAT_VideoInfo;
mt.cbFormat = sizeof(VIDEOINFOHEADER);
// Set the sample size.
mt.bFixedSizeSamples = TRUE;
mt.lSampleSize = DIBSIZE(pVideoHeader->bmiHeader);
// Make the call to actually set the video type to what we want.
if (_pStreamConfig->SetFormat(&mt) != S_OK) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't set resolution to %dx%d using uncompressed 24-bit video\n",
pVideoHeader->bmiHeader.biWidth, pVideoHeader->bmiHeader.biHeight);
return false;
}
// Clean up the pbFormat header memory we allocated above.
CoTaskMemFree(mt.pbFormat);
}
//-------------------------------------------------------------------
// Create a NULL renderer that will be used to discard the video frames
// on the output pin of the sample grabber
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Before CoCreateInstance NullRenderer\n");
#endif
IBaseFilter *pNull = NULL;
CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, reinterpret_cast<void**>(&pNull));
//-------------------------------------------------------------------
// Build the filter graph. First add the filters and then connect them.
// pSrc is the capture filter for the video device we found above.
_pGraph->AddFilter(pSrc, L"Video Capture");
// Add the sample grabber filter
_pGraph->AddFilter(_pSampleGrabberFilter, L"SampleGrabber");
// Add the null renderer filter
_pGraph->AddFilter(pNull, L"NullRenderer");
// Connect the output of the video reader to the sample grabber input
ConnectTwoFilters(_pGraph, pSrc, _pSampleGrabberFilter);
// Connect the output of the sample grabber to the NULL renderer input
ConnectTwoFilters(_pGraph, _pSampleGrabberFilter, pNull);
//-------------------------------------------------------------------
// XXX See if this is a video tuner card by querying for that interface.
// Set it to read the video channel if it is one.
IAMTVTuner *pTuner = NULL;
hr = _pBuilder->FindInterface(NULL, NULL, pSrc, IID_IAMTVTuner, (void**)&pTuner);
if (pTuner != NULL) {
#ifdef DEBUG
printf("directx_camera_server::open_and_find_parameters(): Found a TV Tuner!\n");
#endif
//XXX Put code here.
// Set the first input pin to use the cable as input
hr = pTuner->put_InputType(0, TunerInputCable);
if (FAILED(hr)) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't set input to cable\n");
}
// Set the channel on the video to be baseband (is this channel zero?)
hr = pTuner->put_Channel(0, -1, -1);
if (FAILED(hr)) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't set channel\n");
}
pTuner->Release();
}
//-------------------------------------------------------------------
// Find _num_rows and _num_columns in the video stream.
_pGrabber->GetConnectedMediaType(&mt);
VIDEOINFOHEADER *pVih;
if (mt.formattype == FORMAT_VideoInfo) {
pVih = reinterpret_cast<VIDEOINFOHEADER*>(mt.pbFormat);
} else if (mt.formattype == FORMAT_VideoInfo2) {
pVih = reinterpret_cast<VIDEOINFOHEADER*>(mt.pbFormat);
} else {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Can't get video header type\n");
fprintf(stderr," (Expected %x or %x, got %x)\n", FORMAT_VideoInfo, FORMAT_VideoInfo2, mt.formattype);
fprintf(stderr," (GetConnectedMediaType is not valid for DirectX headers later than version 7)\n");
fprintf(stderr," (We need to re-implement reading video in some other interface)\n");
return false;
}
// Number of rows and columns. This is different if we are using a target
// rectangle (rcTarget) than if we are not.
if (IsRectEmpty(&pVih->rcTarget)) {
_num_columns = pVih->bmiHeader.biWidth;
_num_rows = pVih->bmiHeader.biHeight;
} else {
_num_columns = pVih->rcTarget.right;
_num_rows = pVih->bmiHeader.biHeight;
printf("XXX directx_camera_server::open_and_find_parameters(): Warning: may not work correctly with target rectangle\n");
}
#ifdef DEBUG
printf("Got %dx%d video\n", _num_columns, _num_rows);
#endif
// Make sure that the image is not compressed and that we have 8 bits
// per pixel.
if (pVih->bmiHeader.biCompression != BI_RGB) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Compression not RGB\n");
switch (pVih->bmiHeader.biCompression) {
case BI_RLE8:
fprintf(stderr," (It is BI_RLE8)\n");
break;
case BI_RLE4:
fprintf(stderr," (It is BI_RLE4)\n");
case BI_BITFIELDS:
fprintf(stderr," (It is BI_BITFIELDS)\n");
break;
default:
fprintf(stderr," (Unknown compression type)\n");
}
return false;
}
int BytesPerPixel = pVih->bmiHeader.biBitCount / 8;
if (BytesPerPixel != 3) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Not 3 bytes per pixel (%d)\n",
pVih->bmiHeader.biBitCount);
return false;
}
// A negative height indicates that the images are stored non-inverted in Y
// Not sure what to do with images that have negative height -- need to
// read the book some more to find out.
if (_num_rows < 0) {
fprintf(stderr,"directx_camera_server::open_and_find_parameters(): Num Rows is negative (internal error)\n");
return false;
}
// Find the stride to take when moving from one row of video to the
// next. This is rounded up to the nearest DWORD.
_stride = (_num_columns * BytesPerPixel + 3) & ~3;
// Set the callback, where '0' means 'use the SampleCB callback'
_pGrabber->SetCallback(_pCallback, 0);
//-------------------------------------------------------------------
// Release resources that won't be used later and return
pSrc->Release();
pNull->Release();
return true;
}
/// Construct but do not open a camera
directx_camera_server::directx_camera_server() :
_pGraph(NULL),
_pBuilder(NULL),
_pMediaControl(NULL),
_pEvent(NULL),
_pSampleGrabberFilter(NULL),
_pGrabber(NULL),
_pStreamConfig(NULL),
_pCallback(NULL),
_started_graph(false),
_mode(0),
_buffer(NULL)
{
// No image in memory yet.
_minX = _maxX = _minY = _maxY = 0;
}
/// Open nth available camera with specified resolution.
directx_camera_server::directx_camera_server(int which, unsigned width, unsigned height) :
_pGraph(NULL),
_pBuilder(NULL),
_pMediaControl(NULL),
_pEvent(NULL),
_pSampleGrabberFilter(NULL),
_pGrabber(NULL),
_pStreamConfig(NULL),
_pCallback(NULL),
_started_graph(false),
_mode(0),
_buffer(NULL)
{
//---------------------------------------------------------------------
if (!open_and_find_parameters(which, width, height)) {
fprintf(stderr, "directx_camera_server::directx_camera_server(): Cannot open camera\n");
_status = false;
return;
}
//---------------------------------------------------------------------
// Allocate a buffer that is large enough to read the maximum-sized
// image with no binning.
_buflen = (unsigned)(_num_rows * _num_columns * 3); // Expect B,G,R; 8-bits each.
if ( (_buffer = new unsigned char[_buflen]) == NULL) {
fprintf(stderr,"directx_camera_server::directx_camera_server(): Out of memory for buffer\n");
_status = false;
return;
}
// No image in memory yet.
_minX = _maxX = _minY = _maxY = 0;
#ifdef HACK_TO_REOPEN
close_device();
#endif
_status = true;
}
//---------------------------------------------------------------------
// Close the camera and the system. Free up memory.
void directx_camera_server::close_device(void)
{
// Clean up.
if (_pGrabber) { _pGrabber->Release(); };
if (_pSampleGrabberFilter) { _pSampleGrabberFilter->Release(); };
if (_pStreamConfig) { _pStreamConfig->Release(); };
if (_pEvent) { _pEvent->Release(); };
if (_pMediaControl) { _pMediaControl->Release(); };
if (_pBuilder) { _pBuilder->Release(); };
if (_pGraph) { _pGraph->Release(); };
CoUninitialize();
}
directx_camera_server::~directx_camera_server(void)
{
// Get the callback device to immediately return all samples
// it has queued up, then shut down the filter graph.
if (_pCallback) { _pCallback->shutdown(); }
close_device();
if (_buffer != NULL) { delete [] _buffer; }
// Delete the callback object, so that it can clean up and
// make sure all of its threads exit.
delete _pCallback;
}
bool directx_camera_server::read_image_to_memory(unsigned minX, unsigned maxX, unsigned minY, unsigned maxY,
double exposure_millisecs)
{
if (!_status) {
fprintf(stderr, "directx_camera_server::read_image_to_memory(): broken\n");
return false;
};
//---------------------------------------------------------------------
// In case we fail, clear these
_minX = _minY = _maxX = _maxY = 0;
//---------------------------------------------------------------------
// If the maxes are greater than the mins, set them to the size of
// the image.
if (maxX < minX) {
minX = 0; maxX = _num_columns - 1;
}
if (maxY < minY) {
minY = 0; maxY = _num_rows - 1;
}
//---------------------------------------------------------------------
// Clip collection range to the size of the sensor on the camera.
if (minX < 0) { minX = 0; };
if (minY < 0) { minY = 0; };
if (maxX >= _num_columns) { maxX = _num_columns - 1; };
if (maxY >= _num_rows) { maxY = _num_rows - 1; };
//---------------------------------------------------------------------
// Store image size for later use
_minX = minX; _minY = minY; _maxX = maxX; _maxY = maxY;
//---------------------------------------------------------------------
// Set up and read one frame, if we can.
if (!read_one_frame(_minX, _maxX, _minY, _maxY, (int)exposure_millisecs)) {
fprintf(stderr, "directx_camera_server::read_image_to_memory(): read_one_frame() failed\n");
return false;
}
return true;
}
bool directx_camera_server::write_memory_to_ppm_file(const char *filename, bool sixteen_bits) const
{
// XXX This will depend on what kind of pixels we have!
if (!_status) { return false; };
//---------------------------------------------------------------------
// Make sure the region is non-zero (so we've read an image)
if ( (_maxX <= _minX) || (_maxY <= _minY) ) {
fprintf(stderr,"directx_camera_server::write_memory_to_ppm_file(): No image in memory\n");
return false;
}
//---------------------------------------------------------------------
// If we've collected only a subset of the image, this version of the code
// won't work.
if ( (_minX != 0) || (_maxX != _num_columns-1) || (_minY != 0) || (_maxY != _num_rows-1) ) {
fprintf(stderr, "directx_camera_server::write_memory_to_ppm_file(): Can't write subset (not implemented)\n");
return false;
}
//---------------------------------------------------------------------
// Swap the red and blue values for each triplet in the buffer, since
// the DirectShow order is BGR and the PPM order is RGB.
unsigned char *bufrgb = new unsigned char[_buflen];
if (bufrgb == NULL) {
fprintf(stderr,"directx_camera_server::write_memory_to_ppm_file(): Out of memory\n");
return false;
}
unsigned X,Y;
unsigned cols = (_maxX - _minX) + 1;
for (Y = _minY; Y < _maxY; Y++) {
for (X = _minX; X < _maxX; X++) {
bufrgb[ (Y*cols + X) * 3 + 0 ] = _buffer[ (Y*cols + X) * 3 + 2 ];
bufrgb[ (Y*cols + X) * 3 + 1 ] = _buffer[ (Y*cols + X) * 3 + 1 ];
bufrgb[ (Y*cols + X) * 3 + 2 ] = _buffer[ (Y*cols + X) * 3 + 0 ];
}
}
//---------------------------------------------------------------------
// Write out an uncompressed RGB PPM file. We ignore the "16bits" request
// because we don't have 16 bits to put in there!
if (sixteen_bits) {
fprintf(stderr, "directx_camera_server::write_memory_to_ppm_file(): 16 bits requested, ignoring\n");
}
FILE *of = fopen(filename, "wb");
if (of == NULL) {
fprintf(stderr, "directx_camera_server::write_memory_to_ppm_file(): Can't open %s for write\n", filename);
return false;
}
if (fprintf(of, "P6\n%d %d\n%d\n", _num_columns, _num_rows, 255) < 0) {
fprintf(stderr, "directx_camera_server::write_memory_to_ppm_file(): Can't write header to %s\n", filename);
return false;
}
if (fwrite(bufrgb, 1, _buflen, of) != _buflen) {
fprintf(stderr, "directx_camera_server::write_memory_to_ppm_file(): Can't write data to %s\n", filename);
return false;
}
fclose(of);
delete [] bufrgb;
return true;
}
bool directx_camera_server::get_pixel_from_memory(unsigned X, unsigned Y, vrpn_uint8 &val, int RGB) const
{
if (!_status) { return false; };
// Switch red and blue, since they are backwards in the record (blue is first).
RGB = 2 - RGB;
// XXX This will depend on what kind of pixels we have!
if ( (_maxX <= _minX) || (_maxY <= _minY) ) {
fprintf(stderr,"directx_camera_server::get_pixel_from_memory(): No image in memory\n");
return false;
}
if ( (X < _minX) || (X > _maxX) || (Y < _minY) || (Y > _maxY) ) {
return false;
}
unsigned cols = _num_columns;
val = _buffer[ (Y*cols + X) * 3 + RGB ];
return true;
}
bool directx_camera_server::get_pixel_from_memory(unsigned X, unsigned Y, vrpn_uint16 &val, int RGB) const
{
if (!_status) { return false; };
// Switch red and blue, since they are backwards in the record (blue is first).
RGB = 2 - RGB;
// XXX This will depend on what kind of pixels we have!
if ( (_maxX <= _minX) || (_maxY <= _minY) ) {
fprintf(stderr,"directx_camera_server::get_pixel_from_memory(): No image in memory\n");
return false;
}
if ( (X < _minX) || (X > _maxX) || (Y < _minY) || (Y > _maxY) ) {
return false;
}
unsigned cols = _num_columns;
val = _buffer[ (Y*cols + X) * 3 + RGB ];
return true;
}
bool directx_camera_server::send_vrpn_image(vrpn_Imager_Server* svr,vrpn_Connection* svrcon,double g_exposure,int svrchan, int num_chans)
{
if (!_status) { return false; }
unsigned y;
// Send the current frame over to the client in chunks as big as possible (limited by vrpn_IMAGER_MAX_REGION).
int nRowsPerRegion=vrpn_IMAGER_MAX_REGIONu8/_num_columns;
svr->send_begin_frame(0, _num_columns-1, 0, _num_rows-1);
for(y=0; y<_num_rows; y+=nRowsPerRegion) {
svr->send_region_using_base_pointer(svrchan,0,_num_columns-1,y,__min(_num_rows,y+nRowsPerRegion)-1,
_buffer+2 /* Send the red channel */, 3, 3*_num_columns, _num_rows, true);
svr->mainloop();
}
if (num_chans >= 2) {
for(y=0; y<_num_rows; y+=nRowsPerRegion) {
svr->send_region_using_base_pointer(svrchan+1,0,_num_columns-1,y,__min(_num_rows,y+nRowsPerRegion)-1,
_buffer+1 /* Send the green channel */, 3, 3*_num_columns, _num_rows, true);
svr->mainloop();
}
}
if (num_chans >= 3) {
for(y=0; y<_num_rows; y+=nRowsPerRegion) {
svr->send_region_using_base_pointer(svrchan+2,0,_num_columns-1,y,__min(_num_rows,y+nRowsPerRegion)-1,
_buffer+0 /* Send the blue channel */, 3, 3*_num_columns, _num_rows, true);
svr->mainloop();
}
}
svr->send_end_frame(0, _num_columns-1, 0, _num_rows-1);
svr->mainloop();
// Mainloop the server connection (once per server mainloop, not once per object).
svrcon->mainloop();
return true;
}
// Write the texture, using a virtual method call appropriate to the particular
// camera type. NOTE: At least the first time this function is called,
// we must write a complete texture, which may be larger than the actual bytes
// allocated for the image. After the first time, and if we don't change the
// image size to be larger, we can use the subimage call to only write the
// pixels we have. Also note that we need to swap BGR format to RGB format.
bool directx_camera_server::write_to_opengl_texture(GLuint tex_id)
{
if (!_status) { return false; }
const GLint NUM_COMPONENTS = 3;
const GLenum FORMAT = GL_BGR_EXT;
const GLenum TYPE = GL_UNSIGNED_BYTE;
const void* BASE_BUFFER = _buffer;
const void* SUBSET_BUFFER = &_buffer[NUM_COMPONENTS * ( _minX + get_num_columns()*_minY )];
return write_to_opengl_texture_generic(tex_id, NUM_COMPONENTS, FORMAT, TYPE,
BASE_BUFFER, SUBSET_BUFFER, _minX, _minY, _maxX, _maxY);
}
//--------------------------------------------------------------------------------------------
// This section implements the callback handler that gets frames from the
// SampleGrabber filter.
directx_samplegrabber_callback::directx_samplegrabber_callback(void) :
imageReady(false),
imageDone(false),
imageSample(NULL),
_stayAlive(true)
{
}
directx_samplegrabber_callback::~directx_samplegrabber_callback(void)
{
// Make sure the other thread knows that it is okay to return the
// buffer and wait until it has had time to do so.
_stayAlive = false; Sleep(100);
};
HRESULT directx_samplegrabber_callback::QueryInterface(REFIID interfaceRequested, void **handleToInterfaceRequested)
{
if (handleToInterfaceRequested == NULL) { return E_POINTER; }
if (interfaceRequested == IID_IUnknown) {
*handleToInterfaceRequested = static_cast<IUnknown *>(this);
} else if (interfaceRequested == IID_ISampleGrabberCB) {
*handleToInterfaceRequested = static_cast<ISampleGrabberCB *>(this);
} else {
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
// This is the routine that processes each sample. It gets the information about
// the sample (one frame) from the SampleGrabber, then marks itself as being ready
// to process the sample. It then blocks until the sample has been processed by
// the associated camera server.
// The hand-off is handled by using two booleans acting as semaphores.
// The first semaphore (imageReady)
// controls access to the callback handler's buffer so that the application thread
// will only read it when it is full. The second sempaphore (imageDone) controls when
// the handler routine can release a sample; it makes sure that the sample is not
// released before the application thread is done processing it.
// The directx camera must be sure to free an open sample (if any) after changing
// the state of the filter graph, so that this doesn't block indefinitely. This means
// that the destructor for any object using this callback object has to destroy
// this object. The destructor sets _stayAlive to false to make sure this thread terminates.
HRESULT directx_samplegrabber_callback::SampleCB(double time, IMediaSample *sample)
{
// Point the image sample to the media sample we have and then set the flag
// to tell the application it can process it.
imageSample = sample;
imageReady = true;
// Wait until the image has been processed and then return the buffer to the
// filter graph
while (!imageDone && _stayAlive) { vrpn_SleepMsecs(1); }
if (_stayAlive) {
imageDone = false;
}
return S_OK;
}