VideoManager.cc 26.3 KB
Newer Older
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8 9 10 11 12 13
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/


#include <QQmlContext>
#include <QQmlEngine>
#include <QSettings>
14
#include <QUrl>
15
#include <QDir>
16 17

#ifndef QGC_DISABLE_UVC
18
#include <QCameraInfo>
19
#endif
20 21 22

#include "ScreenToolsController.h"
#include "VideoManager.h"
23 24 25
#include "QGCToolbox.h"
#include "QGCCorePlugin.h"
#include "QGCOptions.h"
26
#include "MultiVehicleManager.h"
27
#include "Settings/SettingsManager.h"
28
#include "Vehicle.h"
29
#include "QGCCameraManager.h"
30

31 32 33 34 35 36
#if defined(QGC_GST_STREAMING)
#include "GStreamer.h"
#else
#include "GLVideoItemStub.h"
#endif

Andrew Voznytsa's avatar
Andrew Voznytsa committed
37 38 39 40
#ifdef QGC_GST_TAISYNC_ENABLED
#include "TaisyncHandler.h"
#endif

41 42
QGC_LOGGING_CATEGORY(VideoManagerLog, "VideoManagerLog")

43
#if defined(QGC_GST_STREAMING)
44 45 46 47 48
static const char* kFileExtension[VideoReceiver::FILE_FORMAT_MAX - VideoReceiver::FILE_FORMAT_MIN] = {
    "mkv",
    "mov",
    "mp4"
};
49
#endif
50

51
//-----------------------------------------------------------------------------
52 53
VideoManager::VideoManager(QGCApplication* app, QGCToolbox* toolbox)
    : QGCTool(app, toolbox)
54
{
55 56 57 58 59 60 61
#if !defined(QGC_GST_STREAMING)
    static bool once = false;
    if (!once) {
        qmlRegisterType<GLVideoItemStub>("org.freedesktop.gstreamer.GLVideoItem", 1, 0, "GstGLVideoItem");
        once = true;
    }
#endif
62 63 64 65 66
}

//-----------------------------------------------------------------------------
VideoManager::~VideoManager()
{
67 68 69 70 71
    for (int i = 0; i < 2; i++) {
        if (_videoReceiver[i] != nullptr) {
            delete _videoReceiver[i];
            _videoReceiver[i] = nullptr;
        }
72
#if defined(QGC_GST_STREAMING)
73 74 75 76
        if (_videoSink[i] != nullptr) {
            GStreamer::releaseVideoSink(_videoSink[i]);
            _videoSink[i] = nullptr;
        }
77
#endif
78
    }
79 80 81 82 83 84 85 86
}

