6#include <QtConcurrent/QtConcurrentRun>
7#include <QtCore/QFileInfo>
8#include <QtCore/QPointer>
9#include <QtCore/QTimer>
10#include <QtMultimedia/QCamera>
11#include <QtMultimedia/QCameraDevice>
12#include <QtMultimedia/QImageCapture>
13#include <QtMultimedia/QMediaCaptureSession>
14#include <QtMultimedia/QMediaDevices>
15#include <QtMultimedia/QVideoFrame>
16#include <QtMultimedia/QVideoSink>
17#include <QtQuick/QQuickItem>
31#if defined(Q_OS_ANDROID) || defined(Q_OS_DARWIN)
32constexpr bool kStillPhotos =
true;
34constexpr bool kStillPhotos =
false;
41#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
42constexpr bool kExposureAndFocusControls =
false;
44constexpr bool kExposureAndFocusControls =
true;
47constexpr QCamera::WhiteBalanceMode kWhiteBalancePresets[] = {
48 QCamera::WhiteBalanceSunlight, QCamera::WhiteBalanceCloudy, QCamera::WhiteBalanceShade,
49 QCamera::WhiteBalanceTungsten, QCamera::WhiteBalanceFluorescent, QCamera::WhiteBalanceFlash,
50 QCamera::WhiteBalanceSunset,
58 , _mediaDevices(new QMediaDevices(this))
59 , _retryTimer(new QTimer(this))
60 , _imageCapture(new QImageCapture(this))
66 (void) connect(_imageCapture, &QImageCapture::imageAvailable,
this, &UVCCameraController::_onImageAvailable);
68 _imageCapture, &QImageCapture::errorOccurred,
this,
69 [
this](
int id, QImageCapture::Error,
const QString& errorString) { _onImageCaptureError(
id, errorString); });
70 _retryTimer->setSingleShot(
true);
72 (void) connect(_retryTimer, &QTimer::timeout,
this, &UVCCameraController::_recreateCamera);
76 if (_monitor->stats().valid) {
89 qCDebug(UVCCameraControllerLog) <<
"device" <<
device();
95 qCDebug(UVCCameraControllerLog) <<
"active" <<
active();
105 if (_gaveUp || _retryTimer->isActive()) {
117 _recorder->stopAndWait();
121void UVCCameraController::_startOver()
130 if (
name == _formatName) {
133 qCDebug(UVCCameraControllerLog) <<
"format" <<
name;
142 (void) connect(_mediaDevices, &QMediaDevices::videoInputsChanged,
this, &UVCCameraController::_onVideoInputsChanged,
143 Qt::UniqueConnection);
160 (void) QMetaObject::invokeMethod(
162 [
this, output = QPointer<QQuickItem>(
videoOutput)] {
167 Qt::QueuedConnection);
172 qCDebug(UVCCameraControllerLog) <<
"video output" <<
videoOutput();
173 _connectVideoOutput();
178 if (_recorder->active()) {
179 qCWarning(UVCCameraControllerLog) <<
"Not recording the camera to" << file <<
"- recording already";
183 qCWarning(UVCCameraControllerLog) <<
"Can't record the camera now:" << file;
195bool UVCCameraController::_running()
const
197 return _camera && _camera->isActive() &&
videoSink();
221 return _camera && std::ranges::any_of(kWhiteBalancePresets, [
this](QCamera::WhiteBalanceMode mode) {
222 return _camera->isWhiteBalanceModeSupported(mode);
228 return _camera ? _camera->minimumZoomFactor() : 1.;
233 return _camera ? std::max(_camera->maximumZoomFactor(), _camera->minimumZoomFactor()) : 1.;
238 return kExposureAndFocusControls && _camera &&
239 _camera->supportedFeatures().testFlag(QCamera::Feature::ExposureCompensation);
244 return kExposureAndFocusControls && _camera && _camera->isFocusModeSupported(QCamera::FocusModeInfinity);
247void UVCCameraController::_applyControls()
253 _camera->setWhiteBalanceMode(_controls.whiteBalance);
258 _camera->setExposureCompensation(_controls.exposureCompensation);
260 if (
focusAdjustable() && _camera->isFocusModeSupported(_controls.focusMode)) {
261 _camera->setFocusMode(_controls.focusMode);
267 const int id = (_running() && _imageCapture->isReadyForCapture()) ? _imageCapture->capture() : -1;
271 qCDebug(UVCCameraControllerLog) <<
"photo" <<
id << file;
272 _photoFiles.insert(
id, {file, exif});
276void UVCCameraController::_onImageAvailable(
int id,
const QVideoFrame& frame)
278 const PendingPhoto photo = _photoFiles.take(
id);
279 if (photo.file.isEmpty()) {
282 _savePhoto(frame, photo);
285void UVCCameraController::_onImageCaptureError(
int id,
const QString& errorString)
287 const PendingPhoto photo = _photoFiles.take(
id);
288 qCWarning(UVCCameraControllerLog) <<
"Photo capture failed:" <<
id << photo.file << errorString;
289 if (!photo.file.isEmpty()) {
290 _savePhotoOnDisplay(photo);
294void UVCCameraController::_savePhotoOnDisplay(
const PendingPhoto& photo)
298 qCWarning(UVCCameraControllerLog) <<
"No video on display to take the photo from:" << photo.file;
299 emit
errorOccurred(tr(
"Unable to take a photo: no video is on display."));
303void UVCCameraController::_savePhoto(
const QVideoFrame& frame,
const PendingPhoto& photo)
306 (void) QtConcurrent::run([frame, photo,
rotation = _rotation,
mirrored = _mirrored] {
308 }).then(
this, [
this, file = photo.file](
bool saved) {
310 emit errorOccurred(tr(
"Unable to save the photo %1.").arg(QFileInfo(file).fileName()));
315void UVCCameraController::_createCamera()
317 const QString deviceName =
active() ?
device() : QString();
324 if (deviceName.isEmpty()) {
328 qCWarning(UVCCameraControllerLog) <<
"No camera named" << deviceName;
336 _camera =
new QCamera(
device,
this);
338 qCDebug(UVCCameraControllerLog) <<
"camera format" << _formatName;
339 _camera->setCameraFormat(
format);
341 (void) connect(_camera, &QCamera::errorOccurred,
this,
342 [
this](QCamera::Error,
const QString& errorString) { _onCameraError(errorString); });
347 (void) connect(_camera, &QCamera::activeChanged,
this, [
this](
bool active) {
354 _captureSession =
new QMediaCaptureSession(
this);
355 _captureSession->setCamera(_camera);
356 _captureSession->setRecorder(_recorder->mediaRecorder());
358 _captureSession->setImageCapture(_imageCapture);
362void UVCCameraController::_releaseCamera()
365 for (
const PendingPhoto& photo : std::exchange(_photoFiles, {})) {
366 _savePhotoOnDisplay(photo);
369 delete _captureSession;
370 _captureSession =
nullptr;
374 _framesArriving =
false;
378void UVCCameraController::_recreateCamera()
383 _connectVideoOutput();
386void UVCCameraController::_connectVideoOutput()
389 (void) disconnect(_frameConnection);
391 _frameConnection = connect(sink, &QVideoSink::videoFrameChanged,
this, &UVCCameraController::_onVideoFrame);
393 _framesArriving =
false;
395 if (_captureSession) {
396 _captureSession->setVideoSink(sink);
398 if (_camera && sink) {
399 _monitor->attach(_camera, sink);
404 _camera->setActive(sink !=
nullptr);
409void UVCCameraController::_onVideoFrame(
const QVideoFrame& frame)
412 if (!_camera || !
frame.isValid()) {
416 if (!_framesArriving) {
417 _framesArriving =
true;
422void UVCCameraController::_updateState()
425 if (_retryTimer->isActive()) {
427 }
else if (_camera && !_gaveUp &&
videoSink()) {
434void UVCCameraController::_onCameraError(
const QString& errorString)
436 qCWarning(UVCCameraControllerLog) <<
"Camera error:" <<
device() << errorString <<
"retries" << _retries;
437 _framesArriving =
false;
447 _retryTimer->start();
452void UVCCameraController::_onVideoInputsChanged()
454 if (!_cameraId.isEmpty() && !_cameraAttached()) {
456 qCWarning(UVCCameraControllerLog) <<
"Camera unplugged:" <<
device() << _cameraId;
460 }
else if (
active() && !_camera && _cameraAttached()) {
467bool UVCCameraController::_cameraAttached()
const
469 if (_cameraId.isEmpty()) {
472 const QList<QCameraDevice> cameras = QMediaDevices::videoInputs();
473 return std::any_of(cameras.cbegin(), cameras.cend(),
474 [
this](
const QCameraDevice& camera) { return camera.id() == _cameraId; });
#define QGC_LOGGING_CATEGORY(name, categoryStr)
void recordingChanged(bool recording)
static QMediaFormat::FileFormat container(VideoReceiver::FileFormat format)
The container of format.
void recordingFinished(const QString &file, const QString &error)
error is empty for a recording that finished normally.
void recordingStarted(const QString &file)
void onStartRecording(const QString &file, FileFormat format) override
void setControls(const Controls &controls)
Applies controls to the camera, and to each camera from now on as it starts.
UVCCameraController(QObject *parent=nullptr)
bool focusAdjustable() const
qreal maximumZoom() const
void setTransform(QtVideo::Rotation rotation, bool mirrored)
static constexpr std::chrono::seconds kRetryInterval
void onConfigChanged() override
void onStopRecording() override
QString device() const
The selected camera's description, the config's URI; empty while none is.
void controlsChanged()
The camera's adjustable controls, or its zoom range, changed.
const Controls & controls() const
void onActiveChanged() override
bool whiteBalanceAdjustable() const
Whether the camera has a white balance besides automatic.
Q_INVOKABLE void unregisterVideoOutput(QQuickItem *videoOutput)
void setFormat(const QString &name)
Runs the camera in format name, recreating it: not every platform switches a running camera's format.
void onReconnectRequested() override
~UVCCameraController() override
Q_INVOKABLE void registerVideoOutput(QQuickItem *videoOutput)
void onRestartRequested() override
qreal minimumZoom() const
The camera's zoom range; both 1 for a camera that doesn't zoom, or without a camera.
void watchCameras()
Emits camerasChanged() from now on when a camera is plugged in or unplugged.
bool onTakeScreenshot(const QString &file, const VideoScreenshot::Exif &exif) override
QStringList formats() const
The formats the selected camera offers, as UVCDevices::formatNames(); empty without a camera.
bool exposureAdjustable() const
void camerasChanged()
A camera was plugged in or unplugged.
static constexpr int kMaxRetries
void onVideoOutputChanged() override
Also called when the current output is set again.
void setVideoSize(QSize size)
QQuickItem * videoOutput() const
void setVideoOutput(QQuickItem *videoOutput)
VideoReceiver(QObject *parent=nullptr)
void setStats(const VideoStreamStats &stats)
Backends publish a new measurement, and an invalid one once the stream stops or reconnects.
QVideoSink * videoSink() const
The VideoOutput's QVideoSink, or nullptr.
void recordingFinished(const QString &file, const QString &error)
A recording file closed. error is empty when the file was finalized cleanly.
static QSize presentedSize(const QVideoFrame &frame, QSize pictureSize={})
FileFormat
Values are persisted by VideoSettings::recordingFormat.
void recordingStarted(const QString &file)
A recording file opened: the first one after startRecording(), or the recording's next part.
void setDecoding(bool decoding)
const RecordingEncoding & recordingEncoding() const
void setRecording(bool recording)
void setState(State state)
@ Reconnecting
Waiting out the backoff after a failure.
@ Streaming
Data is arriving.
@ Stopped
Inactive, no URI, or given up after a failure (autoReconnect off).
@ Connecting
Pipeline running, no data yet.
void errorOccurred(const QString &message)
virtual bool onTakeScreenshot(const QString &file, const VideoScreenshot::Exif &exif)
takeScreenshot() with an output set: saves the frame on display, unless overridden.
std::optional< Frame > frame(std::string_view text)
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
QStringList formatNames(const QCameraDevice &device)
void requestPermission(QObject *context, std::function< void()> granted)
QCameraDevice device(const QString &description)
The attached camera of description description; a null device when none is.
QCameraFormat format(const QCameraDevice &device, const QString &name)
The format of device that formatName() calls name; a null format for none.
bool deviceExists(const QString &description)
bool save(const QVideoFrame &frame, const QString &file, const Exif &exif={}, QtVideo::Rotation outputRotation=QtVideo::Rotation::None, bool outputMirrored=false)
displayedImage() of frame, then saveImage().