summaryrefslogtreecommitdiffstats
path: root/src/plugins/directshow/camera/dscamerasession.cpp
blob: f921dac209a64db00dbf236cc4c021dcd32e843c (plain)
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/qdebug.h>
#include <QWidget>
#include <QFile>
#include <QtMultimedia/qabstractvideobuffer.h>
#include <QtMultimedia/qvideosurfaceformat.h>

#include "dscamerasession.h"
#include "dsvideorenderer.h"
#include "directshowglobal.h"

QT_BEGIN_NAMESPACE

// If frames come in quicker than we display them, we allow the queue to build
// up to this number before we start dropping them.
const int LIMIT_FRAME = 5;

namespace {
// DirectShow helper implementation
void _FreeMediaType(AM_MEDIA_TYPE& mt)
{
    if (mt.cbFormat != 0) {
        CoTaskMemFree((PVOID)mt.pbFormat);
        mt.cbFormat = 0;
        mt.pbFormat = NULL;
    }
    if (mt.pUnk != NULL) {
        // pUnk should not be used.
        mt.pUnk->Release();
        mt.pUnk = NULL;
    }
}

} // end namespace

class SampleGrabberCallbackPrivate : public ISampleGrabberCB
{
public:
    STDMETHODIMP_(ULONG) AddRef() { return 1; }
    STDMETHODIMP_(ULONG) Release() { return 2; }

    STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject)
    {
        if (NULL == ppvObject) 
            return E_POINTER;
        if (riid == IID_IUnknown /*__uuidof(IUnknown) */ ) {
            *ppvObject = static_cast<IUnknown*>(this);
            return S_OK;
        }
        if (riid == IID_ISampleGrabberCB /*__uuidof(ISampleGrabberCB)*/ ) {
            *ppvObject = static_cast<ISampleGrabberCB*>(this);
            return S_OK;
        }
        return E_NOTIMPL;
    }

    STDMETHODIMP SampleCB(double Time, IMediaSample *pSample)
    {
        Q_UNUSED(Time)
        Q_UNUSED(pSample)
        return E_NOTIMPL;
    }

    STDMETHODIMP BufferCB(double Time, BYTE *pBuffer, long BufferLen)
    {
        if (!cs || active) {
            return S_OK;
        }

        if ((cs->StillMediaType.majortype != MEDIATYPE_Video) ||
                (cs->StillMediaType.formattype != FORMAT_VideoInfo) ||
                (cs->StillMediaType.cbFormat < sizeof(VIDEOINFOHEADER))) {
            return VFW_E_INVALIDMEDIATYPE;
        }

        active = true;

        if(toggle == true) {
            toggle = false;
        }
        else {
            toggle = true;
        }

        if(toggle) {
            active = false;
            return S_OK;
        }

        bool check = false;
        cs->mutex.lock();

        if (cs->frames.size() > LIMIT_FRAME) {
            check = true;
        }

        if (check) {
            cs->mutex.unlock();
            // Frames building up. We're going to drop some here
            Sleep(100);
            active = false;
            return S_OK;
        }
        cs->mutex.unlock();

        unsigned char* vidData = new unsigned char[BufferLen];
        memcpy(vidData, pBuffer, BufferLen);

        cs->mutex.lock();

        video_buffer* buf = new video_buffer;
        buf->buffer = vidData;
        buf->length = BufferLen;
        buf->time   = (qint64)Time;

        cs->frames.append(buf);

        cs->mutex.unlock();

        QMetaObject::invokeMethod(cs, "captureFrame", Qt::QueuedConnection);

        active = false;

        return S_OK;
    }

    DSCameraSession* cs;
    bool active;
    bool toggle;
};


DSCameraSession::DSCameraSession(QObject *parent)
    : QObject(parent)
      ,m_currentImageId(0)
{
    pBuild = NULL;
    pGraph = NULL;
    pCap = NULL;
    pSG_Filter = NULL;
    pSG = NULL;

    opened = false;
    available = false;
    resolutions.clear();
    m_state = QCamera::UnloadedState;
    m_device = "default";

    StillCapCB = new SampleGrabberCallbackPrivate;
    StillCapCB->cs = this;
    StillCapCB->active = false;
    StillCapCB->toggle = false;

    m_output = 0;
    m_surface = 0;
    pixelF = QVideoFrame::Format_Invalid;

    graph = false;
    active = false;

    ::CoInitialize(NULL);
}