//-----------------------------------------------------------------------------
void
VideoManager::setToolbox(QGCToolbox *toolbox)
{
   QGCTool::setToolbox(toolbox);
   QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
87 88
   qmlRegisterUncreatableType<VideoManager> ("QGroundControl.VideoManager", 1, 0, "VideoManager", "Reference only");
   qmlRegisterUncreatableType<VideoReceiver>("QGroundControl",              1, 0, "VideoReceiver","Reference only");
89 90

   // TODO: Those connections should be Per Video, not per VideoManager.
91 92
   _videoSettings = toolbox->settingsManager()->videoSettings();
   QString videoSource = _videoSettings->videoSource()->rawValue().toString();
93 94 95
   connect(_videoSettings->videoSource(),   &Fact::rawValueChanged, this, &VideoManager::_videoSourceChanged);
   connect(_videoSettings->udpPort(),       &Fact::rawValueChanged, this, &VideoManager::_udpPortChanged);
   connect(_videoSettings->rtspUrl(),       &Fact::rawValueChanged, this, &VideoManager::_rtspUrlChanged);
96
   connect(_videoSettings->tcpUrl(),        &Fact::rawValueChanged, this, &VideoManager::_tcpUrlChanged);
97
   connect(_videoSettings->aspectRatio(),   &Fact::rawValueChanged, this, &VideoManager::_aspectRatioChanged);
98
   connect(_videoSettings->lowLatencyMode(),&Fact::rawValueChanged, this, &VideoManager::_lowLatencyModeChanged);
99 100
   MultiVehicleManager *pVehicleMgr = qgcApp()->toolbox()->multiVehicleManager();
   connect(pVehicleMgr, &MultiVehicleManager::activeVehicleChanged, this, &VideoManager::_setActiveVehicle);
101

102
#if defined(QGC_GST_STREAMING)
103 104
#ifndef QGC_DISABLE_UVC
   // If we are using a UVC camera setup the device name
Gus Grubba's avatar
Gus Grubba committed
105
   _updateUVC();
106
#endif
107 108 109

    emit isGStreamerChanged();
    qCDebug(VideoManagerLog) << "New Video Source:" << videoSource;
110
#if defined(QGC_GST_STREAMING)
111 112
    _videoReceiver[0] = toolbox->corePlugin()->createVideoReceiver(this);
    _videoReceiver[1] = toolbox->corePlugin()->createVideoReceiver(this);
113

114 115
    connect(_videoReceiver[0], &VideoReceiver::timeout, this, [this](){
        _restartVideo(0);
116 117
    });

118
    connect(_videoReceiver[0], &VideoReceiver::streamingChanged, this, [this](bool active){
119 120
        _streaming = active;
        emit streamingChanged();
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        _restartVideo(0);
    });

    connect(_videoReceiver[0], &VideoReceiver::onStartComplete, this, [this](VideoReceiver::STATUS status) {
        if (status == VideoReceiver::STATUS_OK) {
            _videoStarted[0] = true;
            _videoReceiver[0]->startDecoding(_videoSink[0]);
        } else if (status == VideoReceiver::STATUS_INVALID_URL) {
            // Invalid URL - don't restart
        } else if (status == VideoReceiver::STATUS_INVALID_STATE) {
            // Already running
        } else {
            _restartVideo(0);
        }
    });

    connect(_videoReceiver[0], &VideoReceiver::onStopComplete, this, [this](VideoReceiver::STATUS) {
        _videoStarted[0] = false;
139 140 141
        _startReceiver(0);
    });

142
    connect(_videoReceiver[0], &VideoReceiver::decodingChanged, this, [this](bool active){
143 144 145 146
        _decoding = active;
        emit decodingChanged();
    });

147
    connect(_videoReceiver[0], &VideoReceiver::recordingChanged, this, [this](bool active){
148 149 150 151 152 153 154
        _recording = active;
        if (!active) {
            _subtitleWriter.stopCapturingTelemetry();
        }
        emit recordingChanged();
    });

155
    connect(_videoReceiver[0], &VideoReceiver::recordingStarted, this, [this](){
156 157 158
        _subtitleWriter.startCapturingTelemetry(_videoFile);
    });

159
    connect(_videoReceiver[0], &VideoReceiver::videoSizeChanged, this, [this](QSize size){
160 161 162 163
        _videoSize = ((quint32)size.width() << 16) | (quint32)size.height();
        emit videoSizeChanged();
    });

164 165 166 167
    //connect(_videoReceiver, &VideoReceiver::onTakeScreenshotComplete, this, [this](VideoReceiver::STATUS status){
    //    if (status == VideoReceiver::STATUS_OK) {
    //    }
    //});
168

169 170
    // FIXME: AV: I believe _thermalVideoReceiver should be handled just like _videoReceiver in terms of event
    // and I expect that it will be changed during multiple video stream activity
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    if (_videoReceiver[1] != nullptr) {
        connect(_videoReceiver[1], &VideoReceiver::timeout, this, [this](){
            _restartVideo(1);
        });

        connect(_videoReceiver[1], &VideoReceiver::streamingChanged, this, [this](bool active){
            _restartVideo(1);
        });

        connect(_videoReceiver[1], &VideoReceiver::onStartComplete, this, [this](VideoReceiver::STATUS status) {
            if (status == VideoReceiver::STATUS_OK) {
                _videoStarted[1] = true;
                _videoReceiver[1]->startDecoding(_videoSink[1]);
            } else if (status == VideoReceiver::STATUS_INVALID_URL) {
                // Invalid URL - don't restart
            } else if (status == VideoReceiver::STATUS_INVALID_STATE) {
                // Already running
            } else {
                _restartVideo(1);
            }
191 192
        });

193 194
        connect(_videoReceiver[1], &VideoReceiver::onStopComplete, this, [this](VideoReceiver::STATUS) {
            _videoStarted[1] = false;
195 196
            _startReceiver(1);
        });
197
    }
198
#endif
199 200
    _updateSettings(0);
    _updateSettings(1);
201
    if(isGStreamer()) {
202
        startVideo();
203
    } else {
204
        stopVideo();
205 206
    }

207
#endif
208 209
}

