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


/**
 * @file
 *   @brief QGC Video Receiver
 *   @author Gus Grubba <mavlink@grubba.com>
 */

#include "VideoReceiver.h"
18 19
#include "SettingsManager.h"
#include "QGCApplication.h"
20
#include "VideoManager.h"
21 22 23
#ifdef QGC_GST_TAISYNC_ENABLED
#include "TaisyncHandler.h"
#endif
Gus Grubba's avatar
Gus Grubba committed
24
#include <QDebug>
25
#include <QUrl>
26 27
#include <QDir>
#include <QDateTime>
28
#include <QSysInfo>
29

30 31
QGC_LOGGING_CATEGORY(VideoReceiverLog, "VideoReceiverLog")

32 33
#if defined(QGC_GST_STREAMING)

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
static const char* kVideoExtensions[] =
{
    "mkv",
    "mov",
    "mp4"
};

static const char* kVideoMuxes[] =
{
    "matroskamux",
    "qtmux",
    "mp4mux"
};

#define NUM_MUXES (sizeof(kVideoMuxes) / sizeof(char*))

50 51 52
#endif


Gus Grubba's avatar
Gus Grubba committed
53 54
VideoReceiver::VideoReceiver(QObject* parent)
    : QObject(parent)
55
#if defined(QGC_GST_STREAMING)
56
    , _running(false)
57
    , _recording(false)
58
    , _streaming(false)
59 60
    , _starting(false)
    , _stopping(false)
61
    , _stop(true)
Gus Grubba's avatar
Gus Grubba committed
62 63 64 65 66
    , _sink(nullptr)
    , _tee(nullptr)
    , _pipeline(nullptr)
    , _pipelineStopRec(nullptr)
    , _videoSink(nullptr)
67
    , _restart_time_ms(1389)
68
    , _udpReconnect_us(5000000)
69
#endif
Gus Grubba's avatar
Gus Grubba committed
70
    , _videoSurface(nullptr)
71 72
    , _videoRunning(false)
    , _showFullScreen(false)
Gus Grubba's avatar
Gus Grubba committed
73
    , _videoSettings(nullptr)
74 75
    , _hwDecoderName(nullptr)
    , _swDecoderName("avdec_h264")
Gus Grubba's avatar
Gus Grubba committed
76
{
77
    _videoSurface = new VideoSurface;
Gus Grubba's avatar
Gus Grubba committed
78
    _videoSettings = qgcApp()->toolbox()->settingsManager()->videoSettings();
79
#if defined(QGC_GST_STREAMING)
80
    setVideoDecoder(H264_SW);
81
    _setVideoSink(_videoSurface->videoSink());
82 83
    _restart_timer.setSingleShot(true);
    connect(&_restart_timer, &QTimer::timeout, this, &VideoReceiver::_restart_timeout);
84 85 86
    connect(this, &VideoReceiver::msgErrorReceived, this, &VideoReceiver::_handleError);
    connect(this, &VideoReceiver::msgEOSReceived, this, &VideoReceiver::_handleEOS);
    connect(this, &VideoReceiver::msgStateChangedReceived, this, &VideoReceiver::_handleStateChanged);
87 88
    connect(&_frameTimer, &QTimer::timeout, this, &VideoReceiver::_updateTimer);
    _frameTimer.start(1000);
89
#endif
Gus Grubba's avatar
Gus Grubba committed
90 91 92 93
}

VideoReceiver::~VideoReceiver()
{
94
#if defined(QGC_GST_STREAMING)
95
    stop();
96 97 98
    if (_videoSink) {
        gst_object_unref(_videoSink);
    }
99
#endif
100 101
    if(_videoSurface)
        delete _videoSurface;
Gus Grubba's avatar
Gus Grubba committed
102 103
}

104
#if defined(QGC_GST_STREAMING)
105 106
void
VideoReceiver::_setVideoSink(GstElement* sink)
Gus Grubba's avatar
Gus Grubba committed
107 108 109
{
    if (_videoSink) {
        gst_object_unref(_videoSink);
Gus Grubba's avatar
Gus Grubba committed
110
        _videoSink = nullptr;
Gus Grubba's avatar
Gus Grubba committed
111 112 113 114 115 116
    }
    if (sink) {
        _videoSink = sink;
        gst_object_ref_sink(_videoSink);
    }
}
117
#endif
Gus Grubba's avatar
Gus Grubba committed
118

119 120 121 122 123 124 125 126 127
//-----------------------------------------------------------------------------
void
VideoReceiver::grabImage(QString imageFile)
{
    _imageFile = imageFile;
    emit imageFileChanged();
}

//-----------------------------------------------------------------------------
128
#if defined(QGC_GST_STREAMING)
129 130
static void
newPadCB(GstElement* element, GstPad* pad, gpointer data)
131
{
132
    gchar* name = gst_pad_get_name(pad);
133
    //g_print("A new pad %s was created\n", name);
134 135
    GstCaps* p_caps = gst_pad_get_pad_template_caps (pad);
    gchar* description = gst_caps_to_string(p_caps);
136
    qCDebug(VideoReceiverLog) << p_caps << ", " << description;
137
    g_free(description);
138 139
    GstElement* sink = GST_ELEMENT(data);
    if(gst_element_link_pads(element, name, sink, "sink") == false)
140 141 142 143
        qCritical() << "newPadCB : failed to link elements\n";
    g_free(name);
}