DSCameraSession::~DSCameraSession()
{
    if (opened) {
        closeStream();
    }

    CoUninitialize();

    SAFE_RELEASE(pCap);
    SAFE_RELEASE(pSG_Filter);
    SAFE_RELEASE(pGraph);
    SAFE_RELEASE(pBuild);

    if (StillCapCB) {
        delete StillCapCB;
    }
}

int DSCameraSession::captureImage(const QString &fileName)
{
    emit readyForCaptureChanged(false);

    // We're going to do this in one big synchronous call
    m_currentImageId++;
    if (fileName.isEmpty()) {
        m_snapshot = "img.jpg";
    } else {
        m_snapshot = fileName;
    }

    if (!active) {
        startStream();
    }

    return m_currentImageId;
}

void DSCameraSession::setSurface(QAbstractVideoSurface* surface)
{
    m_surface = surface;
}

bool DSCameraSession::deviceReady()
{
    return available;
}

bool DSCameraSession::pictureInProgress()
{
    return m_snapshot.isEmpty();
}

int DSCameraSession::framerate() const
{
    return -1;
}

void DSCameraSession::setFrameRate(int rate)
{
    Q_UNUSED(rate)
}

int DSCameraSession::brightness() const
{
    return -1;
}

void DSCameraSession::setBrightness(int b)
{
    Q_UNUSED(b)
}

int DSCameraSession::contrast() const
{
    return -1;
}

void DSCameraSession::setContrast(int c)
{
    Q_UNUSED(c)
}

int DSCameraSession::saturation() const
{
    return -1;
}

void DSCameraSession::setSaturation(int s)
{
    Q_UNUSED(s)
}

int DSCameraSession::hue() const
{
    return -1;
}

void DSCameraSession::setHue(int h)
{
    Q_UNUSED(h)
}

int DSCameraSession::sharpness() const
{
    return -1;
}

void DSCameraSession::setSharpness(int s)
{
    Q_UNUSED(s)
}

int DSCameraSession::zoom() const
{
    return -1;
}

void DSCameraSession::setZoom(int z)
{
    Q_UNUSED(z)
}

bool DSCameraSession::backlightCompensation() const
{
    return false;
}

void DSCameraSession::setBacklightCompensation(bool b)
{
    Q_UNUSED(b)
}

int DSCameraSession::whitelevel() const
{
    return -1;
}

void DSCameraSession::setWhitelevel(int w)
{
    Q_UNUSED(w)
}

int DSCameraSession::rotation() const
{
    return 0;
}

void DSCameraSession::setRotation(int r)
{
    Q_UNUSED(r)
}

bool DSCameraSession::flash() const
{
    return false;
}

void DSCameraSession::setFlash(bool f)
{
    Q_UNUSED(f)
}

bool DSCameraSession::autofocus() const
{
    return false;
}

void DSCameraSession::setAutofocus(bool f)
{
    Q_UNUSED(f)
}

QSize DSCameraSession::frameSize() const
{
    return m_windowSize;
}

void DSCameraSession::setFrameSize(const QSize& s)
{
	if (supportedResolutions(pixelF).contains(s)) 
        m_windowSize = s;
    else 
        qWarning() << "frame size if not supported for current pixel format, no change";
}

void DSCameraSession::setDevice(const QString &device)
{
    if(opened)
        stopStream();

    if(graph) {
        SAFE_RELEASE(pCap);
        SAFE_RELEASE(pSG_Filter);
        SAFE_RELEASE(pGraph);
        SAFE_RELEASE(pBuild);
    }

    available = false;
    m_state = QCamera::LoadedState;

    CoInitialize(NULL);

    ICreateDevEnum* pDevEnum = NULL;
    IEnumMoniker* pEnum = NULL;

    // Create the System device enumerator
    HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
                                  CLSCTX_INPROC_SERVER, IID_ICreateDevEnum,
                                  reinterpret_cast<void**>(&pDevEnum));
    if(SUCCEEDED(hr)) {
        // Create the enumerator for the video capture category
        hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnum, 0);
        if (S_OK == hr) {
            pEnum->Reset();
            // go through and find all video capture devices
            IMoniker* pMoniker = NULL;
            IMalloc *mallocInterface = 0;
            CoGetMalloc(1, (LPMALLOC*)&mallocInterface);
            while(pEnum->Next(1, &pMoniker, NULL) == S_OK) {

                BSTR strName = 0;
                hr = pMoniker->GetDisplayName(NULL, NULL, &strName);
                if (SUCCEEDED(hr)) {
                    QString temp(QString::fromWCharArray(strName));
                    mallocInterface->Free(strName);
                    if(temp.contains(device)) {
                        available = true;
                    }
                }

                pMoniker->Release();
            }
            mallocInterface->Release();
            pEnum->Release();
        }
        pDevEnum->Release();
    }
    CoUninitialize();

    if(available) {
        m_device = QByteArray(device.toUtf8().constData());
        graph = createFilterGraph();
        if(!graph)
            available = false;
    }
}