210
void VideoManager::_cleanupOldVideos()
211 212 213 214 215 216 217 218 219 220 221 222
{
#if defined(QGC_GST_STREAMING)
    //-- Only perform cleanup if storage limit is enabled
    if(!_videoSettings->enableStorageLimit()->rawValue().toBool()) {
        return;
    }
    QString savePath = qgcApp()->toolbox()->settingsManager()->appSettings()->videoSavePath();
    QDir videoDir = QDir(savePath);
    videoDir.setFilter(QDir::Files | QDir::Readable | QDir::NoSymLinks | QDir::Writable);
    videoDir.setSorting(QDir::Time);

    QStringList nameFilters;
223 224 225

    for(size_t i = 0; i < sizeof(kFileExtension) / sizeof(kFileExtension[0]); i += 1) {
        nameFilters << QString("*.") + kFileExtension[i];
226
    }
227

228 229 230 231 232 233 234 235 236 237 238 239 240 241
    videoDir.setNameFilters(nameFilters);
    //-- get the list of videos stored
    QFileInfoList vidList = videoDir.entryInfoList();
    if(!vidList.isEmpty()) {
        uint64_t total   = 0;
        //-- Settings are stored using MB
        uint64_t maxSize = _videoSettings->maxVideoSize()->rawValue().toUInt() * 1024 * 1024;
        //-- Compute total used storage
        for(int i = 0; i < vidList.size(); i++) {
            total += vidList[i].size();
        }
        //-- Remove old movies until max size is satisfied.
        while(total >= maxSize && !vidList.isEmpty()) {
            total -= vidList.last().size();
242
            qCDebug(VideoManagerLog) << "Removing old video file:" << vidList.last().filePath();
243 244 245 246 247 248 249 250
            QFile file (vidList.last().filePath());
            file.remove();
            vidList.removeLast();
        }
    }
#endif
}

251 252 253 254
//-----------------------------------------------------------------------------
void
VideoManager::startVideo()
{
255 256 257 258 259
    if (qgcApp()->runningUnitTests()) {
        return;
    }

    if(!_videoSettings->streamEnabled()->rawValue().toBool() || !_videoSettings->streamConfigured()) {
260
        qCDebug(VideoManagerLog) << "Stream not enabled/configured";
261 262 263
        return;
    }

264 265
    _startReceiver(0);
    _startReceiver(1);
266 267 268 269 270 271
}

//-----------------------------------------------------------------------------
void
VideoManager::stopVideo()
{
272 273 274
    if (qgcApp()->runningUnitTests()) {
        return;
    }
275

276 277
    _stopReceiver(1);
    _stopReceiver(0);
278 279
}