144 145
//-----------------------------------------------------------------------------
void
146
VideoReceiver::_restart_timeout()
147
{
148
    qgcApp()->toolbox()->videoManager()->restartVideo();
149
}
150
#endif
151

152
//-----------------------------------------------------------------------------
153 154 155 156 157 158 159 160
// When we finish our pipeline will look like this:
//
//                                   +-->queue-->decoder-->_videosink
//                                   |
//    datasource-->demux-->parser-->tee
//                                   ^
//                                   |
//                                   +-Here we will later link elements for recording
161 162
void
VideoReceiver::start()
Gus Grubba's avatar
Gus Grubba committed
163
{
164 165 166 167
    if (_uri.isEmpty()) {
        return;
    }
    qCDebug(VideoReceiverLog) << "start():" << _uri;
Gus Grubba's avatar
Gus Grubba committed
168
    if(qgcApp()->runningUnitTests()) {
169 170
        return;
    }
171 172
    if(!_videoSettings->streamEnabled()->rawValue().toBool() ||
       !_videoSettings->streamConfigured()) {
173 174 175
        qCDebug(VideoReceiverLog) << "start() but not enabled/configured";
        return;
    }
176

177
#if defined(QGC_GST_STREAMING)
178
    _stop = false;
179

180
#if defined(QGC_GST_TAISYNC_ENABLED) && (defined(__android__) || defined(__ios__))
181
    //-- Taisync on iOS or Android sends a raw h.264 stream
182 183 184 185
    bool isTaisyncUSB = qgcApp()->toolbox()->videoManager()->isTaisync();
#else
    bool isTaisyncUSB = false;
#endif
Gus Grubba's avatar
Gus Grubba committed
186 187
    bool isUdp264   = _uri.contains("udp://")  && !isTaisyncUSB;
    bool isUdp265   = _uri.contains("udp265://")  && !isTaisyncUSB;
188 189
    bool isTCP      = _uri.contains("tcp://")  && !isTaisyncUSB;
    bool isMPEGTS   = _uri.contains("mpegts://")  && !isTaisyncUSB;
190 191

    if (!isTaisyncUSB && _uri.isEmpty()) {
Gus Grubba's avatar
Gus Grubba committed
192 193 194
        qCritical() << "VideoReceiver::start() failed because URI is not specified";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
195
    if (_videoSink == nullptr) {
Gus Grubba's avatar
Gus Grubba committed
196 197 198
        qCritical() << "VideoReceiver::start() failed because video sink is not set";
        return;
    }
199 200 201 202
    if(_running) {
        qCDebug(VideoReceiverLog) << "Already running!";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
203

204
    _starting = true;
205

206
    bool running    = false;
207
    bool pipelineUp = false;
Gus Grubba's avatar
Gus Grubba committed
208

Gus Grubba's avatar
Gus Grubba committed
209 210 211 212 213 214 215
    GstElement*     dataSource  = nullptr;
    GstCaps*        caps        = nullptr;
    GstElement*     demux       = nullptr;
    GstElement*     parser      = nullptr;
    GstElement*     queue       = nullptr;
    GstElement*     decoder     = nullptr;
    GstElement*     queue1      = nullptr;
216

Gus Grubba's avatar
Gus Grubba committed
217
    do {
Gus Grubba's avatar
Gus Grubba committed
218
        if ((_pipeline = gst_pipeline_new("receiver")) == nullptr) {
219
            qCritical() << "VideoReceiver::start() failed. Error with gst_pipeline_new()";
Gus Grubba's avatar
Gus Grubba committed
220 221 222
            break;
        }

Gus Grubba's avatar
Gus Grubba committed
223
        if(isUdp264 || isUdp265 || isMPEGTS || isTaisyncUSB) {
224
            dataSource = gst_element_factory_make("udpsrc", "udp-source");
225 226
        } else if(isTCP) {
            dataSource = gst_element_factory_make("tcpclientsrc", "tcpclient-source");
227 228
        } else {
            dataSource = gst_element_factory_make("rtspsrc", "rtsp-source");
Gus Grubba's avatar
Gus Grubba committed
229 230
        }

231 232
        if (!dataSource) {
            qCritical() << "VideoReceiver::start() failed. Error with data source for gst_element_factory_make()";
Gus Grubba's avatar
Gus Grubba committed
233 234 235
            break;
        }

Gus Grubba's avatar
Gus Grubba committed
236
        if(isUdp264) {
Gus Grubba's avatar
Gus Grubba committed
237
            if ((caps = gst_caps_from_string("application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264")) == nullptr) {
238 239 240
                qCritical() << "VideoReceiver::start() failed. Error with gst_caps_from_string()";
                break;
            }
241
            g_object_set(static_cast<gpointer>(dataSource), "uri", qPrintable(_uri), "caps", caps, nullptr);
Gus Grubba's avatar
Gus Grubba committed
242 243 244 245 246 247
        } else if(isUdp265) {


            //-- TODO


248
#if  defined(QGC_GST_TAISYNC_ENABLED) && (defined(__android__) || defined(__ios__))
249 250 251 252 253
        } else if(isTaisyncUSB) {
            QString uri = QString("0.0.0.0:%1").arg(TAISYNC_VIDEO_UDP_PORT);
            qCDebug(VideoReceiverLog) << "Taisync URI:" << uri;
            g_object_set(static_cast<gpointer>(dataSource), "port", TAISYNC_VIDEO_UDP_PORT, nullptr);
#endif
254 255
        } else if(isTCP) {
            QUrl url(_uri);
256
            g_object_set(static_cast<gpointer>(dataSource), "host", qPrintable(url.host()), "port", url.port(), nullptr );
257 258 259
        } else if(isMPEGTS) {
            QUrl url(_uri);
            g_object_set(static_cast<gpointer>(dataSource), "port", url.port(), nullptr);
260
        } else {
261
            g_object_set(static_cast<gpointer>(dataSource), "location", qPrintable(_uri), "latency", 17, "udp-reconnect", 1, "timeout", _udpReconnect_us, NULL);
262
        }
Gus Grubba's avatar
Gus Grubba committed
263

264 265
        if (isTCP || isMPEGTS) {
            if ((demux = gst_element_factory_make("tsdemux", "mpeg-ts-demuxer")) == nullptr) {
266 267 268 269
                qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('tsdemux')";
                break;
            }
        } else {
270
            if(!isTaisyncUSB) {
271 272
                if ((demux = gst_element_factory_make(_depayName, "rtp-depacketizer")) == nullptr) {
                   qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('" << _depayName << "')";
273 274
                    break;
                }
275
            }
276 277
        }

278 279
        if ((parser = gst_element_factory_make(_parserName, "parser")) == nullptr) {
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('" << _parserName << "')";
Gus Grubba's avatar
Gus Grubba committed
280 281 282
            break;
        }

Gus Grubba's avatar
Gus Grubba committed
283
        if((_tee = gst_element_factory_make("tee", nullptr)) == nullptr)  {
284 285 286
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('tee')";
            break;
        }
Gus Grubba's avatar
Gus Grubba committed
287

Gus Grubba's avatar
Gus Grubba committed
288
        if((queue = gst_element_factory_make("queue", nullptr)) == nullptr)  {
289 290
            // TODO: We may want to add queue2 max-size-buffers=1 to get lower latency
            //       We should compare gstreamer scripts to QGroundControl to determine the need
291
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('queue')";
292 293
            break;
        }
294

295 296 297 298 299 300
        if (!_hwDecoderName || (decoder = gst_element_factory_make(_hwDecoderName, "decoder")) == nullptr) {
            qWarning() << "VideoReceiver::start() hardware decoding not available " << ((_hwDecoderName) ? _hwDecoderName : "");
            if ((decoder = gst_element_factory_make(_swDecoderName, "decoder")) == nullptr) {
                qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('" << _swDecoderName << "')";
                break;
            }
301 302
        }

Gus Grubba's avatar
Gus Grubba committed
303
        if ((queue1 = gst_element_factory_make("queue", nullptr)) == nullptr) {
304 305 306 307
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('queue') [1]";
            break;
        }

308 309 310 311 312
        if(isTaisyncUSB) {
            gst_bin_add_many(GST_BIN(_pipeline), dataSource, parser, _tee, queue, decoder, queue1, _videoSink, nullptr);
        } else {
            gst_bin_add_many(GST_BIN(_pipeline), dataSource, demux, parser, _tee, queue, decoder, queue1, _videoSink, nullptr);
        }
313
        pipelineUp = true;
314

Gus Grubba's avatar
Gus Grubba committed
315
        if(isUdp264 || isUdp265) {
316
            // Link the pipeline in front of the tee
Gus Grubba's avatar
Gus Grubba committed
317
            if(!gst_element_link_many(dataSource, demux, parser, _tee, queue, decoder, queue1, _videoSink, nullptr)) {
318 319 320
                qCritical() << "Unable to link UDP elements.";
                break;
            }
321 322 323 324 325 326
        } else if(isTaisyncUSB) {
            // Link the pipeline in front of the tee
            if(!gst_element_link_many(dataSource, parser, _tee, queue, decoder, queue1, _videoSink, nullptr)) {
                qCritical() << "Unable to link Taisync USB elements.";
                break;
            }
327
        } else if (isTCP || isMPEGTS) {
328
            if(!gst_element_link(dataSource, demux)) {
329
                qCritical() << "Unable to link TCP/MPEG-TS dataSource to Demux.";
330 331
                break;
            }
Gus Grubba's avatar
Gus Grubba committed
332
            if(!gst_element_link_many(parser, _tee, queue, decoder, queue1, _videoSink, nullptr)) {
333
                qCritical() << "Unable to link TCP/MPEG-TS pipline to parser.";
334 335
                break;
            }
336
            g_signal_connect(demux, "pad-added", G_CALLBACK(newPadCB), parser);
337
        } else {
338
            g_signal_connect(dataSource, "pad-added", G_CALLBACK(newPadCB), demux);
Gus Grubba's avatar
Gus Grubba committed
339
            if(!gst_element_link_many(demux, parser, _tee, queue, decoder, _videoSink, nullptr)) {
340
                qCritical() << "Unable to link RTSP elements.";
341 342
                break;
            }
343 344
        }

Gus Grubba's avatar
Gus Grubba committed
345
        dataSource = demux = parser = queue = decoder = queue1 = nullptr;
Gus Grubba's avatar
Gus Grubba committed
346

Gus Grubba's avatar
Gus Grubba committed
347
        GstBus* bus = nullptr;
Gus Grubba's avatar
Gus Grubba committed
348

Gus Grubba's avatar
Gus Grubba committed
349
        if ((bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline))) != nullptr) {
350 351 352
            gst_bus_enable_sync_message_emission(bus);
            g_signal_connect(bus, "sync-message", G_CALLBACK(_onBusMessage), this);
            gst_object_unref(bus);
Gus Grubba's avatar
Gus Grubba committed
353
            bus = nullptr;
354
        }
Gus Grubba's avatar
Gus Grubba committed
355

356
        GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-paused");
Gus Grubba's avatar
Gus Grubba committed
357 358 359 360
        running = gst_element_set_state(_pipeline, GST_STATE_PLAYING) != GST_STATE_CHANGE_FAILURE;

    } while(0);

Gus Grubba's avatar
Gus Grubba committed
361
    if (caps != nullptr) {
Gus Grubba's avatar
Gus Grubba committed
362
        gst_caps_unref(caps);
Gus Grubba's avatar
Gus Grubba committed
363
        caps = nullptr;
Gus Grubba's avatar
Gus Grubba committed
364 365 366 367 368
    }

    if (!running) {
        qCritical() << "VideoReceiver::start() failed";

369
        // In newer versions, the pipeline will clean up all references that are added to it
Gus Grubba's avatar
Gus Grubba committed
370
        if (_pipeline != nullptr) {
371
            gst_object_unref(_pipeline);
Gus Grubba's avatar
Gus Grubba committed
372
            _pipeline = nullptr;
Gus Grubba's avatar
Gus Grubba committed
373 374
        }

375 376
        // If we failed before adding items to the pipeline, then clean up
        if (!pipelineUp) {
Gus Grubba's avatar
Gus Grubba committed
377
            if (decoder != nullptr) {
378
                gst_object_unref(decoder);
Gus Grubba's avatar
Gus Grubba committed
379
                decoder = nullptr;
380
            }
Gus Grubba's avatar
Gus Grubba committed
381

Gus Grubba's avatar
Gus Grubba committed
382
            if (parser != nullptr) {
383
                gst_object_unref(parser);
Gus Grubba's avatar
Gus Grubba committed
384
                parser = nullptr;
385
            }
Gus Grubba's avatar
Gus Grubba committed
386

Gus Grubba's avatar
Gus Grubba committed
387
            if (demux != nullptr) {
388
                gst_object_unref(demux);
Gus Grubba's avatar
Gus Grubba committed
389
                demux = nullptr;
390
            }
Gus Grubba's avatar
Gus Grubba committed
391

Gus Grubba's avatar
Gus Grubba committed
392
            if (dataSource != nullptr) {
393
                gst_object_unref(dataSource);
Gus Grubba's avatar
Gus Grubba committed
394
                dataSource = nullptr;
395
            }
396

Gus Grubba's avatar
Gus Grubba committed
397
            if (_tee != nullptr) {
398
                gst_object_unref(_tee);
Gus Grubba's avatar
Gus Grubba committed
399
                dataSource = nullptr;
400
            }
401

Gus Grubba's avatar
Gus Grubba committed
402
            if (queue != nullptr) {
403
                gst_object_unref(queue);
Gus Grubba's avatar
Gus Grubba committed
404
                dataSource = nullptr;
405
            }
Gus Grubba's avatar
Gus Grubba committed
406
        }
407 408 409

        _running = false;
    } else {
410
        GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-playing");
411 412
        _running = true;
        qCDebug(VideoReceiverLog) << "Running";
Gus Grubba's avatar
Gus Grubba committed
413
    }
414
    _starting = false;
415
#endif
Gus Grubba's avatar
Gus Grubba committed
416 417
}