QList<QVideoFrame::PixelFormat> DSCameraSession::supportedPixelFormats()
{
    return types;
}

QVideoFrame::PixelFormat DSCameraSession::pixelFormat() const
{
    return pixelF;
}

void DSCameraSession::setPixelFormat(QVideoFrame::PixelFormat fmt)
{
    pixelF = fmt;
}

QList<QSize> DSCameraSession::supportedResolutions(QVideoFrame::PixelFormat format)
{
    if (!resolutions.contains(format)) 
		return QList<QSize>();
    return resolutions.value(format);
}

bool DSCameraSession::setOutputLocation(const QUrl &sink)
{
    m_sink = sink;

    return true;
}

QUrl DSCameraSession::outputLocation() const
{
    return m_sink;
}

qint64 DSCameraSession::position() const
{
    return timeStamp.elapsed();
}

int DSCameraSession::state() const
{
    return int(m_state);
}

void DSCameraSession::record()
{
    if(opened) {
        return;
    }

    if(m_surface) {

        if (!graph)
            graph = createFilterGraph();

        if (types.isEmpty()) {
            if (pixelF == QVideoFrame::Format_Invalid)
                pixelF = QVideoFrame::Format_RGB32;
            if (!m_windowSize.isValid())
                m_windowSize = QSize(320, 240);
        }
        actualFormat = QVideoSurfaceFormat(m_windowSize, pixelF);

        if (!m_surface->isFormatSupported(actualFormat) && !types.isEmpty()) {
            // enumerate through camera formats
            QList<QVideoFrame::PixelFormat> fmts = m_surface->supportedPixelFormats();
            foreach(QVideoFrame::PixelFormat f, types) {
                if (fmts.contains(f)) {
                    pixelF = f;
                    if (!resolutions[pixelF].contains(m_windowSize)) {
                        Q_ASSERT(!resolutions[pixelF].isEmpty());
                        m_windowSize = resolutions[pixelF].first();
                    }
                    actualFormat = QVideoSurfaceFormat(m_windowSize, pixelF);
                    break;
                }
            }
        }

        if (m_surface->isFormatSupported(actualFormat)) {
            m_surface->start(actualFormat);
            m_state = QCamera::ActiveState;
            emit stateChanged(QCamera::ActiveState);
        } else {
            qWarning() << "surface doesn't support camera format, cant start";
            m_state = QCamera::LoadedState;
            emit stateChanged(QCamera::LoadedState);
            return;
        }
    } else {
        qWarning() << "no video surface, cant start";
        m_state = QCamera::LoadedState;
        emit stateChanged(QCamera::LoadedState);
        return;
    }

    opened = startStream();

    if (!opened) {
        qWarning() << "Stream did not open";
        m_state = QCamera::LoadedState;
        emit stateChanged(QCamera::LoadedState);
    }
}

void DSCameraSession::pause()
{
    suspendStream();
}

void DSCameraSession::stop()
{
    if(!opened) {
        return;
    }

    stopStream();
    opened = false;
    m_state = QCamera::LoadedState;
    emit stateChanged(QCamera::LoadedState);
}