280 281 282 283 284 285
void
VideoManager::startRecording(const QString& videoFile)
{
    if (qgcApp()->runningUnitTests()) {
        return;
    }
286
#if defined(QGC_GST_STREAMING)
287
    if (!_videoReceiver[0]) {
288
        qgcApp()->showAppMessage(tr("Video receiver is not ready."));
289 290 291 292 293 294
        return;
    }

    const VideoReceiver::FILE_FORMAT fileFormat = static_cast<VideoReceiver::FILE_FORMAT>(_videoSettings->recordingFormat()->rawValue().toInt());

    if(fileFormat < VideoReceiver::FILE_FORMAT_MIN || fileFormat >= VideoReceiver::FILE_FORMAT_MAX) {
295
        qgcApp()->showAppMessage(tr("Invalid video format defined."));
296 297 298 299 300 301 302 303 304
        return;
    }

    //-- Disk usage maintenance
    _cleanupOldVideos();

    QString savePath = qgcApp()->toolbox()->settingsManager()->appSettings()->videoSavePath();

    if(savePath.isEmpty()) {
305
        qgcApp()->showAppMessage(tr("Unabled to record video. Video save path must be specified in Settings."));
306 307 308 309 310 311 312
        return;
    }

    _videoFile = savePath + "/"
            + (videoFile.isEmpty() ? QDateTime::currentDateTime().toString("yyyy-MM-dd_hh.mm.ss") : videoFile)
            + "." + kFileExtension[fileFormat - VideoReceiver::FILE_FORMAT_MIN];

313
    _videoReceiver[0]->startRecording(_videoFile, fileFormat);
314 315 316
#else
    Q_UNUSED(videoFile)
#endif
317 318 319 320 321 322 323 324
}

void
VideoManager::stopRecording()
{
    if (qgcApp()->runningUnitTests()) {
        return;
    }
325
#if defined(QGC_GST_STREAMING)
326
    if (!_videoReceiver[0]) {
327 328 329
        return;
    }

330
    _videoReceiver[0]->stopRecording();
331
#endif
332 333 334 335 336 337 338 339
}

void
VideoManager::grabImage(const QString& imageFile)
{
    if (qgcApp()->runningUnitTests()) {
        return;
    }
340
#if defined(QGC_GST_STREAMING)
341
    if (!_videoReceiver[0]) {
342 343 344 345 346 347 348
        return;
    }

    _imageFile = imageFile;

    emit imageFileChanged();

349
    _videoReceiver[0]->takeScreenshot(_imageFile);
350 351 352
#else
    Q_UNUSED(imageFile)
#endif
353 354
}

355 356 357
//-----------------------------------------------------------------------------
double VideoManager::aspectRatio()
{
358
    if(_activeVehicle && _activeVehicle->dynamicCameras()) {
359
        QGCVideoStreamInfo* pInfo = _activeVehicle->dynamicCameras()->currentStreamInstance();
360 361 362 363 364
        if(pInfo) {
            qCDebug(VideoManagerLog) << "Primary AR: " << pInfo->aspectRatio();
            return pInfo->aspectRatio();
        }
    }
365
    // FIXME: AV: use _videoReceiver->videoSize() to calculate AR (if AR is not specified in the settings?)
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
    return _videoSettings->aspectRatio()->rawValue().toDouble();
}

//-----------------------------------------------------------------------------
double VideoManager::thermalAspectRatio()
{
    if(_activeVehicle && _activeVehicle->dynamicCameras()) {
        QGCVideoStreamInfo* pInfo = _activeVehicle->dynamicCameras()->thermalStreamInstance();
        if(pInfo) {
            qCDebug(VideoManagerLog) << "Thermal AR: " << pInfo->aspectRatio();
            return pInfo->aspectRatio();
        }
    }
    return 1.0;
}

//-----------------------------------------------------------------------------
double VideoManager::hfov()
{
    if(_activeVehicle && _activeVehicle->dynamicCameras()) {
        QGCVideoStreamInfo* pInfo = _activeVehicle->dynamicCameras()->currentStreamInstance();
        if(pInfo) {
            return pInfo->hfov();
        }
    }
    return 1.0;
}

//-----------------------------------------------------------------------------
double VideoManager::thermalHfov()
{
    if(_activeVehicle && _activeVehicle->dynamicCameras()) {
        QGCVideoStreamInfo* pInfo = _activeVehicle->dynamicCameras()->thermalStreamInstance();
399 400 401 402 403 404 405
        if(pInfo) {
            return pInfo->aspectRatio();
        }
    }
    return _videoSettings->aspectRatio()->rawValue().toDouble();
}