418 419 420
//-----------------------------------------------------------------------------
void
VideoReceiver::stop()
Gus Grubba's avatar
Gus Grubba committed
421
{
422
    if(qgcApp() && qgcApp()->runningUnitTests()) {
423 424
        return;
    }
425
#if defined(QGC_GST_STREAMING)
426
    _stop = true;
427
    qCDebug(VideoReceiverLog) << "stop()";
428 429
    if(!_streaming) {
        _shutdownPipeline();
Gus Grubba's avatar
Gus Grubba committed
430
    } else if (_pipeline != nullptr && !_stopping) {
431 432 433 434
        qCDebug(VideoReceiverLog) << "Stopping _pipeline";
        gst_element_send_event(_pipeline, gst_event_new_eos());
        _stopping = true;
        GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline));
435
        GstMessage* message = gst_bus_timed_pop_filtered(bus, GST_CLOCK_TIME_NONE, (GstMessageType)(GST_MESSAGE_EOS|GST_MESSAGE_ERROR));
436
        gst_object_unref(bus);
437 438 439 440 441 442
        if(GST_MESSAGE_TYPE(message) == GST_MESSAGE_ERROR) {
            _shutdownPipeline();
            qCritical() << "Error stopping pipeline!";
        } else if(GST_MESSAGE_TYPE(message) == GST_MESSAGE_EOS) {
            _handleEOS();
        }