void DSCameraSession::captureFrame()
{
    if(m_surface && frames.count() > 0) {

        QImage image;

        if(pixelF == QVideoFrame::Format_RGB24) {

            mutex.lock();

            image = QImage(frames.at(0)->buffer,m_windowSize.width(),m_windowSize.height(),
                    QImage::Format_RGB888).rgbSwapped().mirrored(true);

            QVideoFrame frame(image);
            frame.setStartTime(frames.at(0)->time);

            mutex.unlock();

            m_surface->present(frame);

        } else if (pixelF == QVideoFrame::Format_RGB32) {

            mutex.lock();

            image = QImage(frames.at(0)->buffer,m_windowSize.width(),m_windowSize.height(),
                    QImage::Format_RGB32).rgbSwapped().mirrored(true);

            QVideoFrame frame(image);
            frame.setStartTime(frames.at(0)->time);

            mutex.unlock();

            m_surface->present(frame);

        } else {
            qWarning() << "TODO:captureFrame() format =" << pixelF;
        }

        if (m_snapshot.length() > 0) {
            emit imageCaptured(m_currentImageId, image);
            image.save(m_snapshot,"JPG");
            emit imageSaved(m_currentImageId, m_snapshot);
            m_snapshot.clear();
            emit readyForCaptureChanged(true);
        }

        mutex.lock();
        if (frames.isEmpty()) {
            qWarning() << "Frames over-run";
        }

        video_buffer* buf = frames.takeFirst();
        delete buf->buffer;
        delete buf;
        mutex.unlock();
    }
}

HRESULT DSCameraSession::getPin(IBaseFilter *pFilter, PIN_DIRECTION PinDir, IPin **ppPin)
{
    *ppPin = 0;
    IEnumPins *pEnum = 0;
    IPin *pPin = 0;

    HRESULT hr = pFilter->EnumPins(&pEnum);
    if(FAILED(hr)) {
        return hr;
    }

    pEnum->Reset();
    while(pEnum->Next(1, &pPin, NULL) == S_OK) {
        PIN_DIRECTION ThisPinDir;
        pPin->QueryDirection(&ThisPinDir);
        if(ThisPinDir == PinDir) {
            pEnum->Release();
            *ppPin = pPin;
            return S_OK;
        }
        pEnum->Release();
    }
    pEnum->Release();
    return E_FAIL;
}

bool DSCameraSession::createFilterGraph()
{
    HRESULT hr;
    IMoniker* pMoniker = NULL;
    ICreateDevEnum* pDevEnum = NULL;
    IEnumMoniker* pEnum = NULL;

    CoInitialize(NULL);

    // Create the filter graph
    hr = CoCreateInstance(CLSID_FilterGraph,NULL,CLSCTX_INPROC,
            IID_IGraphBuilder, (void**)&pGraph);
    if (FAILED(hr)) {
        qWarning()<<"failed to create filter graph";
        return false;
    }

    // Create the capture graph builder
    hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
                          IID_ICaptureGraphBuilder2, (void**)&pBuild);
    if (FAILED(hr)) {
        qWarning()<<"failed to create graph builder";
        return false;
    }

    // Attach the filter graph to the capture graph
    hr = pBuild->SetFiltergraph(pGraph);
    if (FAILED(hr)) {
        qWarning()<<"failed to connect capture graph and filter graph";
        return false;
    }

    // Find the Capture device
    hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
                          CLSCTX_INPROC_SERVER, IID_ICreateDevEnum,
                          reinterpret_cast<void**>(&pDevEnum));
    if (SUCCEEDED(hr)) {
        // Create an enumerator for the video capture category
        hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnum, 0);
        pDevEnum->Release();
        if (S_OK == hr) {
            pEnum->Reset();
            IMalloc *mallocInterface = 0;
            CoGetMalloc(1, (LPMALLOC*)&mallocInterface);
            //go through and find all video capture devices
            while (pEnum->Next(1, &pMoniker, NULL) == S_OK) {

                BSTR strName = 0;
                hr = pMoniker->GetDisplayName(NULL, NULL, &strName);
                if (SUCCEEDED(hr)) {
                    QString output = QString::fromWCharArray(strName);
                    mallocInterface->Free(strName);
                    if (m_device.contains(output.toUtf8().constData())) {
                        hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pCap);
                        if (SUCCEEDED(hr)) {
                            pMoniker->Release();
                            break;
                        }
                    }
                }
                pMoniker->Release();
            }
            mallocInterface->Release();
            if (NULL == pCap)
            {
                if (m_device.contains("default"))
                {
                    pEnum->Reset();
                    // still have to loop to discard bind to storage failure case
                    while (pEnum->Next(1, &pMoniker, NULL) == S_OK) {
                        IPropertyBag *pPropBag = 0;

                        hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void**)(&pPropBag));
                        if (FAILED(hr)) {
                            pMoniker->Release();
                            continue; // Don't panic yet
                        }

                        // No need to get the description, just grab it

                        hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pCap);
                        pPropBag->Release();
                        pMoniker->Release();
                        if (SUCCEEDED(hr)) {
                            break; // done, stop looping through
                        }
                        else
                        {
                            qWarning() << "Object bind failed";
                        }
                    }
                }
            }
            pEnum->Release();
        }
    }

    // Sample grabber filter
    hr = CoCreateInstance(CLSID_SampleGrabber, NULL,CLSCTX_INPROC,
                          IID_IBaseFilter, (void**)&pSG_Filter);
    if (FAILED(hr)) {
        qWarning() << "failed to create sample grabber";
        return false;
    }

    hr = pSG_Filter->QueryInterface(IID_ISampleGrabber, (void**)&pSG);
    if (FAILED(hr)) {
        qWarning() << "failed to get sample grabber";
        return false;
    }
    pSG->SetOneShot(FALSE);
    pSG->SetBufferSamples(TRUE);
    pSG->SetCallback(StillCapCB, 1);

    updateProperties();
    CoUninitialize();
    return true;
}

