summaryrefslogtreecommitdiffstats
path: root/src/imports/multimedia/qdeclarativecamera.cpp
blob: 626342cc6b764af8759dd35b1fbd414d0361eb2a (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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/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 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativecamera_p.h"
#include "qdeclarativecamerapreviewprovider_p.h"

#include "qdeclarativecameraexposure_p.h"
#include "qdeclarativecameraflash_p.h"
#include "qdeclarativetorch_p.h"

#include <private/qplatformmediaplayer_p.h>
#include <qobject.h>
#include <QMediaDeviceManager>
#include <QtQml/qqmlinfo.h>

#include <QtCore/QTimer>
#include <QtGui/qevent.h>

QT_BEGIN_NAMESPACE

void QDeclarativeCamera::_q_errorOccurred(QCamera::Error errorCode)
{
    emit errorOccurred(Error(errorCode), errorString());
    emit errorChanged();
}

/*!
    \qmltype Camera
    \instantiates QDeclarativeCamera
    \brief Access viewfinder frames, and take photos and movies.
    \ingroup multimedia_qml
    \ingroup camera_qml
    \inqmlmodule QtMultimedia

    \inherits QtObject

    You can use \c Camera to capture images and movies from a camera, and manipulate
    the capture and processing settings that get applied to the images.  To display the
    viewfinder you can use \l VideoOutput with the Camera set as the source.

    \qml
    Item {
        width: 640
        height: 360

        Camera {
            id: camera

            imageProcessing.whiteBalanceMode: CameraImageProcessing.WhiteBalanceFlash

            exposure {
                exposureCompensation: -1.0
                exposureMode: Camera.ExposurePortrait
            }

            flash.mode: Camera.FlashOn

            imageCapture {
                onImageCaptured: {
                    photoPreview.source = preview  // Show the preview in an Image
                }
            }
        }

        VideoOutput {
            source: camera
            anchors.fill: parent
            focus : visible // to receive focus and capture key events when visible
        }

        Image {
            id: photoPreview
        }
    }
    \endqml

    If multiple cameras are available, you can select which one to use by setting the \l deviceId
    property to a value from
    \l{QtMultimedia::QtMultimedia::availableCameras}{QtMultimedia.availableCameras}.
    On a mobile device, you can conveniently switch between front-facing and back-facing cameras
    by setting the \l position property.

    The various settings and functionality of the Camera stack is spread
    across a few different child properties of Camera.

    \table
    \header \li Property \li Description
    \row \li \l {CameraCapture} {imageCapture}
         \li Methods and properties for capturing still images.
    \row \li \l {CameraRecorder} {videoRecorder}
         \li Methods and properties for capturing movies.
    \row \li \l {CameraExposure} {exposure}
         \li Methods and properties for adjusting exposure (aperture, shutter speed etc).
    \row \li \l {CameraFocus} {focus}
         \li Methods and properties for adjusting focus and providing feedback on autofocus progress.
    \row \li \l {CameraFlash} {flash}
         \li Methods and properties for controlling the camera flash.
    \row \li \l {CameraImageProcessing} {imageProcessing}
         \li Methods and properties for adjusting camera image processing parameters.
    \endtable

    Basic camera state management, error reporting, and simple zoom properties are
    available in the Camera itself.  For integration with C++ code, the
    \l mediaSource property allows you to
    access the standard Qt Multimedia camera controls.

    Many of the camera settings may take some time to apply, and might be limited
    to certain supported values depending on the hardware.  Some camera settings may be
    set manually or automatically. These settings properties contain the current set value.
    For example, when autofocus is enabled the focus zones are exposed in the
    \l {CameraFocus}{focus} property.

    For additional information, read also the \l{Camera Overview}{camera overview}.
*/

/*!
    \class QDeclarativeCamera
    \internal
    \brief The QDeclarativeCamera class provides a camera item that you can add to a QQuickView.
*/

/*!
    Construct a declarative camera object using \a parent object.
 */
QDeclarativeCamera::QDeclarativeCamera(QObject *parent) :
    QObject(parent),
    m_camera(nullptr),
    m_componentComplete(false)
{
    m_currentCameraInfo = QMediaDeviceManager::defaultVideoInput();
    m_camera = new QCamera(m_currentCameraInfo);

    m_imageCapture = new QDeclarativeCameraCapture(&captureSession);
    m_videoRecorder = new QDeclarativeCameraRecorder(&captureSession);
    m_exposure = new QDeclarativeCameraExposure(m_camera);
    m_flash = new QDeclarativeCameraFlash(m_camera);
    m_torch = new QDeclarativeTorch(m_camera);

    connect(m_camera, &QCamera::activeChanged, this, &QDeclarativeCamera::activeChanged);
    connect(m_camera, SIGNAL(statusChanged(QCamera::Status)), this, SIGNAL(cameraStatusChanged()));
    connect(m_camera, SIGNAL(errorOccurred(QCamera::Error)), this, SLOT(_q_errorOccurred(QCamera::Error)));
}

/*! Destructor, clean up memory */
QDeclarativeCamera::~QDeclarativeCamera()
{
    // These must be deleted before QCamera
    delete m_imageCapture;
    delete m_videoRecorder;
    delete m_exposure;
    delete m_flash;

    delete m_camera;
}

void QDeclarativeCamera::classBegin()
{
}

void QDeclarativeCamera::componentComplete()
{
    m_componentComplete = true;
    setActive(pendingActive);
}

/*!
    \qmlproperty string QtMultimedia::Camera::deviceId

    This property holds the unique identifier for the camera device being used. It may not be human-readable.

    You can get all available device IDs from \l{QtMultimedia::QtMultimedia::availableCameras}{QtMultimedia.availableCameras}.
    If no value is provided or if set to an empty string, the system's default camera will be used.

    If possible, \l cameraState and other camera parameters are
    preserved when changing the camera device.

    \sa displayName, position
    \since 5.4
*/

QString QDeclarativeCamera::deviceId() const
{
    return QString::fromLatin1(m_currentCameraInfo.id());
}

void QDeclarativeCamera::setDeviceId(const QString &name)
{
    auto id = name.toLatin1();
    if (id == m_currentCameraInfo.id())
        return;

    setupDevice(name);
}

/*!
    \qmlproperty enumeration QtMultimedia::Camera::position

    This property holds the physical position of the camera on the hardware system.

    On a mobile device, this property can be used to easily choose between
    front-facing and back-facing cameras. If this property is set to
    \c Camera.UnspecifiedPosition, the system's default camera is used.

    If possible, \l cameraState and other camera
    parameters are preserved when changing the camera device.

    \value  Camera.UnspecifiedPosition
            The camera position is unspecified or unknown.
    \value  Camera.BackFace
            The camera is on the back face of the system hardware. For example,
            on a mobile device, it is on side opposite from the screen.
    \value  Camera.FrontFace
            The camera is on the front face of the system hardware. For example,
            on a mobile device, it means it is on the same side as the screen.
            Viewfinder frames of front-facing cameras are mirrored horizontally,
            so the users can see themselves as looking into a mirror. Captured
            images or videos are not mirrored.

    \sa deviceId
    \since 5.4
*/

QDeclarativeCamera::Position QDeclarativeCamera::position() const
{
    return QDeclarativeCamera::Position(m_currentCameraInfo.position());
}

void QDeclarativeCamera::setPosition(Position position)
{
    QCameraInfo::Position pos = QCameraInfo::Position(position);
    if (pos == m_currentCameraInfo.position())
        return;

    QByteArray id;

    if (pos != QCameraInfo::UnspecifiedPosition) {
        const QList<QCameraInfo> cameras = QMediaDeviceManager::videoInputs();
        for (auto c : cameras) {
            if (c.position() == pos) {
                id = c.id();
                break;
            }
        }
    }
    if (id.isEmpty())
        id = QMediaDeviceManager::defaultVideoInput().id();

    if (!id.isEmpty())
        setupDevice(QString::fromLatin1(id));
}

/*!
    \qmlproperty string QtMultimedia::Camera::displayName

    This property holds the human-readable name of the camera.

    You can use this property to display the name of the camera in a user interface.

    \readonly
    \sa deviceId
    \since 5.4
*/

QString QDeclarativeCamera::displayName() const
{
    return m_currentCameraInfo.description();
}

/*!
    \qmlproperty int QtMultimedia::Camera::orientation

    This property holds the physical orientation of the camera sensor.

    The value is the orientation angle (clockwise, in steps of 90 degrees) of the camera sensor in
    relation to the display in its natural orientation.

    For example, suppose a mobile device which is naturally in portrait orientation. The back-facing
    camera is mounted in landscape. If the top side of the camera sensor is aligned with the right
    edge of the screen in natural orientation, \c orientation returns \c 270. If the top side of a
    front-facing camera sensor is aligned with the right edge of the screen, \c orientation
    returns \c 90.

    \readonly
    \sa VideoOutput::orientation
    \since 5.4
*/

void QDeclarativeCamera::setupDevice(const QString &deviceName)
{
    QCameraInfo oldCameraInfo = m_currentCameraInfo;

    auto cameras = QMediaDeviceManager::videoInputs();
    QByteArray id = deviceName.toUtf8();
    QCameraInfo info;
    for (const auto &c : cameras) {
        if (c.id() == id) {
            info = c;
            break;
        }
    }
    m_currentCameraInfo = info;
    m_camera->setCameraInfo(info);

    emit deviceIdChanged();
    if (oldCameraInfo.description() != m_currentCameraInfo.description())
        emit displayNameChanged();
    if (oldCameraInfo.position() != m_currentCameraInfo.position())
        emit positionChanged();
}

/*!
    Returns any camera error.
    \sa QDeclarativeCameraError::Error
*/
QDeclarativeCamera::Error QDeclarativeCamera::errorCode() const
{
    return QDeclarativeCamera::Error(m_camera->error());
}

/*!
    \qmlproperty string QtMultimedia::Camera::errorString

    This property holds the last error string, if any.

    \sa errorOccurred, errorCode
*/
QString QDeclarativeCamera::errorString() const
{
    return m_camera->errorString();
}

/*!
    \qmlproperty enumeration QtMultimedia::Camera::isAvailable

    This property returns the availability of the camera.
 */
bool QDeclarativeCamera::isAvailable() const
{
    return m_camera->isAvailable();
}

/*!
    \qmlproperty bool QtMultimedia::Camera::active

    This property holds the camera object's current state. By default, the default
    camera is inactive.
*/
bool QDeclarativeCamera::isActive() const
{
    return m_componentComplete ? m_camera->isActive() : pendingActive;
}

/*!
    \qmlproperty enumeration QtMultimedia::Camera::cameraStatus

    This property holds the camera object's current status.

    \value  Camera.ActiveStatus
            The camera has been started and can produce data,
            viewfinder displays video frames.
            Depending on backend, changing camera settings such as
            capture mode, codecs, or resolution in \c {Camera.ActiveState} may
            lead to changing the status to \c LoadedStatus and \c StartingStatus
            while the settings are applied, and back to \c ActiveStatus when
            the camera is ready.
    \value  Camera.StartingStatus
            The camera is transitioning to \c {Camera.ActiveState}. The camera
            service is not ready to capture yet.
    \value  Camera.StoppingStatus
            The camera is transitioning from \c {Camera.ActiveState} to
            \c {Camera.InactiveState}.
    \value  Camera.InactiveStatus
            The camera is inactive.
    \value  Camera.UnavailableStatus
            The camera is not available.
*/
QDeclarativeCamera::Status QDeclarativeCamera::cameraStatus() const
{
    return QDeclarativeCamera::Status(m_camera->status());
}

void QDeclarativeCamera::setActive(bool active)
{
    if (!m_componentComplete) {
        pendingActive = active;
        return;
    }

    m_camera->setActive(active);
}

/*!
    \qmlmethod QtMultimedia::Camera::start()

    Starts the camera.  Viewfinder frames will
    be available and image or movie capture will
    be possible.
*/

/*!
    \qmlmethod QtMultimedia::Camera::stop()

    Stops the camera, but leaves the camera
    stack loaded.

    In this state, the camera still consumes power.
*/

/*!
    \qmlproperty variant QtMultimedia::Camera::mediaSource

    This property holds the native media object for the camera.

    It can be used to get a pointer to a QCamera object in order to integrate with C++ code.

    \code
        QObject *qmlCamera; // The QML Camera object
        QCamera *camera = qvariant_cast<QCamera *>(qmlCamera->property("mediaSource"));
    \endcode

    \note This property is not accessible from QML.
*/

/*!
    \qmlproperty enumeration QtMultimedia::Camera::errorCode

    This property holds the last error code.

    \value  Camera.NoError
            No errors have occurred.
    \value  Camera.CameraError
            An error has occurred.

    \sa errorOccurred, errorString
*/

/*!
    \qmlsignal QtMultimedia::Camera::error(errorCode, errorString)
    \obsolete

    Use errorOccurred() instead.
*/

/*!
    \qmlsignal QtMultimedia::Camera::errorOccurred(errorCode, errorString)
    \since 5.15

    This signal is emitted when an error specified by \a errorCode occurs.
    A descriptive string value is available in \a errorString.

    The corresponding handler is \c onError.

    \sa errorCode, errorString
*/

/*!
    \qmlsignal Camera::activeChanged(active)

    This signal is emitted when the camera state has changed to \a active. Since the
    state changes may take some time to occur this signal may arrive sometime
    after the state change has been requested.

    The corresponding handler is \c onActiveChanged.
*/

/*!
    \qmlsignal Camera::opticalZoomChanged(zoom)

    This signal is emitted when the optical zoom setting has changed to \a zoom.

    The corresponding handler is \c onOpticalZoomChanged.
*/

/*!
    \qmlsignal Camera::digitalZoomChanged(zoom)

    This signal is emitted when the digital zoom setting has changed to \a zoom.

    The corresponding handler is \c onDigitalZoomChanged.
*/

/*!
    \qmlsignal Camera::maximumOpticalZoomChanged(zoom)

    This signal is emitted when the maximum optical zoom setting has
    changed to \a zoom.  This can occur when you change between video
    and still image capture modes, or the capture settings are changed.

    The corresponding handler is \c onMaximumOpticalZoomChanged.
*/

/*!
    \qmlsignal Camera::maximumDigitalZoomChanged(zoom)

    This signal is emitted when the maximum digital zoom setting has
    changed to \a zoom.  This can occur when you change between video
    and still image capture modes, or the capture settings are changed.

    The corresponding handler is \c onMaximumDigitalZoomChanged.
*/

/*!
    \qmlmethod list<size> QtMultimedia::Camera::supportedViewfinderResolutions(real minimumFrameRate, real maximumFrameRate)

    Returns a list of supported viewfinder resolutions.

    If both optional parameters \a minimumFrameRate and \a maximumFrameRate are specified, the
    returned list is reduced to resolutions supported for the given frame rate range.

    The camera must be loaded before calling this function, otherwise the returned list
    is empty.

    \sa {QtMultimedia::Camera::viewfinder}{viewfinder}

    \since 5.5
*/
QJSValue QDeclarativeCamera::supportedResolutions(qreal minimumFrameRate, qreal maximumFrameRate)
{
    QQmlEngine *engine = qmlEngine(this);

    QCameraInfo info = m_camera->cameraInfo();

    const auto formats = info.videoFormats();
    QJSValue supportedResolutions = engine->newArray(formats.count());
    int i = 0;
    for (const auto &f : formats) {
        if (maximumFrameRate >= 0) {
            if (f.maxFrameRate() < minimumFrameRate ||
                f.minFrameRate() > maximumFrameRate)
                continue;
        }
        QJSValue size = engine->newObject();
        QSize resolution = f.resolution();
        size.setProperty(QStringLiteral("width"), resolution.width());
        size.setProperty(QStringLiteral("height"), resolution.height());
        supportedResolutions.setProperty(i++, size);
    }

    return supportedResolutions;
}

/*!
    \qmlmethod list<object> QtMultimedia::Camera::supportedViewfinderFrameRateRanges(size resolution)

    Returns a list of supported viewfinder frame rate ranges.

    Each range object in the list has the \c minimumFrameRate and \c maximumFrameRate properties.

    If the optional parameter \a resolution is specified, the returned list is reduced to frame rate
    ranges supported for the given \a resolution.

    The camera must be loaded before calling this function, otherwise the returned list
    is empty.

    \sa {QtMultimedia::Camera::viewfinder}{viewfinder}

    \since 5.5
*/
QJSValue QDeclarativeCamera::supportedFrameRateRanges(const QJSValue &resolution)
{
    QQmlEngine *engine = qmlEngine(this);

    QSize res;
    if (!resolution.isUndefined()) {
        QJSValue width = resolution.property(QStringLiteral("width"));
        QJSValue height = resolution.property(QStringLiteral("height"));
        if (width.isNumber() && height.isNumber())
            res = QSize(width.toInt(), height.toInt());
    }
    QCameraInfo info = m_camera->cameraInfo();

    float min = 0.;
    float max = 1.e6;
    const auto formats = info.videoFormats();
    QJSValue supportedResolutions = engine->newArray(formats.count());
    for (const auto &f : formats) {
        if (!res.isValid() || f.resolution() == res) {
            min = qMin(min, f.minFrameRate());
            max = qMin(max, f.maxFrameRate());
        }
    }

    if (max == 1.e6)
        min = max = 0.;

    // ### change Qt 5 semantics and not return an array????
    QJSValue supportedFrameRateRanges = engine->newArray(1);
    QJSValue range = engine->newObject();
    range.setProperty(QStringLiteral("minimumFrameRate"), min);
    range.setProperty(QStringLiteral("maximumFrameRate"), max);
    supportedFrameRateRanges.setProperty(0, range);

    return supportedFrameRateRanges;
}

QT_END_NAMESPACE

#include "moc_qdeclarativecamera_p.cpp"