406 407 408 409 410 411 412 413 414 415 416 417 418
//-----------------------------------------------------------------------------
bool
VideoManager::hasThermal()
{
    if(_activeVehicle && _activeVehicle->dynamicCameras()) {
        QGCVideoStreamInfo* pInfo = _activeVehicle->dynamicCameras()->thermalStreamInstance();
        if(pInfo) {
            return true;
        }
    }
    return false;
}

419 420 421 422 423 424 425
//-----------------------------------------------------------------------------
QString
VideoManager::imageFile()
{
    return _imageFile;
}

426 427 428 429
//-----------------------------------------------------------------------------
bool
VideoManager::autoStreamConfigured()
{
Gus Grubba's avatar
Gus Grubba committed
430
#if defined(QGC_GST_STREAMING)
431
    if(_activeVehicle && _activeVehicle->dynamicCameras()) {
432 433 434
        QGCVideoStreamInfo* pInfo = _activeVehicle->dynamicCameras()->currentStreamInstance();
        if(pInfo) {
            return !pInfo->uri().isEmpty();
435 436
        }
    }
Gus Grubba's avatar
Gus Grubba committed
437
#endif
438
    return false;
439 440
}

Gus Grubba's avatar
Gus Grubba committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
//-----------------------------------------------------------------------------
void
VideoManager::_updateUVC()
{
#ifndef QGC_DISABLE_UVC
    QString videoSource = _videoSettings->videoSource()->rawValue().toString();
    QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
    for (const QCameraInfo &cameraInfo: cameras) {
        if(cameraInfo.description() == videoSource) {
            _videoSourceID = cameraInfo.deviceName();
            emit videoSourceIDChanged();
            qCDebug(VideoManagerLog) << "Found USB source:" << _videoSourceID << " Name:" << videoSource;
            break;
        }
    }
#endif
}

459 460 461
//-----------------------------------------------------------------------------
void
VideoManager::_videoSourceChanged()
462
{
Gus Grubba's avatar
Gus Grubba committed
463
    _updateUVC();
464 465
    emit hasVideoChanged();
    emit isGStreamerChanged();
466
    emit isAutoStreamChanged();
467
    _restartVideo(0);
468 469
}

470 471 472
//-----------------------------------------------------------------------------
void
VideoManager::_udpPortChanged()
473
{
474
    _restartVideo(0);
475 476
}

477 478
//-----------------------------------------------------------------------------
void
479
VideoManager::_rtspUrlChanged()
480
{
481
    _restartVideo(0);
482 483
}

484 485 486 487
//-----------------------------------------------------------------------------
void
VideoManager::_tcpUrlChanged()
{
488
    _restartVideo(0);
489 490
}

491 492 493 494
//-----------------------------------------------------------------------------
void
VideoManager::_lowLatencyModeChanged()
{
DoinLakeFlyer's avatar
DoinLakeFlyer committed
495
    //restartVideo();
496 497
}

498 499 500 501
//-----------------------------------------------------------------------------
bool
VideoManager::hasVideo()
{
502 503 504
    if(autoStreamConfigured()) {
        return true;
    }
505
    QString videoSource = _videoSettings->videoSource()->rawValue().toString();
506
    return !videoSource.isEmpty() && videoSource != VideoSettings::videoSourceNoVideo && videoSource != VideoSettings::videoDisabled;
507 508 509 510 511 512 513
}

//-----------------------------------------------------------------------------
bool
VideoManager::isGStreamer()
{
#if defined(QGC_GST_STREAMING)
514
    QString videoSource = _videoSettings->videoSource()->rawValue().toString();
515
    return
Gus Grubba's avatar
Gus Grubba committed
516 517
        videoSource == VideoSettings::videoSourceUDPH264 ||
        videoSource == VideoSettings::videoSourceUDPH265 ||
518
        videoSource == VideoSettings::videoSourceRTSP ||
519
        videoSource == VideoSettings::videoSourceTCP ||
520 521
        videoSource == VideoSettings::videoSourceMPEGTS ||
        autoStreamConfigured();
522 523 524 525 526
#else
    return false;
#endif
}