void DSCameraSession::updateProperties()
{
    HRESULT hr;
    AM_MEDIA_TYPE *pmt = NULL;
    VIDEOINFOHEADER *pvi = NULL;
    VIDEO_STREAM_CONFIG_CAPS scc;
    IAMStreamConfig* pConfig = 0;

    hr = pBuild->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,pCap,
                               IID_IAMStreamConfig, (void**)&pConfig);
    if (FAILED(hr)) {
        qWarning()<<"failed to get config on capture device";
        return;
    }

    int iCount;
    int iSize;
    hr = pConfig->GetNumberOfCapabilities(&iCount, &iSize);
    if (FAILED(hr)) {
        qWarning()<<"failed to get capabilities";
        return;
    }

    QList<QSize> sizes;
    QVideoFrame::PixelFormat f = QVideoFrame::Format_Invalid;

    types.clear();
    resolutions.clear();

    for (int iIndex = 0; iIndex < iCount; iIndex++) {
        hr = pConfig->GetStreamCaps(iIndex, &pmt, reinterpret_cast<BYTE*>(&scc));
        if (hr == S_OK) {
            pvi = (VIDEOINFOHEADER*)pmt->pbFormat;
            if ((pmt->majortype == MEDIATYPE_Video) &&
                    (pmt->formattype == FORMAT_VideoInfo)) {
                // Add types
                if (pmt->subtype == MEDIASUBTYPE_RGB24) {
                    if (!types.contains(QVideoFrame::Format_RGB24)) {
                        types.append(QVideoFrame::Format_RGB24);
                        f = QVideoFrame::Format_RGB24;
                    }
                } else if (pmt->subtype == MEDIASUBTYPE_RGB32) {
                    if (!types.contains(QVideoFrame::Format_RGB32)) {
                        types.append(QVideoFrame::Format_RGB32);
                        f = QVideoFrame::Format_RGB32;
                    }
                } else if (pmt->subtype == MEDIASUBTYPE_YUY2) {
                    if (!types.contains(QVideoFrame::Format_YUYV)) {
                        types.append(QVideoFrame::Format_YUYV);
                        f = QVideoFrame::Format_YUYV;
                    }
                } else if (pmt->subtype == MEDIASUBTYPE_MJPG) {
                } else if (pmt->subtype == MEDIASUBTYPE_I420) {
                    if (!types.contains(QVideoFrame::Format_YUV420P)) {
                        types.append(QVideoFrame::Format_YUV420P);
                        f = QVideoFrame::Format_YUV420P;
                    }
                } else if (pmt->subtype == MEDIASUBTYPE_RGB555) {
                    if (!types.contains(QVideoFrame::Format_RGB555)) {
                        types.append(QVideoFrame::Format_RGB555);
                        f = QVideoFrame::Format_RGB555;
                    }
                } else if (pmt->subtype == MEDIASUBTYPE_YVU9) {
                } else if (pmt->subtype == MEDIASUBTYPE_UYVY) {
                    if (!types.contains(QVideoFrame::Format_UYVY)) {
                        types.append(QVideoFrame::Format_UYVY);
                        f = QVideoFrame::Format_UYVY;
                    }
                } else {
                    qWarning() << "UNKNOWN FORMAT: " << pmt->subtype.Data1;
                }
                // Add resolutions
                QSize res(pvi->bmiHeader.biWidth, pvi->bmiHeader.biHeight);
                if (!resolutions.contains(f)) {
                    sizes.clear();
                    resolutions.insert(f,sizes);
                }
                resolutions[f].append(res);
            }
        }
    }
    pConfig->Release();

    if (!types.isEmpty()) {
        // Add RGB formats and let directshow do color space conversion if required.
        if (!types.contains(QVideoFrame::Format_RGB24)) {
            types.append(QVideoFrame::Format_RGB24);
            resolutions.insert(QVideoFrame::Format_RGB24, resolutions[types.first()]);
        }
        if (!types.contains(QVideoFrame::Format_RGB32)) {
            types.append(QVideoFrame::Format_RGB32);
            resolutions.insert(QVideoFrame::Format_RGB32, resolutions[types.first()]);
        }
    }
}

