QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
VideoManager.cc
Go to the documentation of this file.
1#include "VideoManager.h"
2
3#include <algorithm>
4#include <optional>
5
6#include <QtConcurrent/QtConcurrentRun>
7#include <QtCore/QApplicationStatic>
8#include <QtCore/QCoreApplication>
9#include <QtCore/QDateTime>
10#include <QtCore/QScopedValueRollback>
11#include <QtCore/QUrl>
12#include <QtGui/QGuiApplication>
13
14#include "AppMessages.h"
15#include "AppSettings.h"
16#include "Fact.h"
18#include "MultiVehicleManager.h"
19#include "QGCCameraManager.h"
20#include "QGCCorePlugin.h"
21#include "QGCLoggingCategory.h"
22#include "QGCVideoStreamInfo.h"
23#include "QmlObjectListModel.h"
25#include "QtVideoRecorder.h"
26#include "SettingsManager.h"
27#include "UVCCameraController.h"
28#include "UVCDevices.h"
29#include "UVCStreamMonitor.h"
30#include "Vehicle.h"
31#include "VehicleLinkManager.h"
32#include "VideoBackend.h"
33#include "VideoReceiver.h"
35#include "VideoSettings.h"
37#include "VideoStreamResolver.h"
38#include "VideoStreamUri.h"
40
41#if defined(Q_OS_ANDROID)
42#include "AndroidInterface.h"
43#endif
44
45QGC_LOGGING_CATEGORY(VideoManagerLog, "Video.VideoManager")
46
47namespace {
48
49// What VideoSettings::maxVideoTiles allows: as many tiles as fit beside the main picture.
50constexpr uint kMaxVideoTiles = 4;
51
54VideoReceiver::RecordingEncoding recordingEncodingSetting(VideoSettings* videoSettings)
55{
56 return {.codec = QtVideoRecorder::recordingCodec(videoSettings->uvcRecordingCodec()->rawValue().toString()),
57 .quality = QtVideoRecorder::recordingQuality(videoSettings->uvcRecordingQuality()->rawValue().toInt())};
58}
59
61QString streamAddress(const QString& uri)
62{
63 const QUrl url(uri);
64 const std::optional<VideoStreamUri::Transport> transport = VideoStreamUri::transportFor(url);
65 return (transport && VideoStreamUri::listens(*transport)) ? QStringLiteral("udp:%1").arg(url.port()) : uri;
66}
67
69QList<MavlinkCameraControlInterface*> vehicleCameras(QGCCameraManager* cameraManager)
70{
71 QList<MavlinkCameraControlInterface*> cameras;
72 QmlObjectListModel* const model = cameraManager->cameras();
73 for (int i = 0; i < model->count(); ++i) {
74 if (auto* const camera = qobject_cast<MavlinkCameraControlInterface*>(model->get(i))) {
75 cameras.append(camera);
76 }
77 }
78 return cameras;
79}
80
81} // namespace
82
83Q_APPLICATION_STATIC(VideoManager, _videoManagerInstance);
84
86 : QObject(parent)
87 , _videoSettings(SettingsManager::instance()->videoSettings())
88 , _uvcCamera(new UVCCameraController(this))
89 , _primaryStream(new VideoStreamController(VideoStreamController::Role::Primary, _videoSettings, this))
90 , _thermalStream(new VideoStreamController(VideoStreamController::Role::Thermal, _videoSettings, this))
91 , _cameraSource(new VideoStreamController(VideoStreamController::Role::Camera, _videoSettings, this, _uvcCamera))
92 , _sources{_primaryStream, _thermalStream, _cameraSource}
93 , _measuredSource(_primaryStream)
94 , _recordingService(new VideoRecordingService(_sources, this))
95 , _telemetryOverlay(new VideoTelemetryOverlay(_videoSettings->showTelemetryOverlay(), this))
96 , _receiverFactory([this](QObject* owner) -> VideoReceiver* {
97 if (_videoSettings->videoBackend()->rawValue().toInt() == VideoSettings::VideoBackendQtMultimedia) {
98 return new QtMultimediaVideoReceiver(owner);
99 }
100 return QGCCorePlugin::instance()->createVideoReceiver(owner);
101 })
102 , _cameraAttached(&UVCDevices::deviceExists)
103{
104 qCDebug(VideoManagerLog) << this;
105
106 for (VideoStreamController* source : std::as_const(_sources)) {
107 _connectSource(source);
108 }
109 (void) connect(_recordingService, &VideoRecordingService::recordingChanged, this, &VideoManager::recordingChanged);
110 // A camera plugged in or unplugged changes whether the camera source has one to run.
111 (void) connect(_uvcCamera, &UVCCameraController::camerasChanged, this, [this] {
112 _updateState();
113 _cameraSource->scheduleApply();
114 });
115 // The frame rate the camera is set up for may change without its figures.
116 (void) connect(_uvcCamera->monitor(), &UVCStreamMonitor::statsChanged, this, &VideoManager::_updateSourceSummary);
117 (void) connect(_telemetryOverlay, &VideoTelemetryOverlay::textChanged, this,
119#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
120 // A mobile app in the background shows nothing, and decoding there costs the battery. A desktop app's windows
121 // stay in view without the focus.
122 (void) connect(qGuiApp, &QGuiApplication::applicationStateChanged, this, &VideoManager::_onApplicationStateChanged);
123#endif
124#if defined(Q_OS_ANDROID)
125 // Android cuts the network of an app in the background, which would end a recording there.
126 (void) connect(this, &VideoManager::recordingChanged, this, [](bool recording) {
128 });
129#endif
130
131 _connectSettings();
132 _updateState();
133}
134
136{
137 qCDebug(VideoManagerLog) << this;
138}
139
141{
142 return _videoManagerInstance();
143}
144
145void VideoManager::_onApplicationStateChanged(Qt::ApplicationState state)
146{
147 // Inactive is in view without the focus, as beside another app or under a system dialog.
148 const bool suspended = (state == Qt::ApplicationHidden) || (state == Qt::ApplicationSuspended);
149 if (suspended == _displaySuspended) {
150 return;
151 }
152 _displaySuspended = suspended;
153 qCDebug(VideoManagerLog) << (suspended ? "In the background: display suspended" : "Display resumed");
154 for (VideoStreamController* source : std::as_const(_sources)) {
155 source->setDisplaySuspended(suspended);
156 }
157}
158
159void VideoManager::_connectSource(VideoStreamController* source)
160{
161 (void) connect(source, &VideoStreamController::decodingChanged, this, [this, source] {
162 if (source == _primaryStream) {
163 emit decodingChanged();
164 }
165 });
167 (void) connect(source, &VideoStreamController::streamInfoChanged, this, &VideoManager::_updateState);
170 (void) connect(source, changed, this, &VideoManager::_updateSourceSummary);
171 }
172 (void) connect(source, &VideoStreamController::errorOccurred, this, [source](const QString& message) {
173 qCWarning(VideoManagerLog) << source->name() << message;
174 QGC::showAppMessage(message);
175 });
176}
177
178void VideoManager::_updateSourceSummary()
179{
180 int tileCount = 0;
181 VideoStreamController* measured = nullptr;
182 VideoStreamController* measuredInTile = nullptr;
183 bool degraded = false;
184 for (VideoStreamController* source : std::as_const(_sources)) {
185 const VideoStreamStats stats = source->stats();
186 if (source->tile()) {
187 ++tileCount;
188 }
189 if (stats.valid) {
190 VideoStreamController*& first = source->tile() ? measuredInTile : measured;
191 if (!first) {
192 first = source;
193 }
194 }
195 // A stream that isn't decoded, as the thermal stream while its view is off, shows no frames to compare with
196 // the frame rate its camera advertises.
197 const QGCVideoStreamInfo* const streamInfo = source->decoding() ? source->streamInfo() : nullptr;
198 const double cameraFps = (source == _cameraSource) ? _uvcCamera->monitor()->cameraFrameRate()
199 : (streamInfo ? streamInfo->framerate() : 0.0);
200 degraded = degraded || stats.degraded(cameraFps);
201 }
202 if (!measured) {
203 measured = measuredInTile ? measuredInTile : _primaryStream;
204 }
205
206 if (tileCount != _tileCount) {
207 _tileCount = tileCount;
208 emit tileCountChanged();
209 }
210 if (measured != _measuredSource) {
211 _measuredSource = measured;
213 }
214 if (degraded != _degraded) {
215 _degraded = degraded;
216 emit degradedChanged();
217 }
218}
219
220void VideoManager::_connectSettings()
221{
222 // The choice of the camera as the main picture was of the camera the tile had: another one starts in the tile.
223 // Connected before the reactions, which then find both settings as they are to be.
224 (void) connect(_videoSettings->uvcTileCamera(), &Fact::rawValueChanged, this,
225 [this] { _videoSettings->uvcTileCameraAsMainPicture()->setRawValue(false); });
226
227 // How a change to a video setting reaches the sources. Not listed: aspectRatio, read by
228 // VideoStreamController::aspectRatio(); videoFit, gridLines and showRecControl, read by QML; showTelemetryOverlay,
229 // read by VideoTelemetryOverlay; recordingFormat, enableStorageLimit and maxVideoSize, read when a recording
230 // starts; uvcCameraFormat, uvcCameraRotation, uvcCameraMirror, uvcWhiteBalance, uvcZoom, uvcExposureCompensation
231 // and uvcFocusMode, which go to the USB camera, and uvcRecordingCodec and uvcRecordingQuality, which go to every
232 // source (below).
233
234 // Live: the sources resolve their config again. VideoReceiver restarts for a changed config, except for a change
235 // of autoReconnect alone, which applies at once.
236 const auto reconfigure = [this] {
237 _updateState();
238 for (VideoStreamController* source : std::as_const(_sources)) {
239 source->scheduleApply();
240 }
241 };
242 for (Fact* const fact :
243 {_videoSettings->videoSource(), _videoSettings->udpUrl(), _videoSettings->tcpUrl(), _videoSettings->rtspUrl(),
244 _videoSettings->rtspTimeout(), _videoSettings->lowLatencyMode(), _videoSettings->rtpJitterLatencyMs(),
245 _videoSettings->rtspAutoReconnect(), _videoSettings->disableWhenDisarmed(),
246 // Which sources there are, and what the camera source plays.
247 _videoSettings->maxVideoTiles(), _videoSettings->uvcTileCamera(),
248 _videoSettings->uvcTileCameraAsMainPicture()}) {
249 (void) connect(fact, &Fact::rawValueChanged, this, reconfigure);
250 }
251
252 // Construct-only properties of the display sink: the sources restart, which rebuilds a stream's sink.
253 for (Fact* const fact : {_videoSettings->videoConversionElement(), _videoSettings->disablePixelAspectRatio(),
254 _videoSettings->forceCpuVideoPath()}) {
255 (void) connect(fact, &Fact::rawValueChanged, this, &VideoManager::_restartSources);
256 }
257
258 // The decoder ranks, which are global: once the backend is ready they are applied again, and the sources restart
259 // so the streams' new pipelines pick decoders by them.
260 (void) connect(_videoSettings->forceVideoDecoder(), &Fact::rawValueChanged, this, [this](const QVariant& value) {
261 // Until then, _onBackendInitComplete() applies the setting.
262 if (_initState == InitState::Ready) {
263 VideoBackend::instance().applyDecoderPriorities(videoDecoderOptionFromSetting(value.toInt()));
264 }
265 _restartSources();
266 });
267
268 // Which receiver plays the streams: each stream gets a new one.
269 (void) connect(_videoSettings->videoBackend(), &Fact::rawValueChanged, this, [this] {
270 {
271 // A receiver that is recording runs the event loop as it goes: the sources stay as they are until each has
272 // let go of its own.
273 const QScopedValueRollback<bool> sourcesHeld(_updatingState, true);
274 for (VideoStreamController* source : std::as_const(_sources)) {
275 source->setReceiver(nullptr);
276 }
277 }
278 if (_backendInitFinished() && _hasMainWindow) {
279 _createVideoReceivers();
280 }
281 if (!_updatingState && _updateStatePending) {
282 _updateState();
283 }
284 });
285
286 Fact* const uvcCameraFormat = _videoSettings->uvcCameraFormat();
287 _uvcCamera->setFormat(uvcCameraFormat->rawValue().toString());
288 (void) connect(uvcCameraFormat, &Fact::rawValueChanged, this,
289 [this](const QVariant& value) { _uvcCamera->setFormat(value.toString()); });
290
291 const auto applyUvcTransform = [this] {
292 // uvcCameraRotation's values are degrees, as QtVideo::Rotation's are.
293 _uvcCamera->setTransform(
294 static_cast<QtVideo::Rotation>(_videoSettings->uvcCameraRotation()->rawValue().toInt()),
295 _videoSettings->uvcCameraMirror()->rawValue().toBool());
296 };
297 applyUvcTransform();
298 (void) connect(_videoSettings->uvcCameraRotation(), &Fact::rawValueChanged, this, applyUvcTransform);
299 (void) connect(_videoSettings->uvcCameraMirror(), &Fact::rawValueChanged, this, applyUvcTransform);
300
301 const auto applyUvcControls = [this] {
303 // uvcWhiteBalance's and uvcFocusMode's values are QCamera's.
304 controls.whiteBalance =
305 static_cast<QCamera::WhiteBalanceMode>(_videoSettings->uvcWhiteBalance()->rawValue().toInt());
306 controls.zoom = _videoSettings->uvcZoom()->rawValue().toFloat();
307 controls.exposureCompensation = _videoSettings->uvcExposureCompensation()->rawValue().toFloat();
308 controls.focusMode = static_cast<QCamera::FocusMode>(_videoSettings->uvcFocusMode()->rawValue().toInt());
309 _uvcCamera->setControls(controls);
310 };
311 applyUvcControls();
312 for (Fact* const fact : {_videoSettings->uvcWhiteBalance(), _videoSettings->uvcZoom(),
313 _videoSettings->uvcExposureCompensation(), _videoSettings->uvcFocusMode()}) {
314 (void) connect(fact, &Fact::rawValueChanged, this, applyUvcControls);
315 }
316
317 const auto applyRecordingEncoding = [this] {
318 const VideoReceiver::RecordingEncoding encoding = recordingEncodingSetting(_videoSettings);
319 for (VideoStreamController* source : std::as_const(_sources)) {
320 source->setRecordingEncoding(encoding);
321 }
322 };
323 applyRecordingEncoding();
324 (void) connect(_videoSettings->uvcRecordingCodec(), &Fact::rawValueChanged, this, applyRecordingEncoding);
325 (void) connect(_videoSettings->uvcRecordingQuality(), &Fact::rawValueChanged, this, applyRecordingEncoding);
326}
327
329{
330 if (_initState != InitState::NotStarted) {
331 return;
332 }
333
336 _initState = InitState::Ready;
337 return;
338 }
339
340 _initState = InitState::Pending;
341 const VideoBackend::InitParams params{.arguments = QCoreApplication::arguments(),
342 .environment = backend.prepareEnvironment(),
343 .debugLevel = VideoBackend::persistedDebugLevel()};
344 _watchBackendInit(QtConcurrent::run([&backend, params] { return backend.initialize(params); }));
345}
346
347void VideoManager::_watchBackendInit(const QFuture<bool>& future)
348{
349 _backendInitFuture = future;
350 // Ignored when waitForVideoBackendReady() already took the result.
351 (void) _backendInitFuture.then(this, [this](bool success) { _onBackendInitComplete(success); })
352 .onCanceled(this, [this] { _onBackendInitComplete(false); });
353}
354
356{
357 if (_initState == InitState::NotStarted) {
359 }
360
361 if (_initState == InitState::Pending) {
362 _backendInitFuture.waitForFinished();
363 const bool success =
364 !_backendInitFuture.isCanceled() && (_backendInitFuture.resultCount() > 0) && _backendInitFuture.result();
365 _onBackendInitComplete(success);
366 }
367
368 return _initState == InitState::Ready;
369}
370
371void VideoManager::_onBackendInitComplete(bool success)
372{
373 if (_initState != InitState::Pending) {
374 return;
375 }
376
377 if (!success) {
378 _initState = InitState::Failed;
379 qCCritical(VideoManagerLog) << "video initialization failed";
380 QGC::showAppMessage(VideoBackend::instance().initFailureMessage());
381 // The backend then makes the receivers that need no initialization.
382 if (_hasMainWindow) {
383 _createVideoReceivers();
384 }
385 return;
386 }
387
388 _videoSettings->pruneUnavailableDecoders();
390 videoDecoderOptionFromSetting(_videoSettings->forceVideoDecoder()->rawValue().toInt()));
391
392 _initState = InitState::Ready;
393 qCDebug(VideoManagerLog) << "video backend ready";
394 if (_hasMainWindow) {
395 _createVideoReceivers();
396 }
397}
398
399void VideoManager::init(QQuickWindow* mainWindow)
400{
401 if (_hasMainWindow) {
402 qCDebug(VideoManagerLog) << "Video Manager already initialized";
403 return;
404 }
405
406 if (!mainWindow) {
407 qCCritical(VideoManagerLog) << "Failed To Init Video Manager - mainWindow is NULL";
408 return;
409 }
410
412 (void) connect(SettingsManager::instance()->appSettings()->gstDebugLevel(), &Fact::rawValueChanged, this,
413 [](const QVariant& value) { VideoBackend::instance().setDebugLevel(value.toInt()); });
414
415 MultiVehicleManager* const multiVehicleManager = MultiVehicleManager::instance();
416 (void) connect(multiVehicleManager, &MultiVehicleManager::activeVehicleChanged, this,
417 &VideoManager::_setActiveVehicle);
418 _setActiveVehicle(multiVehicleManager->activeVehicle());
419
420 _onMainWindowReady();
421}
422
423void VideoManager::_onMainWindowReady()
424{
425 _hasMainWindow = true;
426 // The receivers need the backend and nothing from QML: the VideoOutputs register themselves whenever they exist.
428 if (_backendInitFinished()) {
429 _createVideoReceivers();
430 }
431}
432
433void VideoManager::_createVideoReceivers()
434{
435 if (_cleanedUp) {
436 return;
437 }
438 for (VideoStreamController* source : std::as_const(_sources)) {
439 // The camera source has its own.
440 if (source->receiver()) {
441 continue;
442 }
443 VideoReceiver* const receiver = _receiverFactory(source);
444 if (!receiver) {
445 qCDebug(VideoManagerLog) << "No video receiver for" << source->name();
446 continue;
447 }
448 source->setReceiver(receiver);
449 }
450}
451
452void VideoManager::_restartSources()
453{
454 for (VideoStreamController* source : std::as_const(_sources)) {
455 source->restart();
456 }
457}
458
460{
461 // Latched first: the waits below run the event loop, and what it delivers (the backend's init finishing, a setting
462 // or a camera changing) must not bring back what this takes down.
463 _cleanedUp = true;
464 // Receivers must die here, not in ~VideoManager: that runs inside ~QCoreApplication, where queued events are no
465 // longer delivered, so a receiver's worker thread never gets its quit task and the destructor waits forever. The
466 // camera stops here too: Qt Multimedia's backend goes away with the application, before ~VideoManager.
467 for (VideoStreamController* source : std::as_const(_sources)) {
468 source->shutDown();
469 }
470}
471
473{
474 qCDebug(VideoManagerLog) << "startVideo";
475
476 _videoStopped = false;
477 _disabledWhileDisarmed = false;
478 _updateState();
479 _restartSources();
480}
481
483{
484 qCDebug(VideoManagerLog) << "stopVideo";
485
486 _videoStopped = true;
487 _updateState();
488 for (VideoStreamController* source : std::as_const(_sources)) {
489 source->stop();
490 }
491}
492
493void VideoManager::startRecording(const QString& baseName)
494{
495 _recordingService->startRecording(baseName);
496}
497
499{
500 _recordingService->stopRecording();
501}
502
503void VideoManager::grabImage(const QString& imageFile)
504{
505 // One reading of the clock names the file and dates its EXIF data.
506 const QDateTime now = QDateTime::currentDateTime();
507 QString file = imageFile;
508 if (file.isEmpty()) {
509 const QString directory = SettingsManager::instance()->appSettings()->photoSavePath();
510 if (directory.isEmpty()) {
511 QGC::showAppMessage(tr("Unable to save the photo. The save path must be specified in Settings."));
512 return;
513 }
514 file = QStringLiteral("%1/%2.jpg").arg(directory, now.toString(QStringLiteral("yyyy-MM-dd_hh.mm.ss.zzz")));
515 }
516
518 exif.taken = now;
519 if (_activeVehicle) {
520 exif.position = _activeVehicle->coordinate();
521 }
522
523 bool taken = false;
524 for (VideoStreamController* source : std::as_const(_sources)) {
525 // The main picture and the thermal stream with it: not the tiles.
526 if (!source->tile() && source->canTakeScreenshot()) {
527 taken = source->takeScreenshot(source->taggedFile(file), exif) || taken;
528 }
529 }
530 // What goes wrong from here on, the source reports.
531 if (!taken) {
532 qCWarning(VideoManagerLog) << "No video on display to take a screenshot from";
533 QGC::showAppMessage(tr("Unable to take a photo: no video is on display."));
534 }
535}
536
537QQmlListProperty<VideoStreamController> VideoManager::sources()
538{
539 using Sources = QQmlListProperty<VideoStreamController>;
540 // Read-only: QML can't add or remove a source.
541 return Sources(
542 this, nullptr, [](Sources* sources) { return static_cast<VideoManager*>(sources->object)->_sources.size(); },
543 [](Sources* sources, qsizetype index) {
544 return static_cast<VideoManager*>(sources->object)->_sources.at(index);
545 });
546}
547
549{
550 return _primaryStream->decoding();
551}
552
554{
555 return _telemetryOverlay->text();
556}
557
559{
560 return _recordingService->recording();
561}
562
564{
565 return _primaryStream->aspectRatio();
566}
567
569{
570 return _thermalStream->aspectRatio();
571}
572
574{
575 if (on && (!_hasVideo || !_activeVehicle || _activeVehicle->vehicleLinkManager()->communicationLost())) {
576 on = false;
577 }
578
579 if (on != _fullScreen) {
580 _fullScreen = on;
581 emit fullScreenChanged();
582 }
583}
584
586{
587 if (room == _tileRoom) {
588 return;
589 }
590 _tileRoom = room;
591 emit tileRoomChanged();
592 (void) QMetaObject::invokeMethod(this, &VideoManager::_updateState, Qt::QueuedConnection);
593}
594
596{
597 if (!source || !source->tile()) {
598 return;
599 }
600 qCDebug(VideoManagerLog) << "select" << source->name();
601
602 // A stream takes the main picture back from the camera. The sources follow the setting as it changes.
603 _videoSettings->uvcTileCameraAsMainPicture()->setRawValue(source == _cameraSource);
604 if (source == _cameraSource) {
605 return;
606 }
607
608 const auto stream =
609 std::find_if(_otherStreams.cbegin(), _otherStreams.cend(), [source](const AdvertisedStream& other) {
610 return other.streamInfo && (other.streamInfo == source->streamInfo());
611 });
612 QGCCameraManager* const cameraManager = _activeVehicle ? _activeVehicle->cameraManager() : nullptr;
613 if ((source != _primaryStream) && (stream != _otherStreams.cend()) && stream->camera && cameraManager) {
614 // Copied: the camera manager tells of each change at once, which replaces the streams.
615 MavlinkCameraControlInterface* const camera = stream->camera;
616 const int streamIndex = camera->streamLabels().indexOf(stream->streamInfo->name());
617 // The stream first: the camera then becomes the current one with the stream to show.
618 if (streamIndex >= 0) {
619 camera->setCurrentStream(streamIndex);
620 }
621 cameraManager->setCurrentCamera(cameraManager->cameras()->indexOf(camera));
622 }
623 _updateState();
624}
625
626void VideoManager::_updateState()
627{
628 if (_updatingState) {
629 _updateStatePending = true;
630 return;
631 }
632 const QScopedValueRollback<bool> updating(_updatingState, true);
633 do {
634 _updateStatePending = false;
635 _updateStateNow();
636 } while (_updateStatePending);
637}
638
639void VideoManager::_updateStateNow()
640{
641 if (_cleanedUp) {
642 return;
643 }
644 if (!_videoSettings->disableWhenDisarmed()->rawValue().toBool()) {
645 _disabledWhileDisarmed = false;
646 }
647
648 const QString videoSource = _videoSettings->videoSource()->rawValue().toString();
649 const bool streamWanted = !_disabledWhileDisarmed;
650 // The reason that takes the most to lift comes first: arming doesn't bring back video that was stopped.
652 : _disabledWhileDisarmed ? NoVideoReason::DisabledWhileDisarmed
654 const bool autoStreamConfigured = VideoStreamResolver::isAutoStream(_primaryStream->streamInfo());
656 const int tilesAllowed =
657 static_cast<int>(std::min(_videoSettings->maxVideoTiles()->rawValue().toUInt(), kMaxVideoTiles));
658 const int maxTiles = (_tileRoom < 0) ? tilesAllowed : std::min(tilesAllowed, _tileRoom);
659 // A stream to play takes the place of the camera the video source names: the camera source then plays the camera
660 // to show in a tile.
661 const QString cameraName =
662 !isStreamSource ? videoSource
663 : ((maxTiles > 0) ? _videoSettings->uvcTileCamera()->rawValue().toString() : QString());
664 const bool cameraWanted = streamWanted && !cameraName.isEmpty();
665 if (cameraWanted) {
666 // A camera plugged in or unplugged changes whether the camera source has one to play.
667 _uvcCamera->watchCameras();
668 }
669 const QString camera = (cameraWanted && _cameraAttached(cameraName)) ? cameraName : QString();
670 const bool hasUvcCamera = !camera.isEmpty();
671 // A camera selected in its tile is the main picture whenever it plays beside the stream: the setting outlasts a
672 // camera that is unplugged, and a restart.
673 const bool cameraOnMain =
674 isStreamSource && !camera.isEmpty() && _videoSettings->uvcTileCameraAsMainPicture()->rawValue().toBool();
675 const bool cameraTile = isStreamSource && !camera.isEmpty() && !cameraOnMain;
676 const QString uvcVideoSourceID = cameraTile ? QString() : camera;
677 const bool hasVideo = streamWanted && (_primaryStream->configured() || !uvcVideoSourceID.isEmpty());
678 const QGCVideoStreamInfo* const thermalStreamInfo = _thermalStream->streamInfo();
679 // The thermal stream goes with the primary stream's picture.
680 const bool hasThermal = thermalStreamInfo && thermalStreamInfo->isThermal() && !cameraOnMain;
681
682 _cameraSource->setCamera(camera);
683 _cameraSource->setDisplayName(camera);
684 _cameraSource->setTile(cameraTile);
685 _primaryStream->setTile(cameraOnMain);
687 _primaryStream->setDisplayName(_videoSettings->videoSource()->enumStringValue());
688 }
689 // Without video there is no view to show tiles in. The camera, or the stream it took the main picture from, has
690 // one of them.
691 _updateTileStreams(hasVideo ? (maxTiles - ((cameraTile || cameraOnMain) ? 1 : 0)) : 0);
692
693 for (VideoStreamController* source : std::as_const(_sources)) {
694 source->setEnabled(streamWanted && !_videoStopped && ((source != _thermalStream) || !cameraOnMain));
695 }
696
697 if (autoStreamConfigured != _autoStreamConfigured) {
698 _autoStreamConfigured = autoStreamConfigured;
700 }
701 if (isStreamSource != _isStreamSource) {
702 _isStreamSource = isStreamSource;
704 }
705 if (uvcVideoSourceID != _uvcVideoSourceID) {
706 qCDebug(VideoManagerLog) << "UVC changed from [" << _uvcVideoSourceID << "] to [" << uvcVideoSourceID << "]";
707 _uvcVideoSourceID = uvcVideoSourceID;
709 emit isUvcChanged();
710 }
711 if (hasVideo != _hasVideo) {
712 _hasVideo = hasVideo;
713 emit hasVideoChanged();
714 if (!_hasVideo) {
715 // The Fly View swaps the video out of its PiP when hasVideo drops; nothing in QML could leave full screen.
716 setFullScreen(false);
717 }
718 }
719 if (hasThermal != _hasThermal) {
720 _hasThermal = hasThermal;
721 emit hasThermalChanged();
722 }
723 if (hasUvcCamera != _hasUvcCamera) {
724 _hasUvcCamera = hasUvcCamera;
725 emit hasUvcCameraChanged();
726 }
727 if (noVideoReason != _noVideoReason) {
728 _noVideoReason = noVideoReason;
730 }
731}
732
733VideoStreamController* VideoManager::_tileStream(const QGCVideoStreamInfo* streamInfo) const
734{
735 const auto tile =
736 std::find_if(_tileStreams.cbegin(), _tileStreams.cend(),
737 [streamInfo](const VideoStreamController* source) { return source->streamInfo() == streamInfo; });
738 return (streamInfo && (tile != _tileStreams.cend())) ? *tile : nullptr;
739}
740
741void VideoManager::_updateTileStreams(int count)
742{
743 const VideoStreamResolver::Settings settings = VideoStreamResolver::snapshot(_videoSettings);
744 QStringList shownAddresses;
745 for (const VideoStreamController* source : {_primaryStream, _thermalStream}) {
746 if (const auto config = VideoStreamResolver::resolve(settings, source->streamInfo(), source->role())) {
747 shownAddresses.append(streamAddress(config->uri));
748 }
749 }
750
751 QList<VideoStreamController*> tiles;
752 for (const AdvertisedStream& stream : std::as_const(_otherStreams)) {
753 if (tiles.size() >= count) {
754 break;
755 }
756 const auto config =
757 VideoStreamResolver::resolve(settings, stream.streamInfo, VideoStreamController::Role::Tile);
758 if (!config || shownAddresses.contains(streamAddress(config->uri))) {
759 continue;
760 }
761 shownAddresses.append(streamAddress(config->uri));
762
763 VideoStreamController* tile = _tileStream(stream.streamInfo);
764 if (!tile) {
765 tile = new VideoStreamController(VideoStreamController::Role::Tile, _videoSettings, this);
766 tile->setName(QStringLiteral("videoTile%1").arg(++_tileStreamSerial));
767 tile->setStreamInfo(stream.streamInfo);
768 // Its source records once it is the primary stream.
769 tile->setRecordingEncoding(recordingEncodingSetting(_videoSettings));
770 tile->setDisplaySuspended(_displaySuspended);
771 _connectSource(tile);
772 _recordingService->addSource(tile);
773 }
774 tile->setDisplayName(stream.name);
775 tile->setTile(true);
776 tiles.append(tile);
777 }
778
779 QList<VideoStreamController*> removed;
780 for (VideoStreamController* const tile : std::as_const(_tileStreams)) {
781 if (!tiles.contains(tile)) {
782 removed.append(tile);
783 }
784 }
785 _tileStreams = tiles;
786
787 const QList<VideoStreamController*> sources =
788 QList<VideoStreamController*>{_primaryStream, _thermalStream, _cameraSource} + _tileStreams;
789 if (sources != _sources) {
790 _sources = sources;
791 // Before the sources that left are deleted: none of them is the measured one from here on.
792 _updateSourceSummary();
793 emit sourcesChanged();
794 }
795 // Once QML has let go of them.
796 for (VideoStreamController* const tile : std::as_const(removed)) {
797 qCDebug(VideoManagerLog) << "tile removed" << tile->name();
798 tile->shutDown();
799 tile->deleteLater();
800 }
801 // The streams have their receivers: so do the new ones.
802 if (_thermalStream->receiver()) {
803 _createVideoReceivers();
804 }
805 _nameExtraStreams();
806}
807
808void VideoManager::_nameExtraStreams()
809{
810 QGCCameraManager* const cameraManager = _activeVehicle ? _activeVehicle->cameraManager() : nullptr;
811 if (!cameraManager) {
812 return;
813 }
814 const QList<MavlinkCameraControlInterface*> cameras = vehicleCameras(cameraManager);
815 for (MavlinkCameraControlInterface* const camera : cameras) {
816 QList<quint8> streamIds;
817 for (const AdvertisedStream& stream : std::as_const(_otherStreams)) {
818 if ((stream.camera == camera) && _tileStream(stream.streamInfo)) {
819 streamIds.append(stream.streamInfo->streamID());
820 }
821 }
822 camera->setExtraStreams(streamIds);
823 }
824}
825
826void VideoManager::_setActiveVehicle(Vehicle* vehicle)
827{
828 qCDebug(VideoManagerLog) << "new vehicle" << vehicle << "old active vehicle" << _activeVehicle;
829
830 if (_activeVehicle) {
831 (void) disconnect(_activeVehicle, nullptr, this, nullptr);
832 (void) disconnect(_activeVehicle->vehicleLinkManager(), nullptr, this, nullptr);
833 QGCCameraManager* const cameraManager = _activeVehicle->cameraManager();
834 if (cameraManager) {
835 (void) disconnect(cameraManager, nullptr, this, nullptr);
836 // The streams in tiles leave the display first, the current stream after them.
837 const QList<MavlinkCameraControlInterface*> cameras = vehicleCameras(cameraManager);
838 for (MavlinkCameraControlInterface* const camera : cameras) {
839 camera->setExtraStreams({});
840 }
841 MavlinkCameraControlInterface* const camera = cameraManager->currentCameraInstance();
842 if (camera) {
843 camera->stopStream();
844 }
845 }
846 }
847
848 _activeVehicle = vehicle;
849 _disabledWhileDisarmed = false;
850
851 if (_activeVehicle) {
852 (void) connect(_activeVehicle->vehicleLinkManager(), &VehicleLinkManager::communicationLostChanged, this,
853 &VideoManager::_communicationLostChanged);
854 (void) connect(_activeVehicle, &Vehicle::armedChanged, this, &VideoManager::_onArmedChanged);
855 QGCCameraManager* const cameraManager = _activeVehicle->cameraManager();
856 if (cameraManager) {
857 (void) connect(cameraManager, &QGCCameraManager::streamChanged, this, &VideoManager::_updateStreamInfo);
858 MavlinkCameraControlInterface* const camera = cameraManager->currentCameraInstance();
859 if (camera) {
860 camera->resumeStream();
861 }
862 }
863 _reconnectStreams();
864 } else {
865 setFullScreen(false);
866 }
867
868 _updateStreamInfo();
869}
870
871void VideoManager::_updateStreamInfo()
872{
873 QGCCameraManager* const cameraManager = _activeVehicle ? _activeVehicle->cameraManager() : nullptr;
874 if (!cameraManager) {
875 _setAdvertisedStreams({}, nullptr, {});
876 return;
877 }
878
879 // The current camera's streams come first, then the other cameras', in the cameras' order.
880 QList<MavlinkCameraControlInterface*> cameras = vehicleCameras(cameraManager);
881 MavlinkCameraControlInterface* const currentCamera = cameraManager->currentCameraInstance();
882 if (cameras.removeOne(currentCamera)) {
883 cameras.prepend(currentCamera);
884 }
885 QGCVideoStreamInfo* const currentStreamInfo = cameraManager->currentStreamInstance();
886 AdvertisedStream current;
887 QList<AdvertisedStream> others;
888 for (MavlinkCameraControlInterface* const camera : std::as_const(cameras)) {
889 QmlObjectListModel* const streams = camera->streams();
890 for (int i = 0; streams && (i < streams->count()); ++i) {
891 auto* const streamInfo = qobject_cast<QGCVideoStreamInfo*>(streams->get(i));
892 if (!streamInfo || streamInfo->isThermal()) {
893 continue;
894 }
895 const QString name = (cameras.size() > 1)
896 ? QStringLiteral("%1: %2").arg(camera->modelName(), streamInfo->name())
897 : streamInfo->name();
898 if (streamInfo == currentStreamInfo) {
899 current = {streamInfo, camera, name};
900 } else {
901 others.append({streamInfo, camera, name});
902 }
903 }
904 }
905 _setAdvertisedStreams(current, cameraManager->thermalStreamInstance(), others);
906}
907
908void VideoManager::_setAdvertisedStreams(const AdvertisedStream& current, QGCVideoStreamInfo* thermal,
909 const QList<AdvertisedStream>& others)
910{
911 if (_cleanedUp) {
912 return;
913 }
914 _otherStreams = others;
915
916 if (VideoStreamController* const playing = _tileStream(current.streamInfo)) {
917 // The stream to display plays in a tile: its source becomes the primary stream as it is, and the former
918 // primary stream, which plays on, gets a tile if its stream is still one to show.
919 VideoStreamController* const former = _primaryStream;
920 _tileStreams.replace(_tileStreams.indexOf(playing), former);
921 _primaryStream = playing;
922 playing->setTile(former->tile());
923 former->setRole(VideoStreamController::Role::Tile);
924 playing->setRole(VideoStreamController::Role::Primary);
926 emit decodingChanged();
927 emit aspectRatioChanged();
928 } else {
929 _primaryStream->setStreamInfo(current.streamInfo);
930 }
931 if (current.streamInfo) {
932 _primaryStream->setDisplayName(current.name);
933 }
934 _thermalStream->setStreamInfo(thermal);
935 _updateState();
936}
937
938void VideoManager::_onArmedChanged(bool armed)
939{
940 const bool disabled = !armed && _videoSettings->disableWhenDisarmed()->rawValue().toBool();
941 if (disabled != _disabledWhileDisarmed) {
942 qCDebug(VideoManagerLog) << "disabled while disarmed:" << disabled;
943 _disabledWhileDisarmed = disabled;
944 _updateState();
945 }
946}
947
948void VideoManager::_communicationLostChanged(bool communicationLost)
949{
950 if (communicationLost) {
951 setFullScreen(false);
952 } else {
953 _reconnectStreams();
954 }
955}
956
957void VideoManager::_reconnectStreams()
958{
959 for (VideoStreamController* source : std::as_const(_sources)) {
960 source->reconnectNow();
961 }
962}
#define qGuiApp
#define QGC_LOGGING_CATEGORY(name, categoryStr)
constexpr VideoDecoderOption videoDecoderOptionFromSetting(int value)
The option a stored forceVideoDecoder value names: the default for a value that names none.
Q_APPLICATION_STATIC(VideoManager, _videoManagerInstance)
QString photoSavePath()
A Fact is used to hold a single value within the system.
Definition Fact.h:15
void rawValueChanged(const QVariant &value)
QVariant rawValue() const
Definition Fact.h:87
Abstract base class for all camera controls: real and simulated.
virtual QStringList streamLabels() const =0
Stream names to show the user (for selection).
virtual QmlObjectListModel * streams()=0
virtual QString modelName() const =0
virtual Q_INVOKABLE void stopStream()=0
virtual Q_INVOKABLE void resumeStream()=0
virtual void setCurrentStream(int stream)=0
static MultiVehicleManager * instance()
Vehicle * activeVehicle() const
void activeVehicleChanged(Vehicle *activeVehicle)
Camera Manager.
void setCurrentCamera(int sel)
QmlObjectListModel * cameras()
MavlinkCameraControlInterface * currentCameraInstance()
QGCVideoStreamInfo * currentStreamInstance()
QGCVideoStreamInfo * thermalStreamInstance()
static QGCCorePlugin * instance()
Encapsulates the contents of a VIDEO_STREAM_INFORMATION message.
Q_INVOKABLE QObject * get(int index)
int count() const override final
int indexOf(const QObject *object)
static QMediaFormat::VideoCodec recordingCodec(const QString &key)
The codec of key key, as recordingCodecs() names it; Unspecified for an empty or unknown key.
static QMediaRecorder::Quality recordingQuality(int value)
The quality of value value, one of VideoSettings::uvcRecordingQuality's; HighQuality for any other.
Provides access to all app settings.
static SettingsManager * instance()
AppSettings * appSettings() const
void camerasChanged()
A camera was plugged in or unplugged.
void communicationLostChanged(bool communicationLost)
void armedChanged(bool armed)
virtual bool initialize(const InitParams &params)
virtual void applyDecoderPriorities(VideoDecoderOption option)
static VideoBackend & instance()
virtual Capabilities capabilities() const =0
virtual EnvPrepResult prepareEnvironment()
GUI thread, before initialize().
static bool disabledForUnitTests()
True when the backend is skipped under unit tests (opt back in with QGC_TEST_ENABLE_GSTREAMER).
static std::optional< int > persistedDebugLevel()
The persisted gstDebugLevel setting, read before the settings system exists; nullopt when it was neve...
virtual void onMainWindowReady(QQuickWindow *window)
virtual void setDebugLevel(int level)
bool isStreamSource() const
void sourcesChanged()
NoVideoReason noVideoReason() const
void decodingChanged()
Q_INVOKABLE void selectSource(VideoStreamController *source)
void setTileRoom(int room)
void startVideoBackendInit()
Starts the video backend's asynchronous global init. GUI thread only, like everything else here.
Q_INVOKABLE void stopRecording()
int tileCount() const
bool degraded() const
void hasVideoChanged()
void uvcVideoSourceIDChanged()
Q_INVOKABLE void startVideo()
Undoes stopVideo() and "disable when disarmed", and reconnects the streams.
bool hasThermal() const
bool autoStreamConfigured() const
void hasUvcCameraChanged()
NoVideoReason
Why a video view without a picture has none.
@ DisabledWhileDisarmed
VideoSettings::disableWhenDisarmed, until the vehicle arms.
@ Waiting
Nothing keeps the video from playing: it is awaited.
@ Stopped
stopVideo(), until startVideo().
double thermalAspectRatio() const
void isStreamSourceChanged()
~VideoManager() override
static VideoManager * instance()
VideoManager(QObject *parent=nullptr)
QString uvcVideoSourceID() const
bool decoding() const
void autoStreamConfiguredChanged()
Q_INVOKABLE void startRecording(const QString &baseName=QString())
See VideoRecordingService::startRecording().
void degradedChanged()
void fullScreenChanged()
bool hasVideo() const
void init(QQuickWindow *mainWindow)
bool recording() const
Q_INVOKABLE void stopVideo()
Stops the sources, and any recording, until startVideo().
void setFullScreen(bool on)
double aspectRatio() const
bool waitForVideoBackendReady()
Blocks until the backend init finishes, starting it if needed. True when the backend is ready.
void isUvcChanged()
void noVideoReasonChanged()
void measuredSourceChanged()
void primaryStreamChanged()
QQmlListProperty< VideoStreamController > sources()
void recordingChanged(bool recording)
void tileCountChanged()
void tileRoomChanged()
void aspectRatioChanged()
void telemetryOverlayTextChanged()
QString telemetryOverlayText() const
bool hasUvcCamera() const
void hasThermalChanged()
Q_INVOKABLE void grabImage(const QString &imageFile=QString())
void recordingChanged(bool recording)
void setDisplaySuspended(bool suspended)
QGCVideoStreamInfo * streamInfo() const
void setDisplayName(const QString &displayName)
void restart()
Reconnects now and rebuilds the receiver's display sink, so construct-only sink settings apply.
VideoReceiver * receiver() const
QString taggedFile(const QString &file) const
file for this source: the thermal stream's name goes before the extension, "<base>....
bool takeScreenshot(const QString &file, const VideoScreenshot::Exif &exif={}) const
void setReceiver(VideoReceiver *receiver)
void setEnabled(bool enabled)
The stream plays while it is enabled and configured().
void setRecordingEncoding(const VideoReceiver::RecordingEncoding &encoding)
VideoReceiver::setRecordingEncoding(), for the receiver and for each one set later.
void reconnectNow()
VideoReceiver::reconnectNow(): the stream's source is likely back, so a reconnect doesn't wait out it...
void setName(const QString &name)
Names a source that has no receiver yet.
VideoStreamStats stats() const
The receiver's VideoReceiver::stats(); invalid without a receiver.
void setRole(Role role)
Makes a stream in a tile the primary stream, or the reverse. What the source plays stays.
void setStreamInfo(QGCVideoStreamInfo *streamInfo)
The stream the camera advertises for this role, which takes precedence over the manual settings.
void stop()
Disables the stream and stops the receiver now.
void errorOccurred(const QString &message)
bool canTakeScreenshot() const
True while the stream is streaming into a registered output.
void setBackgroundWork(BackgroundWork work, bool active)
constexpr const char * toString(HwVideoBufferPath path) noexcept
Definition GstHwTypes.h:37
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9
bool deviceExists(const QString &description)
Definition UVCDevices.cc:33
Settings snapshot(VideoSettings *videoSettings)
bool isNetworkSource(const QString &videoSource)
True for the manual sources that are network streams (not "disabled", not a local camera).
bool isAutoStream(const QGCVideoStreamInfo *streamInfo)
True when streamInfo advertises a URI, which then takes precedence over the manual settings.
std::optional< VideoReceiver::Config > resolve(const Settings &settings, const QGCVideoStreamInfo *streamInfo, Role role)
constexpr bool listens(Transport transport)
The receiver listens on a local UDP port for transport, rather than connect to a server.
std::optional< Transport > transportFor(const QUrl &url)
The transport url's scheme selects, case-insensitively; nullopt for any other scheme.
QCamera::WhiteBalanceMode whiteBalance
bool asyncInit
initialize() must run, off the GUI thread, before receivers are created.
QGeoCoordinate position
bool degraded(double cameraFps) const
bool valid
Measured at least once for the current stream; the other fields mean nothing while false.