443
        gst_message_unref(message);
Gus Grubba's avatar
Gus Grubba committed
444
    }
445
#endif
Gus Grubba's avatar
Gus Grubba committed
446 447
}

448 449 450
//-----------------------------------------------------------------------------
void
VideoReceiver::setUri(const QString & uri)
Gus Grubba's avatar
Gus Grubba committed
451 452 453 454
{
    _uri = uri;
}

455
//-----------------------------------------------------------------------------
456
#if defined(QGC_GST_STREAMING)
457 458
void
VideoReceiver::_shutdownPipeline() {
459 460 461 462
    if(!_pipeline) {
        qCDebug(VideoReceiverLog) << "No pipeline";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
463 464
    GstBus* bus = nullptr;
    if ((bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline))) != nullptr) {
465 466
        gst_bus_disable_sync_message_emission(bus);
        gst_object_unref(bus);
Gus Grubba's avatar
Gus Grubba committed
467
        bus = nullptr;
468 469 470 471
    }
    gst_element_set_state(_pipeline, GST_STATE_NULL);
    gst_bin_remove(GST_BIN(_pipeline), _videoSink);
    gst_object_unref(_pipeline);
Gus Grubba's avatar
Gus Grubba committed
472
    _pipeline = nullptr;
473
    delete _sink;