527 528 529 530 531 532 533 534 535
//-----------------------------------------------------------------------------
#ifndef QGC_DISABLE_UVC
bool
VideoManager::uvcEnabled()
{
    return QCameraInfo::availableCameras().count() > 0;
}
#endif

536 537 538 539 540 541 542 543 544 545 546 547 548 549
//-----------------------------------------------------------------------------
void
VideoManager::setfullScreen(bool f)
{
    if(f) {
        //-- No can do if no vehicle or connection lost
        if(!_activeVehicle || _activeVehicle->connectionLost()) {
            f = false;
        }
    }
    _fullScreen = f;
    emit fullScreenChanged();
}

550
//-----------------------------------------------------------------------------
551 552 553 554
void
VideoManager::_initVideo()
{
#if defined(QGC_GST_STREAMING)
555 556 557
    QQuickItem* root = qgcApp()->mainRootWindow();

    if (root == nullptr) {
558
        qCDebug(VideoManagerLog) << "mainRootWindow() failed. No root window";
559 560 561 562 563
        return;
    }

    QQuickItem* widget = root->findChild<QQuickItem*>("videoContent");

564 565 566
    if (widget != nullptr && _videoReceiver[0] != nullptr) {
        _videoSink[0] = qgcApp()->toolbox()->corePlugin()->createVideoSink(this, widget);
        if (_videoSink[0] == nullptr) {
567
            qCDebug(VideoManagerLog) << "createVideoSink() failed";
568
        }
569
    } else {
570
        qCDebug(VideoManagerLog) << "video receiver disabled";
571 572 573 574
    }

    widget = root->findChild<QQuickItem*>("thermalVideo");

575 576 577
    if (widget != nullptr && _videoReceiver[1] != nullptr) {
        _videoSink[1] = qgcApp()->toolbox()->corePlugin()->createVideoSink(this, widget);
        if (_videoSink[1] == nullptr) {
578
            qCDebug(VideoManagerLog) << "createVideoSink() failed";
579
        }
580
    } else {
581
        qCDebug(VideoManagerLog) << "thermal video receiver disabled";
582
    }
583 584 585
#endif
}

