QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
UVCCameraController.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <utility>
5
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>
18
19#include "AppMessages.h"
20#include "QGCLoggingCategory.h"
21#include "UVCDevices.h"
22#include "UVCStreamMonitor.h"
23#include "VideoScreenshot.h"
24
25QGC_LOGGING_CATEGORY(UVCCameraControllerLog, "Video.UVCCameraController")
26
27namespace {
28
29// Qt takes still photos with Android's and Apple's cameras. With the others QImageCapture converts the camera's next
30// frame on the camera's thread, the GUI thread for a V4L2 camera, so the photo is the frame on display instead.
31#if defined(Q_OS_ANDROID) || defined(Q_OS_DARWIN)
32constexpr bool kStillPhotos = true;
33#else
34constexpr bool kStillPhotos = false;
35#endif
36
37// Qt defect, seen in Qt 6.12.0: QV4L2Camera::initV4L2Controls() reads the focus range into the exposure compensation
38// range and never sets its focus range (qtmultimedia/src/plugins/multimedia/ffmpeg/qv4l2camera.cpp), so neither
39// control does what it is asked. Fixed after 6.12.0 by qtmultimedia b7f6f39957 (6.12 branch): remove this constant and
40// its two uses once the minimum Qt has that fix.
41#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
42constexpr bool kExposureAndFocusControls = false;
43#else
44constexpr bool kExposureAndFocusControls = true;
45#endif
46
47constexpr QCamera::WhiteBalanceMode kWhiteBalancePresets[] = {
48 QCamera::WhiteBalanceSunlight, QCamera::WhiteBalanceCloudy, QCamera::WhiteBalanceShade,
49 QCamera::WhiteBalanceTungsten, QCamera::WhiteBalanceFluorescent, QCamera::WhiteBalanceFlash,
50 QCamera::WhiteBalanceSunset,
51};
52
53} // namespace
54
56 : VideoReceiver(parent)
57 , _monitor(new UVCStreamMonitor(this))
58 , _mediaDevices(new QMediaDevices(this))
59 , _retryTimer(new QTimer(this))
60 , _imageCapture(new QImageCapture(this))
61 , _recorder(new QtVideoRecorder(this))
62{
66 (void) connect(_imageCapture, &QImageCapture::imageAvailable, this, &UVCCameraController::_onImageAvailable);
67 (void) connect(
68 _imageCapture, &QImageCapture::errorOccurred, this,
69 [this](int id, QImageCapture::Error, const QString& errorString) { _onImageCaptureError(id, errorString); });
70 _retryTimer->setSingleShot(true);
71 _retryTimer->setInterval(kRetryInterval);
72 (void) connect(_retryTimer, &QTimer::timeout, this, &UVCCameraController::_recreateCamera);
73 (void) connect(_monitor, &UVCStreamMonitor::statsChanged, this, [this] {
74 setStats(_monitor->stats());
75 // Frames flowing again end a run of retries.
76 if (_monitor->stats().valid) {
77 _retries = 0;
78 }
79 });
80}
81
83{
84 _releaseCamera();
85}
86
88{
89 qCDebug(UVCCameraControllerLog) << "device" << device();
90 _startOver();
91}
92
94{
95 qCDebug(UVCCameraControllerLog) << "active" << active();
96 if (!active()) {
97 _recorder->stop();
98 }
99 _startOver();
100}
101
103{
104 // A camera that runs has no display sink to rebuild, and a new one would end its recording.
105 if (_gaveUp || _retryTimer->isActive()) {
106 _startOver();
107 }
108}
109
111{
112 // The retry keeps to its timer: a USB camera doesn't come back with a vehicle's link.
113}
114
116{
117 _recorder->stopAndWait();
119}
120
121void UVCCameraController::_startOver()
122{
123 _retryTimer->stop();
124 _retries = 0;
125 _recreateCamera();
126}
127
129{
130 if (name == _formatName) {
131 return;
132 }
133 qCDebug(UVCCameraControllerLog) << "format" << name;
134 _formatName = name;
135 if (_camera) {
136 _recreateCamera();
137 }
138}
139
141{
142 (void) connect(_mediaDevices, &QMediaDevices::videoInputsChanged, this, &UVCCameraController::_onVideoInputsChanged,
143 Qt::UniqueConnection);
144}
145
147{
148 // Not for the output already set: the camera has nothing to bind anew, and its measurements would start over.
149 if (videoOutput && (videoOutput != this->videoOutput())) {
150 setVideoOutput(videoOutput);
151 }
152}
153
155{
156 if (!videoOutput || (videoOutput != this->videoOutput())) {
157 return;
158 }
159 // Queued: the output that takes this one's place, in the main picture or in a tile, registers in the same pass.
160 (void) QMetaObject::invokeMethod(
161 this,
162 [this, output = QPointer<QQuickItem>(videoOutput)] {
163 if (output == this->videoOutput()) {
164 setVideoOutput(nullptr);
165 }
166 },
167 Qt::QueuedConnection);
168}
169
171{
172 qCDebug(UVCCameraControllerLog) << "video output" << videoOutput();
173 _connectVideoOutput();
174}
175
177{
178 if (_recorder->active()) {
179 qCWarning(UVCCameraControllerLog) << "Not recording the camera to" << file << "- recording already";
180 return;
181 }
182 if (!_running()) {
183 qCWarning(UVCCameraControllerLog) << "Can't record the camera now:" << file;
184 emit recordingFinished(file, tr("The USB camera isn't running"));
185 return;
186 }
187 _recorder->start(file, QtVideoRecorder::container(format), recordingEncoding().codec, recordingEncoding().quality);
188}
189
191{
192 _recorder->stop();
193}
194
195bool UVCCameraController::_running() const
196{
197 return _camera && _camera->isActive() && videoSink();
198}
199
201{
202 if ((rotation == _rotation) && (mirrored == _mirrored)) {
203 return;
204 }
205 _rotation = rotation;
206 _mirrored = mirrored;
207 emit transformChanged();
208}
209
211{
212 if (controls == _controls) {
213 return;
214 }
215 _controls = controls;
216 _applyControls();
217}
218
220{
221 return _camera && std::ranges::any_of(kWhiteBalancePresets, [this](QCamera::WhiteBalanceMode mode) {
222 return _camera->isWhiteBalanceModeSupported(mode);
223 });
224}
225
227{
228 return _camera ? _camera->minimumZoomFactor() : 1.;
229}
230
232{
233 return _camera ? std::max(_camera->maximumZoomFactor(), _camera->minimumZoomFactor()) : 1.;
234}
235
237{
238 return kExposureAndFocusControls && _camera &&
239 _camera->supportedFeatures().testFlag(QCamera::Feature::ExposureCompensation);
240}
241
243{
244 return kExposureAndFocusControls && _camera && _camera->isFocusModeSupported(QCamera::FocusModeInfinity);
245}
246
247void UVCCameraController::_applyControls()
248{
249 if (!_camera) {
250 return;
251 }
252 // QCamera leaves a white balance or focus mode the camera lacks as it is.
253 _camera->setWhiteBalanceMode(_controls.whiteBalance);
254 if (maximumZoom() > minimumZoom()) {
255 _camera->setZoomFactor(std::clamp(static_cast<qreal>(_controls.zoom), minimumZoom(), maximumZoom()));
256 }
257 if (exposureAdjustable()) {
258 _camera->setExposureCompensation(_controls.exposureCompensation);
259 }
260 if (focusAdjustable() && _camera->isFocusModeSupported(_controls.focusMode)) {
261 _camera->setFocusMode(_controls.focusMode);
262 }
263}
264
266{
267 const int id = (_running() && _imageCapture->isReadyForCapture()) ? _imageCapture->capture() : -1;
268 if (id < 0) {
269 return VideoReceiver::onTakeScreenshot(file, exif);
270 }
271 qCDebug(UVCCameraControllerLog) << "photo" << id << file;
272 _photoFiles.insert(id, {file, exif});
273 return true;
274}
275
276void UVCCameraController::_onImageAvailable(int id, const QVideoFrame& frame)
277{
278 const PendingPhoto photo = _photoFiles.take(id);
279 if (photo.file.isEmpty()) {
280 return;
281 }
282 _savePhoto(frame, photo);
283}
284
285void UVCCameraController::_onImageCaptureError(int id, const QString& errorString)
286{
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);
291 }
292}
293
294void UVCCameraController::_savePhotoOnDisplay(const PendingPhoto& photo)
295{
296 // Not takeScreenshot(), which would ask for another capture.
297 if (!videoSink() || !VideoReceiver::onTakeScreenshot(photo.file, photo.exif)) {
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."));
300 }
301}
302
303void UVCCameraController::_savePhoto(const QVideoFrame& frame, const PendingPhoto& photo)
304{
305 // Converting and encoding a full-resolution photo would stall the UI.
306 (void) QtConcurrent::run([frame, photo, rotation = _rotation, mirrored = _mirrored] {
307 return VideoScreenshot::save(frame, photo.file, photo.exif, rotation, mirrored);
308 }).then(this, [this, file = photo.file](bool saved) {
309 if (!saved) {
310 emit errorOccurred(tr("Unable to save the photo %1.").arg(QFileInfo(file).fileName()));
311 }
312 });
313}
314
315void UVCCameraController::_createCamera()
316{
317 const QString deviceName = active() ? device() : QString();
318 const QCameraDevice device = UVCDevices::device(deviceName);
319 const QStringList formats = UVCDevices::formatNames(device);
320 if (formats != _formats) {
321 _formats = formats;
322 emit formatsChanged();
323 }
324 if (deviceName.isEmpty()) {
325 return;
326 }
327 if (device.isNull()) {
328 qCWarning(UVCCameraControllerLog) << "No camera named" << deviceName;
329 return;
330 }
331
332 // Until the user grants the permission, Qt's Android and Apple cameras refuse to start, without an error: the
333 // camera starts once it is granted.
334 UVCDevices::requestPermission(this, [this] { _connectVideoOutput(); });
335 _cameraId = device.id();
336 _camera = new QCamera(device, this);
337 if (const QCameraFormat format = UVCDevices::format(device, _formatName); !format.isNull()) {
338 qCDebug(UVCCameraControllerLog) << "camera format" << _formatName;
339 _camera->setCameraFormat(format);
340 }
341 (void) connect(_camera, &QCamera::errorOccurred, this,
342 [this](QCamera::Error, const QString& errorString) { _onCameraError(errorString); });
343 // Some platforms know what a camera supports, or take its settings, only once it runs.
344 (void) connect(_camera, &QCamera::supportedFeaturesChanged, this, &UVCCameraController::controlsChanged);
345 (void) connect(_camera, &QCamera::minimumZoomFactorChanged, this, &UVCCameraController::controlsChanged);
346 (void) connect(_camera, &QCamera::maximumZoomFactorChanged, this, &UVCCameraController::controlsChanged);
347 (void) connect(_camera, &QCamera::activeChanged, this, [this](bool active) {
348 if (active) {
349 _applyControls();
350 emit controlsChanged();
351 }
352 });
353 _applyControls();
354 _captureSession = new QMediaCaptureSession(this);
355 _captureSession->setCamera(_camera);
356 _captureSession->setRecorder(_recorder->mediaRecorder());
357 if (kStillPhotos) {
358 _captureSession->setImageCapture(_imageCapture);
359 }
360}
361
362void UVCCameraController::_releaseCamera()
363{
364 // The capture session's photos still pending won't come: save the frame on display instead.
365 for (const PendingPhoto& photo : std::exchange(_photoFiles, {})) {
366 _savePhotoOnDisplay(photo);
367 }
368 _monitor->detach();
369 delete _captureSession;
370 _captureSession = nullptr;
371 delete _camera;
372 _camera = nullptr;
373 _cameraId.clear();
374 _framesArriving = false;
375 _gaveUp = false;
376}
377
378void UVCCameraController::_recreateCamera()
379{
380 _releaseCamera();
381 _createCamera();
382 emit controlsChanged();
383 _connectVideoOutput();
384}
385
386void UVCCameraController::_connectVideoOutput()
387{
388 QVideoSink* const sink = videoSink();
389 (void) disconnect(_frameConnection);
390 if (sink) {
391 _frameConnection = connect(sink, &QVideoSink::videoFrameChanged, this, &UVCCameraController::_onVideoFrame);
392 } else {
393 _framesArriving = false;
394 }
395 if (_captureSession) {
396 _captureSession->setVideoSink(sink);
397 }
398 if (_camera && sink) {
399 _monitor->attach(_camera, sink);
400 } else {
401 _monitor->detach();
402 }
403 if (_camera) {
404 _camera->setActive(sink != nullptr);
405 }
406 _updateState();
407}
408
409void UVCCameraController::_onVideoFrame(const QVideoFrame& frame)
410{
411 // The sink clears the display with an invalid frame when the camera stops.
412 if (!_camera || !frame.isValid()) {
413 return;
414 }
416 if (!_framesArriving) {
417 _framesArriving = true;
418 _updateState();
419 }
420}
421
422void UVCCameraController::_updateState()
423{
425 if (_retryTimer->isActive()) {
427 } else if (_camera && !_gaveUp && videoSink()) {
428 state = _framesArriving ? State::Streaming : State::Connecting;
429 }
432}
433
434void UVCCameraController::_onCameraError(const QString& errorString)
435{
436 qCWarning(UVCCameraControllerLog) << "Camera error:" << device() << errorString << "retries" << _retries;
437 _framesArriving = false;
438 if (_retries >= kMaxRetries) {
439 _gaveUp = true;
440 QGC::showAppMessage(tr("USB camera %1: %2").arg(device(), errorString));
441 } else {
442 if (_retries == 0) {
443 QGC::showAppMessage(tr("USB camera %1: %2. Retrying.").arg(device(), errorString));
444 }
445 ++_retries;
446 // Deferred: the camera emitting this error can't be deleted from its own signal.
447 _retryTimer->start();
448 }
449 _updateState();
450}
451
452void UVCCameraController::_onVideoInputsChanged()
453{
454 if (!_cameraId.isEmpty() && !_cameraAttached()) {
455 // Qt stops an unplugged camera without an error.
456 qCWarning(UVCCameraControllerLog) << "Camera unplugged:" << device() << _cameraId;
457 QGC::showAppMessage(tr("USB camera %1 was disconnected").arg(device()));
458 // Runs another camera of the same name, if one is attached.
459 _recreateCamera();
460 } else if (active() && !_camera && _cameraAttached()) {
461 // Plugged back in.
462 _recreateCamera();
463 }
464 emit camerasChanged();
465}
466
467bool UVCCameraController::_cameraAttached() const
468{
469 if (_cameraId.isEmpty()) {
471 }
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; });
475}
#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)
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
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.
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
State state() const
void setVideoOutput(QQuickItem *videoOutput)
virtual void shutDown()
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={})
QString name() const
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.
bool active() const
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.
Definition AppMessages.cc:9
QStringList formatNames(const QCameraDevice &device)
Definition UVCDevices.cc:60
void requestPermission(QObject *context, std::function< void()> granted)
Definition UVCDevices.cc:89
QCameraDevice device(const QString &description)
The attached camera of description description; a null device when none is.
Definition UVCDevices.cc:21
QCameraFormat format(const QCameraDevice &device, const QString &name)
The format of device that formatName() calls name; a null format for none.
Definition UVCDevices.cc:78
bool deviceExists(const QString &description)
Definition UVCDevices.cc:33
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().