Gus Grubba's avatar
Gus Grubba committed
474
    _sink = nullptr;
475 476 477 478 479 480
    _streaming = false;
    _recording = false;
    _stopping = false;
    _running = false;
    emit recordingChanged();
}
481
#endif
482

483
//-----------------------------------------------------------------------------
484
#if defined(QGC_GST_STREAMING)
485 486
void
VideoReceiver::_handleError() {
487
    qCDebug(VideoReceiverLog) << "Gstreamer error!";
488 489
    // If there was an error we switch to software decoding only
    _tryWithHardwareDecoding = false;
490
    stop();
491
    _restart_timer.start(_restart_time_ms);
492 493 494
}
#endif

495
//-----------------------------------------------------------------------------
496
#if defined(QGC_GST_STREAMING)
497 498
void
VideoReceiver::_handleEOS() {
499 500
    if(_stopping) {
        _shutdownPipeline();
501
        qCDebug(VideoReceiverLog) << "Stopped";
502 503 504
    } else if(_recording && _sink->removing) {
        _shutdownRecordingBranch();
    } else {
505
        qWarning() << "VideoReceiver: Unexpected EOS!";
506
        _handleError();
Gus Grubba's avatar
Gus Grubba committed
507 508
    }
}
509
#endif
Gus Grubba's avatar
Gus Grubba committed
510

511
//-----------------------------------------------------------------------------
512
#if defined(QGC_GST_STREAMING)
513 514 515 516
void
VideoReceiver::_handleStateChanged() {
    if(_pipeline) {
        _streaming = GST_STATE(_pipeline) == GST_STATE_PLAYING;
517
        //qCDebug(VideoReceiverLog) << "State changed, _streaming:" << _streaming;
518
    }
519 520 521
}
#endif

522
//-----------------------------------------------------------------------------
523
#if defined(QGC_GST_STREAMING)
524 525
gboolean
VideoReceiver::_onBusMessage(GstBus* bus, GstMessage* msg, gpointer data)
Gus Grubba's avatar
Gus Grubba committed
526 527
{
    Q_UNUSED(bus)
Gus Grubba's avatar
Gus Grubba committed
528
    Q_ASSERT(msg != nullptr && data != nullptr);
Gus Grubba's avatar
Gus Grubba committed
529
    VideoReceiver* pThis = (VideoReceiver*)data;
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551

    switch(GST_MESSAGE_TYPE(msg)) {
    case(GST_MESSAGE_ERROR): {
        gchar* debug;
        GError* error;
        gst_message_parse_error(msg, &error, &debug);
        g_free(debug);
        qCritical() << error->message;
        g_error_free(error);
        pThis->msgErrorReceived();
    }
        break;
    case(GST_MESSAGE_EOS):
        pThis->msgEOSReceived();
        break;
    case(GST_MESSAGE_STATE_CHANGED):
        pThis->msgStateChangedReceived();
        break;
    default:
        break;
    }

Gus Grubba's avatar
Gus Grubba committed
552 553
    return TRUE;
}
554
#endif
555

556
//-----------------------------------------------------------------------------
557
#if defined(QGC_GST_STREAMING)
558 559
void
VideoReceiver::_cleanupOldVideos()
560
{
561
    //-- Only perform cleanup if storage limit is enabled
562
    if(_videoSettings->enableStorageLimit()->rawValue().toBool()) {
563 564 565 566 567 568 569 570
        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);
        //-- All the movie extensions we support
        QStringList nameFilters;
        for(uint32_t i = 0; i < NUM_MUXES; i++) {
            nameFilters << QString("*.") + QString(kVideoExtensions[i]);
571
        }
572 573 574 575 576 577
        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
578
            uint64_t maxSize = (_videoSettings->maxVideoSize()->rawValue().toUInt() * 1024 * 1024);
579 580 581 582 583 584 585 586 587 588 589 590
            //-- 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();
                qCDebug(VideoReceiverLog) << "Removing old video file:" << vidList.last().filePath();
                QFile file (vidList.last().filePath());
                file.remove();
                vidList.removeLast();
            }