bool DSCameraSession::setProperties()
{
    CoInitialize(NULL);

    HRESULT hr;
    AM_MEDIA_TYPE am_media_type;
    AM_MEDIA_TYPE *pmt = NULL;
    VIDEOINFOHEADER *pvi = NULL;
    VIDEO_STREAM_CONFIG_CAPS scc;

    IAMStreamConfig* pConfig = 0;
    hr = pBuild->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, pCap,
                               IID_IAMStreamConfig, (void**)&pConfig);
    if(FAILED(hr)) {
        qWarning()<<"failed to get config on capture device";
        return false;
    }

    int iCount;
    int iSize;
    hr = pConfig->GetNumberOfCapabilities(&iCount, &iSize);
    if(FAILED(hr)) {
        qWarning()<<"failed to get capabilities";
        return false;
    }

    bool setFormatOK = false;
    for (int iIndex = 0; iIndex < iCount; iIndex++) {
        hr = pConfig->GetStreamCaps(iIndex, &pmt, reinterpret_cast<BYTE*>(&scc));
        if (hr == S_OK) {
            pvi = (VIDEOINFOHEADER*)pmt->pbFormat;

            if ((pmt->majortype == MEDIATYPE_Video) &&
                (pmt->formattype == FORMAT_VideoInfo)) {
                if ((actualFormat.frameWidth() == pvi->bmiHeader.biWidth) &&
                    (actualFormat.frameHeight() == pvi->bmiHeader.biHeight)) {
                    hr = pConfig->SetFormat(pmt);
                    _FreeMediaType(*pmt);
                    if(FAILED(hr)) {
                        qWarning()<<"failed to set format:" << hr;
                        qWarning()<<"but going to continue";
                        continue; // We going to continue
                    } else {
                        setFormatOK = true;
                        break;
                    }
                }
            }
        }
    }
    pConfig->Release();

    if (!setFormatOK) {
            qWarning() << "unable to set any format for camera";
            return false;
    }

    // Set Sample Grabber config to match capture
    ZeroMemory(&am_media_type, sizeof(am_media_type));
    am_media_type.majortype = MEDIATYPE_Video;

    if (actualFormat.pixelFormat() == QVideoFrame::Format_RGB32)
        am_media_type.subtype = MEDIASUBTYPE_RGB32;
    else if (actualFormat.pixelFormat() == QVideoFrame::Format_RGB24)
        am_media_type.subtype = MEDIASUBTYPE_RGB24;
    else if (actualFormat.pixelFormat() == QVideoFrame::Format_YUYV)
        am_media_type.subtype = MEDIASUBTYPE_YUY2;
    else if (actualFormat.pixelFormat() == QVideoFrame::Format_YUV420P)
        am_media_type.subtype = MEDIASUBTYPE_I420;
    else if (actualFormat.pixelFormat() == QVideoFrame::Format_RGB555)
        am_media_type.subtype = MEDIASUBTYPE_RGB555;
    else if (actualFormat.pixelFormat() == QVideoFrame::Format_UYVY)
        am_media_type.subtype = MEDIASUBTYPE_UYVY;
    else {
        qWarning()<<"unknown format? for SG";
        return false;
    }

    am_media_type.formattype = FORMAT_VideoInfo;
    hr = pSG->SetMediaType(&am_media_type);
    if (FAILED(hr)) {
        qWarning()<<"failed to set video format on grabber";
        return false;
    }

    pSG->GetConnectedMediaType(&StillMediaType);

    CoUninitialize();

    return true;
}