586
//-----------------------------------------------------------------------------
587
bool
588
VideoManager::_updateSettings(unsigned id)
589
{
590
    if(!_videoSettings)
591
        return false;
592
    //-- Auto discovery
593
    if(_activeVehicle && _activeVehicle->dynamicCameras()) {
594
        QGCVideoStreamInfo* pInfo = _activeVehicle->dynamicCameras()->currentStreamInstance();
595
        if(pInfo) {
596
            bool status = false;
597 598 599
            if (id == 0) {
                qCDebug(VideoManagerLog) << "Configure primary stream:" << pInfo->uri();
                switch(pInfo->type()) {
600
                    case VIDEO_STREAM_TYPE_RTSP:
601 602 603 604
                        if ((status = _updateVideoUri(id, pInfo->uri()))) {
                            _toolbox->settingsManager()->videoSettings()->videoSource()->setRawValue(VideoSettings::videoSourceRTSP);
                        }
                        break;
605
                    case VIDEO_STREAM_TYPE_TCP_MPEG:
606 607 608
                        if ((status = _updateVideoUri(id, pInfo->uri()))) {
                            _toolbox->settingsManager()->videoSettings()->videoSource()->setRawValue(VideoSettings::videoSourceTCP);
                        }
609 610
                        break;
                    case VIDEO_STREAM_TYPE_RTPUDP:
611 612 613
                        if ((status = _updateVideoUri(id, QStringLiteral("udp://0.0.0.0:%1").arg(pInfo->uri())))) {
                            _toolbox->settingsManager()->videoSettings()->videoSource()->setRawValue(VideoSettings::videoSourceUDPH264);
                        }
614 615
                        break;
                    case VIDEO_STREAM_TYPE_MPEG_TS_H264:
616 617 618
                        if ((status = _updateVideoUri(id, QStringLiteral("mpegts://0.0.0.0:%1").arg(pInfo->uri())))) {
                            _toolbox->settingsManager()->videoSettings()->videoSource()->setRawValue(VideoSettings::videoSourceMPEGTS);
                        }
619 620
                        break;
                    default:
621
                        status = _updateVideoUri(id, pInfo->uri());
622 623 624
                        break;
                }
            }
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
            else if (id == 1) { //-- Thermal stream (if any)
                QGCVideoStreamInfo* pTinfo = _activeVehicle->dynamicCameras()->thermalStreamInstance();
                if (pTinfo) {
                    qCDebug(VideoManagerLog) << "Configure secondary stream:" << pTinfo->uri();
                    switch(pTinfo->type()) {
                        case VIDEO_STREAM_TYPE_RTSP:
                        case VIDEO_STREAM_TYPE_TCP_MPEG:
                            status |= _updateVideoUri(id, pTinfo->uri());
                            break;
                        case VIDEO_STREAM_TYPE_RTPUDP:
                            status |= _updateVideoUri(id, QStringLiteral("udp://0.0.0.0:%1").arg(pTinfo->uri()));
                            break;
                        case VIDEO_STREAM_TYPE_MPEG_TS_H264:
                            status |= _updateVideoUri(id, QStringLiteral("mpegts://0.0.0.0:%1").arg(pTinfo->uri()));
                            break;
                        default:
                            status |= _updateVideoUri(id, pTinfo->uri());
                            break;
                    }
                }
            }
646
            return status;
647 648
        }
    }
649
    QString source = _videoSettings->videoSource()->rawValue().toString();
Gus Grubba's avatar
Gus Grubba committed
650
    if (source == VideoSettings::videoSourceUDPH264)
651
        return _updateVideoUri(0, QStringLiteral("udp://0.0.0.0:%1").arg(_videoSettings->udpPort()->rawValue().toInt()));
Gus Grubba's avatar
Gus Grubba committed
652
    else if (source == VideoSettings::videoSourceUDPH265)
653
        return _updateVideoUri(0, QStringLiteral("udp265://0.0.0.0:%1").arg(_videoSettings->udpPort()->rawValue().toInt()));
654
    else if (source == VideoSettings::videoSourceMPEGTS)
655
        return _updateVideoUri(0, QStringLiteral("mpegts://0.0.0.0:%1").arg(_videoSettings->udpPort()->rawValue().toInt()));
656
    else if (source == VideoSettings::videoSourceRTSP)
657
        return _updateVideoUri(0, _videoSettings->rtspUrl()->rawValue().toString());
658
    else if (source == VideoSettings::videoSourceTCP)
659
        return _updateVideoUri(0, QStringLiteral("tcp://%1").arg(_videoSettings->tcpUrl()->rawValue().toString()));
660

661
    return false;
662 663
}

664
//-----------------------------------------------------------------------------
665
bool
666
VideoManager::_updateVideoUri(unsigned id, const QString& uri)
667 668 669 670
{
#if defined(QGC_GST_TAISYNC_ENABLED) && (defined(__android__) || defined(__ios__))
    //-- Taisync on iOS or Android sends a raw h.264 stream
    if (isTaisync()) {
671 672 673 674 675 676 677 678 679 680
        if (id == 0) {
            return _updateVideoUri(0, QString("tsusb://0.0.0.0:%1").arg(TAISYNC_VIDEO_UDP_PORT));
        } if (id == 1) {
            // FIXME: AV: TAISYNC_VIDEO_UDP_PORT is used by video stream, thermal stream should go via its own proxy
            if (!_videoUri[1].isEmpty()) {
                _videoUri[1].clear();
                return true;
            } else {
                return false;
            }
Andrew Voznytsa's avatar
Andrew Voznytsa committed
681
        }
682 683
    }
#endif
684
    if (uri == _videoUri[id]) {
685
        return false;
686 687
    }

688
    _videoUri[id] = uri;
689

690
    return true;
691 692
}