591 592 593
        }
    }
}
594
#endif
595

596 597 598 599
//-----------------------------------------------------------------------------
void
VideoReceiver::setVideoDecoder(VideoEncoding encoding)
{
600 601 602 603 604 605 606 607
    /*
    #if defined(Q_OS_MAC)
        _hwDecoderName = "vtdec";
    #else
        _hwDecoderName = "vaapidecode";
    #endif
    */

608 609 610
    if (encoding == H265_HW || encoding == H265_SW) {
        _depayName = "rtph265depay";
        _parserName = "h265parse";
611 612 613 614
#if defined(__android__)
        _hwDecoderName = "amcviddec-omxgooglehevcdecoder";
#endif
        _swDecoderName = "avdec_h265";
615 616 617
    } else {
        _depayName = "rtph264depay";
        _parserName = "h264parse";
618 619 620 621
#if defined(__android__)
        _hwDecoderName = "amcviddec-omxgoogleh264decoder";
#endif
        _swDecoderName = "avdec_h264";
622 623
    }

624 625 626 627
    if (!_tryWithHardwareDecoding) {
        _hwDecoderName = nullptr;
    }
}
628
//-----------------------------------------------------------------------------
629 630 631 632 633 634 635 636 637 638 639
// When we finish our pipeline will look like this:
//
//                                   +-->queue-->decoder-->_videosink
//                                   |
//    datasource-->demux-->parser-->tee
//                                   |
//                                   |    +--------------_sink-------------------+
//                                   |    |                                      |
//   we are adding these elements->  +->teepad-->queue-->matroskamux-->_filesink |
//                                        |                                      |
//                                        +--------------------------------------+
640
void
641
VideoReceiver::startRecording(const QString &videoFile)
642
{
643
#if defined(QGC_GST_STREAMING)
644

645 646
    qCDebug(VideoReceiverLog) << "startRecording()";
    // exit immediately if we are already recording
Gus Grubba's avatar
Gus Grubba committed
647
    if(_pipeline == nullptr || _recording) {
648 649 650 651
        qCDebug(VideoReceiverLog) << "Already recording!";
        return;
    }

652
    uint32_t muxIdx = _videoSettings->recordingFormat()->rawValue().toUInt();
653 654 655 656 657 658 659 660
    if(muxIdx >= NUM_MUXES) {
        qgcApp()->showMessage(tr("Invalid video format defined."));
        return;
    }

    //-- Disk usage maintenance
    _cleanupOldVideos();

661
    _sink           = new Sink();
662
    _sink->teepad   = gst_element_get_request_pad(_tee, "src_%u");
Gus Grubba's avatar
Gus Grubba committed
663
    _sink->queue    = gst_element_factory_make("queue", nullptr);
664
    _sink->parse    = gst_element_factory_make(_parserName, nullptr);
Gus Grubba's avatar
Gus Grubba committed
665 666
    _sink->mux      = gst_element_factory_make(kVideoMuxes[muxIdx], nullptr);
    _sink->filesink = gst_element_factory_make("filesink", nullptr);
667 668
    _sink->removing = false;

669
    if(!_sink->teepad || !_sink->queue || !_sink->mux || !_sink->filesink || !_sink->parse) {
670 671 672 673
        qCritical() << "VideoReceiver::startRecording() failed to make _sink elements";
        return;
    }

674 675 676 677 678 679 680 681 682 683 684
    if(videoFile.isEmpty()) {
        QString savePath = qgcApp()->toolbox()->settingsManager()->appSettings()->videoSavePath();
        if(savePath.isEmpty()) {
            qgcApp()->showMessage(tr("Unabled to record video. Video save path must be specified in Settings."));
            return;
        }
        _videoFile = savePath + "/" + QDateTime::currentDateTime().toString("yyyy-MM-dd_hh.mm.ss") + "." + kVideoExtensions[muxIdx];
    } else {
        _videoFile = videoFile;
    }
    emit videoFileChanged();
685

686
    g_object_set(static_cast<gpointer>(_sink->filesink), "location", qPrintable(_videoFile), nullptr);
687
    qCDebug(VideoReceiverLog) << "New video file:" << _videoFile;
688 689

    gst_object_ref(_sink->queue);
690
    gst_object_ref(_sink->parse);
691 692 693
    gst_object_ref(_sink->mux);
    gst_object_ref(_sink->filesink);

694 695
    gst_bin_add_many(GST_BIN(_pipeline), _sink->queue, _sink->parse, _sink->mux, nullptr);
    gst_element_link_many(_sink->queue, _sink->parse, _sink->mux, nullptr);
696 697

    gst_element_sync_state_with_parent(_sink->queue);
698
    gst_element_sync_state_with_parent(_sink->parse);
699 700
    gst_element_sync_state_with_parent(_sink->mux);

701 702 703
    // Install a probe on the recording branch to drop buffers until we hit our first keyframe
    // When we hit our first keyframe, we can offset the timestamps appropriately according to the first keyframe time
    // This will ensure the first frame is a keyframe at t=0, and decoding can begin immediately on playback
704 705
    // Once we have this valid frame, we attach the filesink.
    // Attaching it here would cause the filesink to fail to preroll and to stall the pipeline for a few seconds.
706
    GstPad* probepad = gst_element_get_static_pad(_sink->queue, "src");
Gus Grubba's avatar
Gus Grubba committed
707
    gst_pad_add_probe(probepad, (GstPadProbeType)(GST_PAD_PROBE_TYPE_BUFFER /* | GST_PAD_PROBE_TYPE_BLOCK */), _keyframeWatch, this, nullptr); // to drop the buffer or to block the buffer?
708 709 710
    gst_object_unref(probepad);

    // Link the recording branch to the pipeline
711 712 713 714
    GstPad* sinkpad = gst_element_get_static_pad(_sink->queue, "sink");
    gst_pad_link(_sink->teepad, sinkpad);
    gst_object_unref(sinkpad);

715 716
    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-recording");

717 718 719
    _recording = true;
    emit recordingChanged();
    qCDebug(VideoReceiverLog) << "Recording started";
DonLakeFlyer's avatar
DonLakeFlyer committed
720 721
#else
    Q_UNUSED(videoFile)
722 723 724
#endif
}

