summaryrefslogtreecommitdiffstats
path: root/src/plugins/winrt/qwinrtcameracontrol.cpp
blob: 3c51de5a4134401e95d52934d499bac394b431a7 (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
/****************************************************************************
**
** Copyright (C) 2014 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 "qwinrtcameracontrol.h"
#include "qwinrtcameravideorenderercontrol.h"
#include "qwinrtvideodeviceselectorcontrol.h"
#include "qwinrtcameraimagecapturecontrol.h"

#include <QtCore/qfunctions_winrt.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QPointer>

#include <mfapi.h>
#include <mferror.h>
#include <mfidl.h>
#include <wrl.h>
#include <windows.devices.enumeration.h>
#include <windows.media.capture.h>
#include <windows.storage.streams.h>

using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Devices::Enumeration;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Media;
using namespace ABI::Windows::Media::Capture;
using namespace ABI::Windows::Media::Devices;
using namespace ABI::Windows::Media::MediaProperties;
using namespace ABI::Windows::Storage::Streams;

QT_USE_NAMESPACE

#define RETURN_VOID_AND_EMIT_ERROR(msg) \
    if (FAILED(hr)) { \
        emit error(QCamera::CameraError, qt_error_string(hr)); \
        RETURN_VOID_IF_FAILED(msg); \
    }

class CriticalSectionLocker
{
public:
    CriticalSectionLocker(CRITICAL_SECTION *section)
        : m_section(section)
    {
        EnterCriticalSection(m_section);
    }
    ~CriticalSectionLocker()
    {
        LeaveCriticalSection(m_section);
    }
private:
    CRITICAL_SECTION *m_section;
};

class MediaStream : public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IMFStreamSink, IMFMediaEventGenerator, IMFMediaTypeHandler>
{
public:
    MediaStream(IMFMediaType *type, IMFMediaSink *mediaSink, QWinRTCameraVideoRendererControl *videoRenderer)
        : m_type(type), m_sink(mediaSink), m_videoRenderer(videoRenderer)
    {
        Q_ASSERT(m_videoRenderer);

        InitializeCriticalSectionEx(&m_mutex, 0, 0);

        HRESULT hr;
        hr = MFCreateEventQueue(&m_eventQueue);
        Q_ASSERT_SUCCEEDED(hr);
        hr = MFAllocateSerialWorkQueue(MFASYNC_CALLBACK_QUEUE_STANDARD, &m_workQueueId);
        Q_ASSERT_SUCCEEDED(hr);
    }

    ~MediaStream()
    {
        CriticalSectionLocker locker(&m_mutex);
        m_eventQueue->Shutdown();
        DeleteCriticalSection(&m_mutex);
    }

    HRESULT RequestSample()
    {
        if (m_pendingSamples.load() < 3) {
            m_pendingSamples.ref();
            return QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, Q_NULLPTR);
        }
        return S_OK;
    }

    HRESULT __stdcall GetEvent(DWORD flags, IMFMediaEvent **event) Q_DECL_OVERRIDE
    {
        EnterCriticalSection(&m_mutex);
        // Create an extra reference to avoid deadlock
        ComPtr<IMFMediaEventQueue> eventQueue = m_eventQueue;
        LeaveCriticalSection(&m_mutex);

        return eventQueue->GetEvent(flags, event);
    }

    HRESULT __stdcall BeginGetEvent(IMFAsyncCallback *callback, IUnknown *state) Q_DECL_OVERRIDE
    {
        CriticalSectionLocker locker(&m_mutex);
        HRESULT hr = m_eventQueue->BeginGetEvent(callback, state);
        return hr;
    }

    HRESULT __stdcall EndGetEvent(IMFAsyncResult *result, IMFMediaEvent **event) Q_DECL_OVERRIDE
    {
        CriticalSectionLocker locker(&m_mutex);
        return m_eventQueue->EndGetEvent(result, event);
    }

    HRESULT __stdcall QueueEvent(MediaEventType eventType, const GUID &extendedType, HRESULT status, const PROPVARIANT *value) Q_DECL_OVERRIDE
    {
        CriticalSectionLocker locker(&m_mutex);
        return m_eventQueue->QueueEventParamVar(eventType, extendedType, status, value);
    }

    HRESULT __stdcall GetMediaSink(IMFMediaSink **mediaSink) Q_DECL_OVERRIDE
    {
        *mediaSink = m_sink;
        return S_OK;
    }

    HRESULT __stdcall GetIdentifier(DWORD *identifier) Q_DECL_OVERRIDE
    {
        *identifier = 0;
        return S_OK;
    }

    HRESULT __stdcall GetMediaTypeHandler(IMFMediaTypeHandler **handler) Q_DECL_OVERRIDE
    {
        return QueryInterface(IID_PPV_ARGS(handler));
    }

    HRESULT __stdcall ProcessSample(IMFSample *sample) Q_DECL_OVERRIDE
    {
        ComPtr<IMFMediaBuffer> buffer;
        HRESULT hr = sample->GetBufferByIndex(0, &buffer);
        RETURN_HR_IF_FAILED("Failed to get buffer from camera sample");
        ComPtr<IMF2DBuffer> buffer2d;
        hr = buffer.As(&buffer2d);
        RETURN_HR_IF_FAILED("Failed to cast camera sample buffer to 2D buffer");

        m_pendingSamples.deref();
        m_videoRenderer->queueBuffer(buffer2d.Get());

        return hr;
    }

    HRESULT __stdcall PlaceMarker(MFSTREAMSINK_MARKER_TYPE type, const PROPVARIANT *value, const PROPVARIANT *context) Q_DECL_OVERRIDE
    {
        Q_UNUSED(type);
        Q_UNUSED(value);
        QueueEvent(MEStreamSinkMarker, GUID_NULL, S_OK, context);
        return S_OK;
    }

    HRESULT __stdcall Flush() Q_DECL_OVERRIDE
    {
        m_videoRenderer->discardBuffers();
        m_pendingSamples.store(0);
        return S_OK;
    }

    HRESULT __stdcall IsMediaTypeSupported(IMFMediaType *type, IMFMediaType **) Q_DECL_OVERRIDE
    {
        HRESULT hr;
        GUID majorType;
        hr = type->GetMajorType(&majorType);
        Q_ASSERT_SUCCEEDED(hr);
        if (!IsEqualGUID(majorType, MFMediaType_Video))
            return MF_E_INVALIDMEDIATYPE;
        return S_OK;
    }

    HRESULT __stdcall GetMediaTypeCount(DWORD *typeCount) Q_DECL_OVERRIDE
    {
        *typeCount = 1;
        return S_OK;
    }

    HRESULT __stdcall GetMediaTypeByIndex(DWORD index, IMFMediaType **type) Q_DECL_OVERRIDE
    {
        if (index == 0)
            return m_type.CopyTo(type);
        return E_BOUNDS;
    }

    HRESULT __stdcall SetCurrentMediaType(IMFMediaType *type) Q_DECL_OVERRIDE
    {
        if (FAILED(IsMediaTypeSupported(type, Q_NULLPTR)))
            return MF_E_INVALIDREQUEST;

        m_type = type;
        return S_OK;
    }

    HRESULT __stdcall GetCurrentMediaType(IMFMediaType **type) Q_DECL_OVERRIDE
    {
        return m_type.CopyTo(type);
    }

    HRESULT __stdcall GetMajorType(GUID *majorType) Q_DECL_OVERRIDE
    {
        return m_type->GetMajorType(majorType);
    }

private:
    CRITICAL_SECTION m_mutex;
    ComPtr<IMFMediaType> m_type;
    IMFMediaSink *m_sink;
    ComPtr<IMFMediaEventQueue> m_eventQueue;
    DWORD m_workQueueId;

    QWinRTCameraVideoRendererControl *m_videoRenderer;
    QAtomicInt m_pendingSamples;
};

class MediaSink : public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IMediaExtension, IMFMediaSink, IMFClockStateSink>
{
public:
    MediaSink(IMediaEncodingProfile *encodingProfile, QWinRTCameraVideoRendererControl *videoRenderer)
        : m_videoRenderer(videoRenderer)
    {
        HRESULT hr;
        ComPtr<IVideoEncodingProperties> videoProperties;
        hr = encodingProfile->get_Video(&videoProperties);
        RETURN_VOID_IF_FAILED("Failed to get video properties");
        ComPtr<IMFMediaType> videoType;
        hr = MFCreateMediaTypeFromProperties(videoProperties.Get(), &videoType);
        RETURN_VOID_IF_FAILED("Failed to create video type");
        m_stream = Make<MediaStream>(videoType.Get(), this, videoRenderer);
    }

    ~MediaSink()
    {
    }

    HRESULT RequestSample()
    {
        return m_stream->RequestSample();
    }

    HRESULT __stdcall SetProperties(Collections::IPropertySet *configuration) Q_DECL_OVERRIDE
    {
        Q_UNUSED(configuration);
        return E_NOTIMPL;
    }

    HRESULT __stdcall GetCharacteristics(DWORD *characteristics) Q_DECL_OVERRIDE
    {
        *characteristics = MEDIASINK_FIXED_STREAMS | MEDIASINK_RATELESS;
        return S_OK;
    }

    HRESULT __stdcall AddStreamSink(DWORD streamSinkIdentifier, IMFMediaType *mediaType, IMFStreamSink **streamSink) Q_DECL_OVERRIDE
    {
        Q_UNUSED(streamSinkIdentifier);
        Q_UNUSED(mediaType);
        Q_UNUSED(streamSink);
        return E_NOTIMPL;
    }

    HRESULT __stdcall RemoveStreamSink(DWORD streamSinkIdentifier) Q_DECL_OVERRIDE
    {
        Q_UNUSED(streamSinkIdentifier);
        return E_NOTIMPL;
    }

    HRESULT __stdcall GetStreamSinkCount(DWORD *streamSinkCount) Q_DECL_OVERRIDE
    {
        *streamSinkCount = 1;
        return S_OK;
    }

    HRESULT __stdcall GetStreamSinkByIndex(DWORD index, IMFStreamSink **streamSink) Q_DECL_OVERRIDE
    {
        if (index == 0)
            return m_stream.CopyTo(streamSink);
        return MF_E_INVALIDINDEX;
    }

    HRESULT __stdcall GetStreamSinkById(DWORD streamSinkIdentifier, IMFStreamSink **streamSink) Q_DECL_OVERRIDE
    {
        // ID and index are always 0
        HRESULT hr = GetStreamSinkByIndex(streamSinkIdentifier, streamSink);
        return hr == MF_E_INVALIDINDEX ? MF_E_INVALIDSTREAMNUMBER : hr;
    }

    HRESULT __stdcall SetPresentationClock(IMFPresentationClock *presentationClock) Q_DECL_OVERRIDE
    {
        HRESULT hr = S_OK;
        m_presentationClock = presentationClock;
        if (m_presentationClock)
            hr = m_presentationClock->AddClockStateSink(this);
        return hr;
    }

    HRESULT __stdcall GetPresentationClock(IMFPresentationClock **presentationClock) Q_DECL_OVERRIDE
    {
        return m_presentationClock.CopyTo(presentationClock);
    }

    HRESULT __stdcall Shutdown() Q_DECL_OVERRIDE
    {
        m_stream->Flush();
        m_videoRenderer->setActive(false);
        return m_presentationClock->Stop();
    }

    HRESULT __stdcall OnClockStart(MFTIME systemTime, LONGLONG clockStartOffset) Q_DECL_OVERRIDE
    {
        Q_UNUSED(systemTime);
        Q_UNUSED(clockStartOffset);

        m_videoRenderer->setActive(true);

        return S_OK;
    }

    HRESULT __stdcall OnClockStop(MFTIME systemTime) Q_DECL_OVERRIDE
    {
        Q_UNUSED(systemTime);

        m_videoRenderer->setActive(false);

        return m_stream->QueueEvent(MEStreamSinkStopped, GUID_NULL, S_OK, Q_NULLPTR);
    }

    HRESULT __stdcall OnClockPause(MFTIME systemTime) Q_DECL_OVERRIDE
    {
        Q_UNUSED(systemTime);

        m_videoRenderer->setActive(false);

        return m_stream->QueueEvent(MEStreamSinkPaused, GUID_NULL, S_OK, Q_NULLPTR);
    }

    HRESULT __stdcall OnClockRestart(MFTIME systemTime) Q_DECL_OVERRIDE
    {
        Q_UNUSED(systemTime);

        m_videoRenderer->setActive(true);

        return m_stream->QueueEvent(MEStreamSinkStarted, GUID_NULL, S_OK, Q_NULLPTR);
    }

    HRESULT __stdcall OnClockSetRate(MFTIME systemTime, float rate) Q_DECL_OVERRIDE
    {
        Q_UNUSED(systemTime);
        Q_UNUSED(rate);
        return E_NOTIMPL;
    }

private:
    ComPtr<MediaStream> m_stream;
    ComPtr<IMFPresentationClock> m_presentationClock;

    QWinRTCameraVideoRendererControl *m_videoRenderer;
};

class QWinRTCameraControlPrivate
{
public:
    QCamera::State state;
    QCamera::Status status;
    QCamera::CaptureModes captureMode;

    ComPtr<IMediaCapture> capture;
    ComPtr<IMediaCaptureVideoPreview> capturePreview;
    EventRegistrationToken captureFailedCookie;
    EventRegistrationToken recordLimitationCookie;

    ComPtr<IMediaEncodingProfileStatics> encodingProfileFactory;

    ComPtr<IMediaEncodingProfile> encodingProfile;
    ComPtr<MediaSink> mediaSink;

    QSize size;
    QPointer<QWinRTCameraVideoRendererControl> videoRenderer;
    QPointer<QWinRTVideoDeviceSelectorControl> videoDeviceSelector;
    QPointer<QWinRTCameraImageCaptureControl> imageCaptureControl;
};

QWinRTCameraControl::QWinRTCameraControl(QObject *parent)
    : QCameraControl(parent), d_ptr(new QWinRTCameraControlPrivate)
{
    Q_D(QWinRTCameraControl);

    d->state = QCamera::UnloadedState;
    d->status = QCamera::UnloadedStatus;
    d->captureMode = QCamera::CaptureStillImage;
    d->captureFailedCookie.value = 0;
    d->recordLimitationCookie.value = 0;
    d->videoRenderer = new QWinRTCameraVideoRendererControl(d->size, this);
    connect(d->videoRenderer, &QWinRTCameraVideoRendererControl::bufferRequested,
            this, &QWinRTCameraControl::onBufferRequested);
    d->videoDeviceSelector = new QWinRTVideoDeviceSelectorControl(this);
    d->imageCaptureControl = new QWinRTCameraImageCaptureControl(this);
}

QWinRTCameraControl::~QWinRTCameraControl()
{
    setState(QCamera::UnloadedState);
}

QCamera::State QWinRTCameraControl::state() const
{
    Q_D(const QWinRTCameraControl);
    return d->state;
}

void QWinRTCameraControl::setState(QCamera::State state)
{
    Q_D(QWinRTCameraControl);

    if (d->state == state)
        return;

    HRESULT hr;
    switch (state) {
    case QCamera::ActiveState: {
        // Capture has not been created or initialized
        if (d->state == QCamera::UnloadedState) {
            hr = initialize();
            RETURN_VOID_AND_EMIT_ERROR("Failed to initialize media capture");
        }
        Q_ASSERT(d->state == QCamera::LoadedState);

        d->mediaSink = Make<MediaSink>(d->encodingProfile.Get(), d->videoRenderer);
        ComPtr<IAsyncAction> op;
        hr = d->capturePreview->StartPreviewToCustomSinkAsync(d->encodingProfile.Get(), d->mediaSink.Get(), &op);
        RETURN_VOID_AND_EMIT_ERROR("Failed to initiate capture");
        if (d->status != QCamera::StartingStatus) {
            d->status = QCamera::StartingStatus;
            emit statusChanged(d->status);
        }

        hr = QWinRTFunctions::await(op);
        if (FAILED(hr)) {
            emit error(QCamera::CameraError, qt_error_string(hr));
            setState(QCamera::UnloadedState); // Unload everything, as initialize() will need be called again
            return;
        }

        d->state = QCamera::ActiveState;
        emit stateChanged(d->state);
        d->status = QCamera::ActiveStatus;
        emit statusChanged(d->status);
        break;
    }
    case QCamera::LoadedState: {
        // If moving from unloaded, initialize the camera
        if (d->state == QCamera::UnloadedState) {
            hr = initialize();
            RETURN_VOID_AND_EMIT_ERROR("Failed to initialize media capture");
        }
        // fall through
    }
    case QCamera::UnloadedState: {
        // Stop the camera if it is running (transition to LoadedState)
        if (d->status == QCamera::ActiveStatus) {
            ComPtr<IAsyncAction> op;
            hr = d->capturePreview->StopPreviewAsync(&op);
            RETURN_VOID_AND_EMIT_ERROR("Failed to stop camera preview");
            if (d->status != QCamera::StoppingStatus) {
                d->status = QCamera::StoppingStatus;
                emit statusChanged(d->status);
            }
            Q_ASSERT_SUCCEEDED(hr);
            hr = QWinRTFunctions::await(op); // Synchronize unloading
            if (FAILED(hr))
                emit error(QCamera::InvalidRequestError, qt_error_string(hr));

            d->mediaSink->Shutdown();
            d->mediaSink.Reset();

            d->state = QCamera::LoadedState;
            emit stateChanged(d->state);

            d->status = QCamera::LoadedStatus;
            emit statusChanged(d->status);
        }
        // Completely unload if needed
        if (state == QCamera::UnloadedState) {
            if (!d->capture) // Already unloaded
                break;

            if (d->status != QCamera::UnloadingStatus) {
                d->status = QCamera::UnloadingStatus;
                emit statusChanged(d->status);
            }

            if (d->capture && d->captureFailedCookie.value) {
                hr = d->capture->remove_Failed(d->captureFailedCookie);
                Q_ASSERT_SUCCEEDED(hr);
                d->captureFailedCookie.value = 0;
            }
            if (d->capture && d->recordLimitationCookie.value) {
                d->capture->remove_RecordLimitationExceeded(d->recordLimitationCookie);
                Q_ASSERT_SUCCEEDED(hr);
                d->recordLimitationCookie.value = 0;
            }
            ComPtr<IClosable> capture;
            hr = d->capture.As(&capture);
            Q_ASSERT_SUCCEEDED(hr);
            hr = capture->Close();
            RETURN_VOID_AND_EMIT_ERROR("Failed to close the capture manger");
            d->capture.Reset();
            if (d->state != QCamera::UnloadedState) {
                d->state = QCamera::UnloadedState;
                emit stateChanged(d->state);
            }
            if (d->status != QCamera::UnloadedStatus) {
                d->status = QCamera::UnloadedStatus;
                emit statusChanged(d->status);
            }
        }
        break;
    }
    default:
        break;
    }
}

QCamera::Status QWinRTCameraControl::status() const
{
    Q_D(const QWinRTCameraControl);
    return d->status;
}

QCamera::CaptureModes QWinRTCameraControl::captureMode() const
{
    Q_D(const QWinRTCameraControl);
    return d->captureMode;
}

void QWinRTCameraControl::setCaptureMode(QCamera::CaptureModes mode)
{
    Q_D(QWinRTCameraControl);

    if (d->captureMode == mode)
        return;

    if (!isCaptureModeSupported(mode)) {
        qWarning("Unsupported capture mode: %d", mode);
        return;
    }

    d->captureMode = mode;
    emit captureModeChanged(d->captureMode);
}

bool QWinRTCameraControl::isCaptureModeSupported(QCamera::CaptureModes mode) const
{
    return mode >= QCamera::CaptureViewfinder && mode <= QCamera::CaptureStillImage;
}

bool QWinRTCameraControl::canChangeProperty(QCameraControl::PropertyChangeType changeType, QCamera::Status status) const
{
    Q_UNUSED(changeType);

    return status == QCamera::UnloadedStatus; // For now, assume shutdown is required for all property changes
}

QVideoRendererControl *QWinRTCameraControl::videoRenderer() const
{
    Q_D(const QWinRTCameraControl);
    return d->videoRenderer;
}

QVideoDeviceSelectorControl *QWinRTCameraControl::videoDeviceSelector() const
{
    Q_D(const QWinRTCameraControl);
    return d->videoDeviceSelector;
}

QCameraImageCaptureControl *QWinRTCameraControl::imageCaptureControl() const
{
    Q_D(const QWinRTCameraControl);
    return d->imageCaptureControl;
}

IMediaCapture *QWinRTCameraControl::handle() const
{
    Q_D(const QWinRTCameraControl);
    return d->capture.Get();
}

QSize QWinRTCameraControl::imageSize() const
{
    Q_D(const QWinRTCameraControl);
    return d->size;
}

void QWinRTCameraControl::onBufferRequested()
{
    Q_D(QWinRTCameraControl);

    if (d->mediaSink)
        d->mediaSink->RequestSample();
}

HRESULT QWinRTCameraControl::initialize()
{
    Q_D(QWinRTCameraControl);

    if (d->status != QCamera::LoadingStatus) {
        d->status = QCamera::LoadingStatus;
        emit statusChanged(d->status);
    }

    HRESULT hr;
    ComPtr<IInspectable> capture;
    hr = RoActivateInstance(Wrappers::HString::MakeReference(RuntimeClass_Windows_Media_Capture_MediaCapture).Get(),
                            &capture);
    Q_ASSERT_SUCCEEDED(hr);
    hr = capture.As(&d->capture);
    Q_ASSERT_SUCCEEDED(hr);
    hr = d->capture.As(&d->capturePreview);
    Q_ASSERT_SUCCEEDED(hr);
    hr = d->capture->add_Failed(Callback<IMediaCaptureFailedEventHandler>(this, &QWinRTCameraControl::onCaptureFailed).Get(),
                                &d->captureFailedCookie);
    Q_ASSERT_SUCCEEDED(hr);
    hr = d->capture->add_RecordLimitationExceeded(Callback<IRecordLimitationExceededEventHandler>(this, &QWinRTCameraControl::onRecordLimitationExceeded).Get(),
                                                  &d->recordLimitationCookie);
    Q_ASSERT_SUCCEEDED(hr);
    hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Media_MediaProperties_MediaEncodingProfile).Get(),
                                IID_PPV_ARGS(&d->encodingProfileFactory));
    Q_ASSERT_SUCCEEDED(hr);

    int deviceIndex = d->videoDeviceSelector->selectedDevice();
    if (deviceIndex < 0)
        deviceIndex = d->videoDeviceSelector->defaultDevice();

    const QString deviceName = d->videoDeviceSelector->deviceName(deviceIndex);
    if (deviceName.isEmpty()) {
        qWarning("No video device available or selected.");
        return E_FAIL;
    }

    if (d->videoDeviceSelector->cameraPosition(deviceName) == QCamera::FrontFace)
        d->videoRenderer->setScanLineDirection(QVideoSurfaceFormat::BottomToTop);

    ComPtr<IMediaCaptureInitializationSettings> settings;
    hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Media_Capture_MediaCaptureInitializationSettings).Get(),
                            &settings);
    Q_ASSERT_SUCCEEDED(hr);
    HStringReference deviceId(reinterpret_cast<LPCWSTR>(deviceName.utf16()), deviceName.length());
    hr = settings->put_VideoDeviceId(deviceId.Get());
    Q_ASSERT_SUCCEEDED(hr);

    hr = settings->put_StreamingCaptureMode(StreamingCaptureMode_Video);
    Q_ASSERT_SUCCEEDED(hr);

    hr = settings->put_PhotoCaptureSource(PhotoCaptureSource_Auto);
    Q_ASSERT_SUCCEEDED(hr);

    ComPtr<IAsyncAction> op;
    hr = d->capture->InitializeWithSettingsAsync(settings.Get(), &op);
    RETURN_HR_IF_FAILED("Failed to begin initialization of media capture manager");
    hr = QWinRTFunctions::await(op, QWinRTFunctions::ProcessThreadEvents);
    if (hr == E_ACCESSDENIED) {
        qWarning("Access denied when initializing the media capture manager. "
                 "Check your manifest settings for microphone and webcam access.");
    }
    RETURN_HR_IF_FAILED("Failed to initialize media capture manager");

    ComPtr<IVideoDeviceController> videoDeviceController;
    hr = d->capture->get_VideoDeviceController(&videoDeviceController);
    Q_ASSERT_SUCCEEDED(hr);
    ComPtr<IMediaDeviceController> deviceController;
    hr = videoDeviceController.As(&deviceController);
    Q_ASSERT_SUCCEEDED(hr);
    ComPtr<IVectorView<IMediaEncodingProperties *>> encodingPropertiesList;
    MediaStreamType mediaStreamType;
    switch (d->captureMode) {
    default:
    case QCamera::CaptureViewfinder:
        mediaStreamType = MediaStreamType_VideoPreview;
        break;
    case QCamera::CaptureStillImage:
        mediaStreamType = MediaStreamType_Photo;
        break;
    case QCamera::CaptureVideo:
        mediaStreamType = MediaStreamType_VideoRecord;
        break;
    }
    hr = deviceController->GetAvailableMediaStreamProperties(mediaStreamType, &encodingPropertiesList);
    Q_ASSERT_SUCCEEDED(hr);

    d->size = QSize();
    ComPtr<IVideoEncodingProperties> videoEncodingProperties;
    quint32 encodingPropertiesListSize;
    hr = encodingPropertiesList->get_Size(&encodingPropertiesListSize);
    Q_ASSERT_SUCCEEDED(hr);
    for (quint32 i = 0; i < encodingPropertiesListSize; ++i) {
        ComPtr<IMediaEncodingProperties> properties;
        hr = encodingPropertiesList->GetAt(i, &properties);
        Q_ASSERT_SUCCEEDED(hr);
        ComPtr<IVideoEncodingProperties> videoProperties;
        hr = properties.As(&videoProperties);
        Q_ASSERT_SUCCEEDED(hr);
        UINT32 width, height;
        hr = videoProperties->get_Width(&width);
        Q_ASSERT_SUCCEEDED(hr);
        hr = videoProperties->get_Height(&height);
        Q_ASSERT_SUCCEEDED(hr);
        // Choose the highest-quality format
        if (int(width * height) > d->size.width() * d->size.height()) {
            d->size = QSize(width, height);
            videoEncodingProperties = videoProperties;
        }
    }

    if (!videoEncodingProperties || d->size.isEmpty()) {
        hr = MF_E_INVALID_FORMAT;
        RETURN_HR_IF_FAILED("Failed to find a suitable video format");
    }

    hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Media_MediaProperties_MediaEncodingProfile).Get(),
                            &d->encodingProfile);
    Q_ASSERT_SUCCEEDED(hr);
    hr = d->encodingProfile->put_Video(videoEncodingProperties.Get());
    Q_ASSERT_SUCCEEDED(hr);
    if (d->videoRenderer)
        d->videoRenderer->setSize(d->size);

    if (SUCCEEDED(hr) && d->state != QCamera::LoadedState) {
        d->state = QCamera::LoadedState;
        emit stateChanged(d->state);
    }
    if (SUCCEEDED(hr) && d->status != QCamera::LoadedStatus) {
        d->status = QCamera::LoadedStatus;
        emit statusChanged(d->status);
    }
    return hr;
}

HRESULT QWinRTCameraControl::onCaptureFailed(IMediaCapture *, IMediaCaptureFailedEventArgs *args)
{
    HRESULT hr;
    UINT32 code;
    hr = args->get_Code(&code);
    RETURN_HR_IF_FAILED("Failed to get error code");
    HString message;
    args->get_Message(message.GetAddressOf());
    RETURN_HR_IF_FAILED("Failed to get error message");
    quint32 messageLength;
    const wchar_t *messageBuffer = message.GetRawBuffer(&messageLength);
    emit error(QCamera::CameraError, QString::fromWCharArray(messageBuffer, messageLength));
    setState(QCamera::LoadedState);
    return S_OK;
}

HRESULT QWinRTCameraControl::onRecordLimitationExceeded(IMediaCapture *)
{
    emit error(QCamera::CameraError, QStringLiteral("Recording limit exceeded."));
    setState(QCamera::LoadedState);
    return S_OK;
}