693
//-----------------------------------------------------------------------------
694
void
695
VideoManager::_restartVideo(unsigned id)
696
{
697
#if defined(QGC_GST_STREAMING)
698 699 700 701 702 703
    QString oldUri = _videoUri[id];
    _updateSettings(id);
    QString newUri = _videoUri[id];

    if (oldUri == newUri && _videoStarted[id]) {
        qCDebug(VideoManagerLog) << "No sense to restart video streaming, skipped"  << id;
704 705 706
        return;
    }

707
    qCDebug(VideoManagerLog) << "Restart video streaming"  << id;
708

709 710
    if (_videoStarted[id]) {
        _stopReceiver(id);
711
    } else {
712
        _startReceiver(id);
713
    }
714 715
#endif
}
716

717 718 719 720 721 722 723 724
//-----------------------------------------------------------------------------
void
VideoManager::_restartAllVideos()
{
    _restartVideo(0);
    _restartVideo(1);
}

725 726 727 728 729 730 731
//----------------------------------------------------------------------------------------
void
VideoManager::_startReceiver(unsigned id)
{
#if defined(QGC_GST_STREAMING)
    const unsigned timeout = _videoSettings->rtspTimeout()->rawValue().toUInt();

732
    if (id > 1) {
733
        qCDebug(VideoManagerLog) << "Unsupported receiver id" << id;
734 735 736 737
    } else if (_videoReceiver[id] != nullptr && _videoSink[id] != nullptr) {
        if (!_videoUri[id].isEmpty()) {
            _videoReceiver[id]->start(_videoUri[id], timeout);
        }
738 739 740 741 742 743 744 745 746
    }
#endif
}

//----------------------------------------------------------------------------------------
void
VideoManager::_stopReceiver(unsigned id)
{
#if defined(QGC_GST_STREAMING)
747
    if (id > 1) {
748
        qCDebug(VideoManagerLog) << "Unsupported receiver id" << id;
749 750
    } else if (_videoReceiver[id] != nullptr) {
        _videoReceiver[id]->stop();
751 752 753 754
    }
#endif
}

755 756 757 758 759
//----------------------------------------------------------------------------------------
void
VideoManager::_setActiveVehicle(Vehicle* vehicle)
{
    if(_activeVehicle) {
760
        disconnect(_activeVehicle, &Vehicle::connectionLostChanged, this, &VideoManager::_connectionLostChanged);
761 762 763 764 765
        if(_activeVehicle->dynamicCameras()) {
            QGCCameraControl* pCamera = _activeVehicle->dynamicCameras()->currentCameraInstance();
            if(pCamera) {
                pCamera->stopStream();
            }
766
            disconnect(_activeVehicle->dynamicCameras(), &QGCCameraManager::streamChanged, this, &VideoManager::_restartAllVideos);
767
        }
768 769 770
    }
    _activeVehicle = vehicle;
    if(_activeVehicle) {
771
        connect(_activeVehicle, &Vehicle::connectionLostChanged, this, &VideoManager::_connectionLostChanged);
772
        if(_activeVehicle->dynamicCameras()) {
773
            connect(_activeVehicle->dynamicCameras(), &QGCCameraManager::streamChanged, this, &VideoManager::_restartAllVideos);
774 775 776 777
            QGCCameraControl* pCamera = _activeVehicle->dynamicCameras()->currentCameraInstance();
            if(pCamera) {
                pCamera->resumeStream();
            }
778
        }
779 780 781
    } else {
        //-- Disable full screen video if vehicle is gone
        setfullScreen(false);
782
    }
783
    emit autoStreamConfiguredChanged();
784
    _restartAllVideos();
785 786
}

787 788 789 790 791 792 793 794 795 796
//----------------------------------------------------------------------------------------
void
VideoManager::_connectionLostChanged(bool connectionLost)
{
    if(connectionLost) {
        //-- Disable full screen video if connection is lost
        setfullScreen(false);
    }
}

797 798
//----------------------------------------------------------------------------------------
void
799
VideoManager::_aspectRatioChanged()
800
{
801
    emit aspectRatioChanged();
802
}