725 726 727
//-----------------------------------------------------------------------------
void
VideoReceiver::stopRecording(void)
728
{
729
#if defined(QGC_GST_STREAMING)
730 731
    qCDebug(VideoReceiverLog) << "stopRecording()";
    // exit immediately if we are not recording
Gus Grubba's avatar
Gus Grubba committed
732
    if(_pipeline == nullptr || !_recording) {
733 734 735 736
        qCDebug(VideoReceiverLog) << "Not recording!";
        return;
    }
    // Wait for data block before unlinking
Gus Grubba's avatar
Gus Grubba committed
737
    gst_pad_add_probe(_sink->teepad, GST_PAD_PROBE_TYPE_IDLE, _unlinkCallBack, this, nullptr);
738 739 740
#endif
}

741
//-----------------------------------------------------------------------------
742 743 744 745 746 747
// This is only installed on the transient _pipelineStopRec in order
// to finalize a video file. It is not used for the main _pipeline.
// -EOS has appeared on the bus of the temporary pipeline
// -At this point all of the recoring elements have been flushed, and the video file has been finalized
// -Now we can remove the temporary pipeline and its elements
#if defined(QGC_GST_STREAMING)
748 749
void
VideoReceiver::_shutdownRecordingBranch()
750 751
{
    gst_bin_remove(GST_BIN(_pipelineStopRec), _sink->queue);
752
    gst_bin_remove(GST_BIN(_pipelineStopRec), _sink->parse);
753 754 755 756 757
    gst_bin_remove(GST_BIN(_pipelineStopRec), _sink->mux);
    gst_bin_remove(GST_BIN(_pipelineStopRec), _sink->filesink);

    gst_element_set_state(_pipelineStopRec, GST_STATE_NULL);
    gst_object_unref(_pipelineStopRec);
Gus Grubba's avatar
Gus Grubba committed
758
    _pipelineStopRec = nullptr;
759

760 761 762 763
    gst_element_set_state(_sink->filesink,  GST_STATE_NULL);
    gst_element_set_state(_sink->parse,     GST_STATE_NULL);
    gst_element_set_state(_sink->mux,       GST_STATE_NULL);
    gst_element_set_state(_sink->queue,     GST_STATE_NULL);
764 765

    gst_object_unref(_sink->queue);
766
    gst_object_unref(_sink->parse);
767 768 769 770
    gst_object_unref(_sink->mux);
    gst_object_unref(_sink->filesink);

    delete _sink;
Gus Grubba's avatar
Gus Grubba committed
771
    _sink = nullptr;
772
    _recording = false;
773

774 775 776 777 778
    emit recordingChanged();
    qCDebug(VideoReceiverLog) << "Recording Stopped";
}
#endif

779
//-----------------------------------------------------------------------------
780 781 782 783 784
// -Unlink the recording branch from the tee in the main _pipeline
// -Create a second temporary pipeline, and place the recording branch elements into that pipeline
// -Setup watch and handler for EOS event on the temporary pipeline's bus
// -Send an EOS event at the beginning of that pipeline
#if defined(QGC_GST_STREAMING)
785 786
void
VideoReceiver::_detachRecordingBranch(GstPadProbeInfo* info)
787 788 789 790
{
    Q_UNUSED(info)

    // Also unlinks and unrefs
Gus Grubba's avatar
Gus Grubba committed
791
    gst_bin_remove_many(GST_BIN(_pipeline), _sink->queue, _sink->parse, _sink->mux, _sink->filesink, nullptr);
792 793 794 795 796 797 798 799 800

    // Give tee its pad back
    gst_element_release_request_pad(_tee, _sink->teepad);
    gst_object_unref(_sink->teepad);

    // Create temporary pipeline
    _pipelineStopRec = gst_pipeline_new("pipeStopRec");

    // Put our elements from the recording branch into the temporary pipeline
Gus Grubba's avatar
Gus Grubba committed
801 802
    gst_bin_add_many(GST_BIN(_pipelineStopRec), _sink->queue, _sink->parse, _sink->mux, _sink->filesink, nullptr);
    gst_element_link_many(_sink->queue, _sink->parse, _sink->mux, _sink->filesink, nullptr);
803

804 805 806
    // Add handler for EOS event
    GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(_pipelineStopRec));
    gst_bus_enable_sync_message_emission(bus);