bool DSCameraSession::openStream()
{
    //Opens the stream for reading and allocates any necessary resources needed
    //Return true if success, false otherwise

    if (opened) {
        return true;
    }

    if (!graph) {
        graph = createFilterGraph();
        if(!graph) {
            qWarning()<<"failed to create filter graph in openStream";
            return false;
        }
    }

    CoInitialize(NULL);

    HRESULT hr;

    hr = pGraph->AddFilter(pCap, L"Capture Filter");
    if (FAILED(hr)) {
        qWarning()<<"failed to create capture filter";
        return false;
    }

    hr = pGraph->AddFilter(pSG_Filter, L"Sample Grabber");
    if (FAILED(hr)) {
        qWarning()<<"failed to add sample grabber";
        return false;
    }

    hr = pBuild->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
                              pCap, NULL, pSG_Filter);
    if (FAILED(hr)) {
        qWarning() << "failed to renderstream" << hr;
        return false;
    }
    pSG->GetConnectedMediaType(&StillMediaType);
    pSG_Filter->Release();

    CoUninitialize();

    return true;
}

void DSCameraSession::closeStream()
{
    // Closes the stream and internally frees any resources used
    HRESULT hr;
    IMediaControl* pControl = 0;

    hr = pGraph->QueryInterface(IID_IMediaControl,(void**)&pControl);
    if (FAILED(hr)) {
        qWarning()<<"failed to get stream control";
        return;
    }

    hr = pControl->StopWhenReady();
    if (FAILED(hr)) {
        qWarning()<<"failed to stop";
        pControl->Release();
        return;
    }

    pControl->Release();

    opened = false;
    IPin *pPin = 0;

    if (pCap)
    {
        hr = getPin(pCap, PINDIR_OUTPUT, &pPin);
        if(FAILED(hr)) {
            qWarning()<<"failed to disconnect capture filter";
            return;
        }
    }

    pGraph->Disconnect(pPin);
    if (FAILED(hr)) {
        qWarning()<<"failed to disconnect grabber filter";
        return;
    }

    hr = getPin(pSG_Filter,PINDIR_INPUT,&pPin);
    pGraph->Disconnect(pPin);
    pGraph->RemoveFilter(pSG_Filter);
    pGraph->RemoveFilter(pCap);

    SAFE_RELEASE(pCap);
    SAFE_RELEASE(pSG_Filter);
    SAFE_RELEASE(pGraph);
    SAFE_RELEASE(pBuild);

    graph = false;
}

bool DSCameraSession::startStream()
{
    // Starts the stream, by emitting either QVideoPackets
    // or QvideoFrames, depending on Format chosen
    if (!graph)
        graph = createFilterGraph();

    if (!setProperties()) {
        qWarning() << "Couldn't set properties (retrying)";
        closeStream();
        if (!openStream()) {
            qWarning() << "Retry to open strean failed";
            return false;
        }
    }

    if (!opened) {
        opened = openStream();
        if (!opened) {
            qWarning() << "failed to openStream()";
            return false;
        }
    }

    HRESULT hr;
    IMediaControl* pControl = 0;

    hr = pGraph->QueryInterface(IID_IMediaControl, (void**)&pControl);
    if (FAILED(hr)) {
        qWarning() << "failed to get stream control";
        return false;
    }

    hr = pControl->Run();
    pControl->Release();

    if (FAILED(hr)) {
        qWarning() << "failed to start";
        return false;
    }
    active = true;
    return true;
}

void DSCameraSession::stopStream()
{
    // Stops the stream from emitting packets
    HRESULT hr;

    IMediaControl* pControl = 0;
    hr = pGraph->QueryInterface(IID_IMediaControl, (void**)&pControl);
    if (FAILED(hr)) {
        qWarning() << "failed to get stream control";
        return;
    }

    hr = pControl->Stop();
    pControl->Release();
    if (FAILED(hr)) {
        qWarning() << "failed to stop";
        return;
    }
    active = false;

    if (opened) {
        closeStream();
    }
}

void DSCameraSession::suspendStream()
{
    // Pauses the stream
    HRESULT hr;

    IMediaControl* pControl = 0;
    hr = pGraph->QueryInterface(IID_IMediaControl, (void**)&pControl);
    if (FAILED(hr)) {
        qWarning() << "failed to get stream control";
        return;
    }

    hr = pControl->Pause();
    pControl->Release();
    if (FAILED(hr)) {
        qWarning() << "failed to pause";
        return;
    }

    active = false;
}

void DSCameraSession::resumeStream()
{
    // Resumes a paused stream
    startStream();
}

QT_END_NAMESPACE