807
    g_signal_connect(bus, "sync-message", G_CALLBACK(_onBusMessage), this);
808
    gst_object_unref(bus);
809 810 811 812 813 814 815 816 817 818 819 820 821

    if(gst_element_set_state(_pipelineStopRec, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
        qCDebug(VideoReceiverLog) << "problem starting _pipelineStopRec";
    }

    // Send EOS at the beginning of the pipeline
    GstPad* sinkpad = gst_element_get_static_pad(_sink->queue, "sink");
    gst_pad_send_event(sinkpad, gst_event_new_eos());
    gst_object_unref(sinkpad);
    qCDebug(VideoReceiverLog) << "Recording branch unlinked";
}
#endif

822
//-----------------------------------------------------------------------------
823
#if defined(QGC_GST_STREAMING)
824 825
GstPadProbeReturn
VideoReceiver::_unlinkCallBack(GstPad* pad, GstPadProbeInfo* info, gpointer user_data)
826 827
{
    Q_UNUSED(pad);
Gus Grubba's avatar
Gus Grubba committed
828 829
    if(info != nullptr && user_data != nullptr) {
        VideoReceiver* pThis = static_cast<VideoReceiver*>(user_data);
830 831 832 833 834
        // We will only act once
        if(g_atomic_int_compare_and_exchange(&pThis->_sink->removing, FALSE, TRUE)) {
            pThis->_detachRecordingBranch(info);
        }
    }
835 836 837
    return GST_PAD_PROBE_REMOVE;
}
#endif
838

839 840 841 842 843 844
//-----------------------------------------------------------------------------
#if defined(QGC_GST_STREAMING)
GstPadProbeReturn
VideoReceiver::_keyframeWatch(GstPad* pad, GstPadProbeInfo* info, gpointer user_data)
{
    Q_UNUSED(pad);
Gus Grubba's avatar
Gus Grubba committed
845
    if(info != nullptr && user_data != nullptr) {
846 847 848 849
        GstBuffer* buf = gst_pad_probe_info_get_buffer(info);
        if(GST_BUFFER_FLAG_IS_SET(buf, GST_BUFFER_FLAG_DELTA_UNIT)) { // wait for a keyframe
            return GST_PAD_PROBE_DROP;
        } else {
Gus Grubba's avatar
Gus Grubba committed
850
            VideoReceiver* pThis = static_cast<VideoReceiver*>(user_data);
851
            // reset the clock
Jacob Walser's avatar
Jacob Walser committed
852
            GstClock* clock = gst_pipeline_get_clock(GST_PIPELINE(pThis->_pipeline));
853 854 855 856 857
            GstClockTime time = gst_clock_get_time(clock);
            gst_object_unref(clock);
            gst_element_set_base_time(pThis->_pipeline, time); // offset pipeline timestamps to start at zero again
            buf->dts = 0; // The offset will not apply to this current buffer, our first frame, timestamp is zero
            buf->pts = 0;
858 859 860 861 862 863

            // Add the filesink once we have a valid I-frame
            gst_bin_add_many(GST_BIN(pThis->_pipeline), pThis->_sink->filesink, nullptr);
            gst_element_link_many(pThis->_sink->mux, pThis->_sink->filesink, nullptr);
            gst_element_sync_state_with_parent(pThis->_sink->filesink);

864
            qCDebug(VideoReceiverLog) << "Got keyframe, stop dropping buffers";
865
            pThis->gotFirstRecordingKeyFrame();
866 867 868 869 870 871 872
        }
    }

    return GST_PAD_PROBE_REMOVE;
}
#endif

873 874 875 876 877 878
//-----------------------------------------------------------------------------
void
VideoReceiver::_updateTimer()
{
#if defined(QGC_GST_STREAMING)
    if(_videoSurface) {
879
        if(_stopping || _starting) {
880 881
            return;
        }
882
        if(_streaming) {
883 884 885 886 887 888 889 890 891 892 893 894
            if(!_videoRunning) {
                _videoSurface->setLastFrame(0);
                _videoRunning = true;
                emit videoRunningChanged();
            }
        } else {
            if(_videoRunning) {
                _videoRunning = false;
                emit videoRunningChanged();
            }
        }
        if(_videoRunning) {
895 896
            uint32_t timeout = 1;
            if(qgcApp()->toolbox() && qgcApp()->toolbox()->settingsManager()) {
897
                timeout = _videoSettings->rtspTimeout()->rawValue().toUInt();
898
            }
899 900 901
            time_t elapsed = 0;
            time_t lastFrame = _videoSurface->lastFrame();
            if(lastFrame != 0) {
Gus Grubba's avatar
Gus Grubba committed
902
                elapsed = time(nullptr) - _videoSurface->lastFrame();
903
            }
Gus Grubba's avatar
Gus Grubba committed
904
            if(elapsed > static_cast<time_t>(timeout) && _videoSurface) {
905
                stop();
906 907
                // We want to start it back again with _updateTimer
                _stop = false;
908 909
            }
        } else {
910
            if(!_stop && _running && !_uri.isEmpty() && _videoSettings->streamEnabled()->rawValue().toBool()) {
911 912 913 914 915 916 917
                start();
            }
        }
    }
#endif
}