VideoReceiver.cc 32.1 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * 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)
Gus Grubba's avatar
Gus Grubba committed
61 62 63 64 65 66
    , _sink(nullptr)
    , _tee(nullptr)
    , _pipeline(nullptr)
    , _pipelineStopRec(nullptr)
    , _videoSink(nullptr)
    , _socket(nullptr)
67
    , _serverPresent(false)
68
    , _rtspTestInterval_ms(5000)
69
    , _udpReconnect_us(5000000)
70
#endif
Gus Grubba's avatar
Gus Grubba committed
71
    , _videoSurface(nullptr)
72 73
    , _videoRunning(false)
    , _showFullScreen(false)
Gus Grubba's avatar
Gus Grubba committed
74
    , _videoSettings(nullptr)
Gus Grubba's avatar
Gus Grubba committed
75
{
76 77
    _videoSurface = new VideoSurface;
    _videoSettings = qgcApp()->toolbox()->settingsManager()->videoSettings();
78
#if defined(QGC_GST_STREAMING)
79
    _setVideoSink(_videoSurface->videoSink());
80 81
    _timer.setSingleShot(true);
    connect(&_timer, &QTimer::timeout, this, &VideoReceiver::_timeout);
82 83 84
    connect(this, &VideoReceiver::msgErrorReceived, this, &VideoReceiver::_handleError);
    connect(this, &VideoReceiver::msgEOSReceived, this, &VideoReceiver::_handleEOS);
    connect(this, &VideoReceiver::msgStateChangedReceived, this, &VideoReceiver::_handleStateChanged);
85 86
    connect(&_frameTimer, &QTimer::timeout, this, &VideoReceiver::_updateTimer);
    _frameTimer.start(1000);
87
#endif
Gus Grubba's avatar
Gus Grubba committed
88 89 90 91
}

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

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

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

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

147
//-----------------------------------------------------------------------------
148
#if defined(QGC_GST_STREAMING)
149 150
void
VideoReceiver::_connected()
151 152 153
{
    //-- Server showed up. Now we start the stream.
    _timer.stop();
154
    _socket->deleteLater();
Gus Grubba's avatar
Gus Grubba committed
155
    _socket = nullptr;
156
    if(_videoSettings->streamEnabled()->rawValue().toBool()) {
Gus Grubba's avatar
Gus Grubba committed
157 158 159
        _serverPresent = true;
        start();
    }
160 161 162
}
#endif

163
//-----------------------------------------------------------------------------
164
#if defined(QGC_GST_STREAMING)
165 166
void
VideoReceiver::_socketError(QAbstractSocket::SocketError socketError)
167 168
{
    Q_UNUSED(socketError);
169
    _socket->deleteLater();
Gus Grubba's avatar
Gus Grubba committed
170
    _socket = nullptr;
171
    //-- Try again in a while
172
    if(_videoSettings->streamEnabled()->rawValue().toBool()) {
173
        _timer.start(_rtspTestInterval_ms);
Gus Grubba's avatar
Gus Grubba committed
174
    }
175 176 177
}
#endif

178
//-----------------------------------------------------------------------------
179
#if defined(QGC_GST_STREAMING)
180 181
void
VideoReceiver::_timeout()
182 183 184 185
{
    //-- If socket is live, we got no connection nor a socket error
    if(_socket) {
        delete _socket;
Gus Grubba's avatar
Gus Grubba committed
186
        _socket = nullptr;
187
    }
188
    if(_videoSettings->streamEnabled()->rawValue().toBool()) {
Gus Grubba's avatar
Gus Grubba committed
189 190 191 192 193
        //-- RTSP will try to connect to the server. If it cannot connect,
        //   it will simply give up and never try again. Instead, we keep
        //   attempting a connection on this timer. Once a connection is
        //   found to be working, only then we actually start the stream.
        QUrl url(_uri);
194 195 196 197
        //-- If RTSP and no port is defined, set default RTSP port (554)
        if(_uri.contains("rtsp://") && url.port() <= 0) {
            url.setPort(554);
        }
Gus Grubba's avatar
Gus Grubba committed
198
        _socket = new QTcpSocket;
199 200 201
        QNetworkProxy tempProxy;
        tempProxy.setType(QNetworkProxy::DefaultProxy);
        _socket->setProxy(tempProxy);
Gus Grubba's avatar
Gus Grubba committed
202 203
        connect(_socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &VideoReceiver::_socketError);
        connect(_socket, &QTcpSocket::connected, this, &VideoReceiver::_connected);
Gus Grubba's avatar
Gus Grubba committed
204
        _socket->connectToHost(url.host(), static_cast<uint16_t>(url.port()));
205
        _timer.start(_rtspTestInterval_ms);
Gus Grubba's avatar
Gus Grubba committed
206
    }
207 208 209
}
#endif

210
//-----------------------------------------------------------------------------
211 212 213 214 215 216 217 218 219
// When we finish our pipeline will look like this:
//
//                                   +-->queue-->decoder-->_videosink
//                                   |
//    datasource-->demux-->parser-->tee
//
//                                   ^
//                                   |
//                                   +-Here we will later link elements for recording
220 221
void
VideoReceiver::start()
Gus Grubba's avatar
Gus Grubba committed
222
{
Gus Grubba's avatar
Gus Grubba committed
223 224
    qCDebug(VideoReceiverLog) << "start():" << _uri;
    if(qgcApp()->runningUnitTests()) {
225 226
        return;
    }
227 228
    if(!_videoSettings->streamEnabled()->rawValue().toBool() ||
       !_videoSettings->streamConfigured()) {
229 230 231
        qCDebug(VideoReceiverLog) << "start() but not enabled/configured";
        return;
    }
232
#if defined(QGC_GST_STREAMING)
233
    _stop = false;
234 235
    qCDebug(VideoReceiverLog) << "start()";

236 237
#if  defined(QGC_GST_TAISYNC_ENABLED) && (defined(__android__) || defined(__ios__))
    //-- Taisync on iOS or Android sends a raw h.264 stream
238 239 240 241 242 243 244 245 246
    bool isTaisyncUSB = qgcApp()->toolbox()->videoManager()->isTaisync();
#else
    bool isTaisyncUSB = false;
#endif
    bool isUdp  = _uri.contains("udp://")  && !isTaisyncUSB;
    bool isRtsp = _uri.contains("rtsp://") && !isTaisyncUSB;
    bool isTCP  = _uri.contains("tcp://")  && !isTaisyncUSB;

    if (!isTaisyncUSB && _uri.isEmpty()) {
Gus Grubba's avatar
Gus Grubba committed
247 248 249
        qCritical() << "VideoReceiver::start() failed because URI is not specified";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
250
    if (_videoSink == nullptr) {
Gus Grubba's avatar
Gus Grubba committed
251 252 253
        qCritical() << "VideoReceiver::start() failed because video sink is not set";
        return;
    }
254 255 256 257
    if(_running) {
        qCDebug(VideoReceiverLog) << "Already running!";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
258

259
    _starting = true;
260

261 262
    //-- For RTSP and TCP, check to see if server is there first
    if(!_serverPresent && (isRtsp || isTCP)) {
263 264 265 266
        _timer.start(100);
        return;
    }

267
    bool running    = false;
268
    bool pipelineUp = false;
Gus Grubba's avatar
Gus Grubba committed
269

Gus Grubba's avatar
Gus Grubba committed
270 271 272 273 274 275 276
    GstElement*     dataSource  = nullptr;
    GstCaps*        caps        = nullptr;
    GstElement*     demux       = nullptr;
    GstElement*     parser      = nullptr;
    GstElement*     queue       = nullptr;
    GstElement*     decoder     = nullptr;
    GstElement*     queue1      = nullptr;
277

Gus Grubba's avatar
Gus Grubba committed
278
    do {
Gus Grubba's avatar
Gus Grubba committed
279
        if ((_pipeline = gst_pipeline_new("receiver")) == nullptr) {
280
            qCritical() << "VideoReceiver::start() failed. Error with gst_pipeline_new()";
Gus Grubba's avatar
Gus Grubba committed
281 282 283
            break;
        }

284
        if(isUdp || isTaisyncUSB) {
285
            dataSource = gst_element_factory_make("udpsrc", "udp-source");
286 287
        } else if(isTCP) {
            dataSource = gst_element_factory_make("tcpclientsrc", "tcpclient-source");
288 289
        } else {
            dataSource = gst_element_factory_make("rtspsrc", "rtsp-source");
Gus Grubba's avatar
Gus Grubba committed
290 291
        }

292 293
        if (!dataSource) {
            qCritical() << "VideoReceiver::start() failed. Error with data source for gst_element_factory_make()";
Gus Grubba's avatar
Gus Grubba committed
294 295 296
            break;
        }

297
        if(isUdp) {
Gus Grubba's avatar
Gus Grubba committed
298
            if ((caps = gst_caps_from_string("application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264")) == nullptr) {
299 300 301
                qCritical() << "VideoReceiver::start() failed. Error with gst_caps_from_string()";
                break;
            }
302
            g_object_set(static_cast<gpointer>(dataSource), "uri", qPrintable(_uri), "caps", caps, nullptr);
303
#if  defined(QGC_GST_TAISYNC_ENABLED) && (defined(__android__) || defined(__ios__))
304 305 306 307 308
        } 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
309 310
        } else if(isTCP) {
            QUrl url(_uri);
311
            g_object_set(static_cast<gpointer>(dataSource), "host", qPrintable(url.host()), "port", url.port(), nullptr );
312
        } else {
313
            g_object_set(static_cast<gpointer>(dataSource), "location", qPrintable(_uri), "latency", 17, "udp-reconnect", 1, "timeout", _udpReconnect_us, NULL);
314
        }
Gus Grubba's avatar
Gus Grubba committed
315

316 317
        // Currently, we expect H264 when using anything except for TCP.  Long term we may want this to be settable
        if (isTCP) {
Gus Grubba's avatar
Gus Grubba committed
318
            if ((demux = gst_element_factory_make("tsdemux", "mpeg2-ts-demuxer")) == nullptr) {
319 320 321 322
                qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('tsdemux')";
                break;
            }
        } else {
323 324
            if(!isTaisyncUSB) {
                if ((demux = gst_element_factory_make("rtph264depay", "rtp-h264-depacketizer")) == nullptr) {
325 326 327
                qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('rtph264depay')";
                break;
            }
328
        }
329
        }
330

Gus Grubba's avatar
Gus Grubba committed
331
        if ((parser = gst_element_factory_make("h264parse", "h264-parser")) == nullptr) {
332
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('h264parse')";
Gus Grubba's avatar
Gus Grubba committed
333 334 335
            break;
        }

Gus Grubba's avatar
Gus Grubba committed
336
        if((_tee = gst_element_factory_make("tee", nullptr)) == nullptr)  {
337 338 339
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('tee')";
            break;
        }
Gus Grubba's avatar
Gus Grubba committed
340

Gus Grubba's avatar
Gus Grubba committed
341
        if((queue = gst_element_factory_make("queue", nullptr)) == nullptr)  {
342 343
            // 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
344
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('queue')";
345 346
            break;
        }
347

Gus Grubba's avatar
Gus Grubba committed
348
        if ((decoder = gst_element_factory_make("avdec_h264", "h264-decoder")) == nullptr) {
349 350 351 352
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('avdec_h264')";
            break;
        }

Gus Grubba's avatar
Gus Grubba committed
353
        if ((queue1 = gst_element_factory_make("queue", nullptr)) == nullptr) {
354 355 356 357
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('queue') [1]";
            break;
        }

358 359 360 361 362
        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);
        }
363
        pipelineUp = true;
364

365 366
        if(isUdp) {
            // Link the pipeline in front of the tee
Gus Grubba's avatar
Gus Grubba committed
367
            if(!gst_element_link_many(dataSource, demux, parser, _tee, queue, decoder, queue1, _videoSink, nullptr)) {
368 369 370
                qCritical() << "Unable to link UDP elements.";
                break;
            }
371 372 373 374 375 376
        } 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;
            }
377 378 379 380 381
        } else if (isTCP) {
            if(!gst_element_link(dataSource, demux)) {
                qCritical() << "Unable to link TCP dataSource to Demux.";
                break;
            }
Gus Grubba's avatar
Gus Grubba committed
382
            if(!gst_element_link_many(parser, _tee, queue, decoder, queue1, _videoSink, nullptr)) {
383
                qCritical() << "Unable to link TCP pipline to parser.";
384 385
                break;
            }
386
            g_signal_connect(demux, "pad-added", G_CALLBACK(newPadCB), parser);
387
        } else {
388
            g_signal_connect(dataSource, "pad-added", G_CALLBACK(newPadCB), demux);
Gus Grubba's avatar
Gus Grubba committed
389
            if(!gst_element_link_many(demux, parser, _tee, queue, decoder, _videoSink, nullptr)) {
390
                qCritical() << "Unable to link RTSP elements.";
391 392
                break;
            }
393 394
        }

Gus Grubba's avatar
Gus Grubba committed
395
        dataSource = demux = parser = queue = decoder = queue1 = nullptr;
Gus Grubba's avatar
Gus Grubba committed
396

Gus Grubba's avatar
Gus Grubba committed
397
        GstBus* bus = nullptr;
Gus Grubba's avatar
Gus Grubba committed
398

Gus Grubba's avatar
Gus Grubba committed
399
        if ((bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline))) != nullptr) {
400 401 402
            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
403
            bus = nullptr;
404
        }
Gus Grubba's avatar
Gus Grubba committed
405

406
        GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-paused");
Gus Grubba's avatar
Gus Grubba committed
407 408 409 410
        running = gst_element_set_state(_pipeline, GST_STATE_PLAYING) != GST_STATE_CHANGE_FAILURE;

    } while(0);

Gus Grubba's avatar
Gus Grubba committed
411
    if (caps != nullptr) {
Gus Grubba's avatar
Gus Grubba committed
412
        gst_caps_unref(caps);
Gus Grubba's avatar
Gus Grubba committed
413
        caps = nullptr;
Gus Grubba's avatar
Gus Grubba committed
414 415 416 417 418
    }

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

419
        // In newer versions, the pipeline will clean up all references that are added to it
Gus Grubba's avatar
Gus Grubba committed
420
        if (_pipeline != nullptr) {
421
            gst_object_unref(_pipeline);
Gus Grubba's avatar
Gus Grubba committed
422
            _pipeline = nullptr;
Gus Grubba's avatar
Gus Grubba committed
423 424
        }

425 426
        // If we failed before adding items to the pipeline, then clean up
        if (!pipelineUp) {
Gus Grubba's avatar
Gus Grubba committed
427
            if (decoder != nullptr) {
428
                gst_object_unref(decoder);
Gus Grubba's avatar
Gus Grubba committed
429
                decoder = nullptr;
430
            }
Gus Grubba's avatar
Gus Grubba committed
431

Gus Grubba's avatar
Gus Grubba committed
432
            if (parser != nullptr) {
433
                gst_object_unref(parser);
Gus Grubba's avatar
Gus Grubba committed
434
                parser = nullptr;
435
            }
Gus Grubba's avatar
Gus Grubba committed
436

Gus Grubba's avatar
Gus Grubba committed
437
            if (demux != nullptr) {
438
                gst_object_unref(demux);
Gus Grubba's avatar
Gus Grubba committed
439
                demux = nullptr;
440
            }
Gus Grubba's avatar
Gus Grubba committed
441

Gus Grubba's avatar
Gus Grubba committed
442
            if (dataSource != nullptr) {
443
                gst_object_unref(dataSource);
Gus Grubba's avatar
Gus Grubba committed
444
                dataSource = nullptr;
445
            }
446

Gus Grubba's avatar
Gus Grubba committed
447
            if (_tee != nullptr) {
448
                gst_object_unref(_tee);
Gus Grubba's avatar
Gus Grubba committed
449
                dataSource = nullptr;
450
            }
451

Gus Grubba's avatar
Gus Grubba committed
452
            if (queue != nullptr) {
453
                gst_object_unref(queue);
Gus Grubba's avatar
Gus Grubba committed
454
                dataSource = nullptr;
455
            }
Gus Grubba's avatar
Gus Grubba committed
456
        }
457 458 459

        _running = false;
    } else {
460
        GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-playing");
461 462
        _running = true;
        qCDebug(VideoReceiverLog) << "Running";
Gus Grubba's avatar
Gus Grubba committed
463
    }
464
    _starting = false;
465
#endif
Gus Grubba's avatar
Gus Grubba committed
466 467
}

468 469 470
//-----------------------------------------------------------------------------
void
VideoReceiver::stop()
Gus Grubba's avatar
Gus Grubba committed
471
{
472 473 474
    if(!qgcApp()->runningUnitTests()) {
        return;
    }
475
#if defined(QGC_GST_STREAMING)
476
    _stop = true;
477
    qCDebug(VideoReceiverLog) << "stop()";
478 479
    if(!_streaming) {
        _shutdownPipeline();
Gus Grubba's avatar
Gus Grubba committed
480
    } else if (_pipeline != nullptr && !_stopping) {
481 482 483 484
        qCDebug(VideoReceiverLog) << "Stopping _pipeline";
        gst_element_send_event(_pipeline, gst_event_new_eos());
        _stopping = true;
        GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline));
485
        GstMessage* message = gst_bus_timed_pop_filtered(bus, GST_CLOCK_TIME_NONE, (GstMessageType)(GST_MESSAGE_EOS|GST_MESSAGE_ERROR));
486
        gst_object_unref(bus);
487 488 489 490 491 492
        if(GST_MESSAGE_TYPE(message) == GST_MESSAGE_ERROR) {
            _shutdownPipeline();
            qCritical() << "Error stopping pipeline!";
        } else if(GST_MESSAGE_TYPE(message) == GST_MESSAGE_EOS) {
            _handleEOS();
        }
493
        gst_message_unref(message);
Gus Grubba's avatar
Gus Grubba committed
494
    }
495
#endif
Gus Grubba's avatar
Gus Grubba committed
496 497
}

498 499 500
//-----------------------------------------------------------------------------
void
VideoReceiver::setUri(const QString & uri)
Gus Grubba's avatar
Gus Grubba committed
501 502 503 504
{
    _uri = uri;
}

505
//-----------------------------------------------------------------------------
506
#if defined(QGC_GST_STREAMING)
507 508
void
VideoReceiver::_shutdownPipeline() {
509 510 511 512
    if(!_pipeline) {
        qCDebug(VideoReceiverLog) << "No pipeline";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
513 514
    GstBus* bus = nullptr;
    if ((bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline))) != nullptr) {
515 516
        gst_bus_disable_sync_message_emission(bus);
        gst_object_unref(bus);
Gus Grubba's avatar
Gus Grubba committed
517
        bus = nullptr;
518 519 520 521
    }
    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
522
    _pipeline = nullptr;
523
    delete _sink;
Gus Grubba's avatar
Gus Grubba committed
524
    _sink = nullptr;
525 526 527 528 529 530 531
    _serverPresent = false;
    _streaming = false;
    _recording = false;
    _stopping = false;
    _running = false;
    emit recordingChanged();
}
532
#endif
533

534
//-----------------------------------------------------------------------------
535
#if defined(QGC_GST_STREAMING)
536 537
void
VideoReceiver::_handleError() {
538
    qCDebug(VideoReceiverLog) << "Gstreamer error!";
539 540
    stop();
    start();
541 542 543
}
#endif

544
//-----------------------------------------------------------------------------
545
#if defined(QGC_GST_STREAMING)
546 547
void
VideoReceiver::_handleEOS() {
548 549
    if(_stopping) {
        _shutdownPipeline();
550
        qCDebug(VideoReceiverLog) << "Stopped";
551 552 553
    } else if(_recording && _sink->removing) {
        _shutdownRecordingBranch();
    } else {
554
        qWarning() << "VideoReceiver: Unexpected EOS!";
555 556
        stop();
        start();
Gus Grubba's avatar
Gus Grubba committed
557 558
    }
}
559
#endif
Gus Grubba's avatar
Gus Grubba committed
560

561
//-----------------------------------------------------------------------------
562
#if defined(QGC_GST_STREAMING)
563 564 565 566 567 568
void
VideoReceiver::_handleStateChanged() {
    if(_pipeline) {
        _streaming = GST_STATE(_pipeline) == GST_STATE_PLAYING;
        qCDebug(VideoReceiverLog) << "State changed, _streaming:" << _streaming;
    }
569 570 571
}
#endif

572
//-----------------------------------------------------------------------------
573
#if defined(QGC_GST_STREAMING)
574 575
gboolean
VideoReceiver::_onBusMessage(GstBus* bus, GstMessage* msg, gpointer data)
Gus Grubba's avatar
Gus Grubba committed
576 577
{
    Q_UNUSED(bus)
Gus Grubba's avatar
Gus Grubba committed
578
    Q_ASSERT(msg != nullptr && data != nullptr);
Gus Grubba's avatar
Gus Grubba committed
579
    VideoReceiver* pThis = (VideoReceiver*)data;
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

    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
602 603
    return TRUE;
}
604
#endif
605

606
//-----------------------------------------------------------------------------
607
#if defined(QGC_GST_STREAMING)
608 609
void
VideoReceiver::_cleanupOldVideos()
610
{
611
    //-- Only perform cleanup if storage limit is enabled
612
    if(_videoSettings->enableStorageLimit()->rawValue().toBool()) {
613 614 615 616 617 618 619 620
        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]);
621
        }
622 623 624 625 626 627
        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
628
            uint64_t maxSize = (_videoSettings->maxVideoSize()->rawValue().toUInt() * 1024 * 1024);
629 630 631 632 633 634 635 636 637 638 639 640
            //-- 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();
            }
641 642 643
        }
    }
}
644
#endif
645

646
//-----------------------------------------------------------------------------
647 648 649 650 651 652 653 654 655 656 657
// 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 |
//                                        |                                      |
//                                        +--------------------------------------+
658
void
659
VideoReceiver::startRecording(const QString &videoFile)
660
{
661
#if defined(QGC_GST_STREAMING)
662

663 664
    qCDebug(VideoReceiverLog) << "startRecording()";
    // exit immediately if we are already recording
Gus Grubba's avatar
Gus Grubba committed
665
    if(_pipeline == nullptr || _recording) {
666 667 668 669
        qCDebug(VideoReceiverLog) << "Already recording!";
        return;
    }

670
    uint32_t muxIdx = _videoSettings->recordingFormat()->rawValue().toUInt();
671 672 673 674 675 676 677 678
    if(muxIdx >= NUM_MUXES) {
        qgcApp()->showMessage(tr("Invalid video format defined."));
        return;
    }

    //-- Disk usage maintenance
    _cleanupOldVideos();

679
    _sink           = new Sink();
680
    _sink->teepad   = gst_element_get_request_pad(_tee, "src_%u");
Gus Grubba's avatar
Gus Grubba committed
681 682 683 684
    _sink->queue    = gst_element_factory_make("queue", nullptr);
    _sink->parse    = gst_element_factory_make("h264parse", nullptr);
    _sink->mux      = gst_element_factory_make(kVideoMuxes[muxIdx], nullptr);
    _sink->filesink = gst_element_factory_make("filesink", nullptr);
685 686
    _sink->removing = false;

687
    if(!_sink->teepad || !_sink->queue || !_sink->mux || !_sink->filesink || !_sink->parse) {
688 689 690 691
        qCritical() << "VideoReceiver::startRecording() failed to make _sink elements";
        return;
    }

692 693 694 695 696 697 698 699 700 701 702
    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();
703

704
    g_object_set(static_cast<gpointer>(_sink->filesink), "location", qPrintable(_videoFile), nullptr);
705
    qCDebug(VideoReceiverLog) << "New video file:" << _videoFile;
706 707

    gst_object_ref(_sink->queue);
708
    gst_object_ref(_sink->parse);
709 710 711
    gst_object_ref(_sink->mux);
    gst_object_ref(_sink->filesink);

Gus Grubba's avatar
Gus Grubba committed
712 713
    gst_bin_add_many(GST_BIN(_pipeline), _sink->queue, _sink->parse, _sink->mux, _sink->filesink, nullptr);
    gst_element_link_many(_sink->queue, _sink->parse, _sink->mux, _sink->filesink, nullptr);
714 715

    gst_element_sync_state_with_parent(_sink->queue);
716
    gst_element_sync_state_with_parent(_sink->parse);
717 718 719
    gst_element_sync_state_with_parent(_sink->mux);
    gst_element_sync_state_with_parent(_sink->filesink);

720 721 722 723
    // 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
    GstPad* probepad = gst_element_get_static_pad(_sink->queue, "src");
Gus Grubba's avatar
Gus Grubba committed
724
    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?
725 726 727
    gst_object_unref(probepad);

    // Link the recording branch to the pipeline
728 729 730 731
    GstPad* sinkpad = gst_element_get_static_pad(_sink->queue, "sink");
    gst_pad_link(_sink->teepad, sinkpad);
    gst_object_unref(sinkpad);

732 733
    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-recording");

734 735 736
    _recording = true;
    emit recordingChanged();
    qCDebug(VideoReceiverLog) << "Recording started";
DonLakeFlyer's avatar
DonLakeFlyer committed
737 738
#else
    Q_UNUSED(videoFile)
739 740 741
#endif
}

742 743 744
//-----------------------------------------------------------------------------
void
VideoReceiver::stopRecording(void)
745
{
746
#if defined(QGC_GST_STREAMING)
747 748
    qCDebug(VideoReceiverLog) << "stopRecording()";
    // exit immediately if we are not recording
Gus Grubba's avatar
Gus Grubba committed
749
    if(_pipeline == nullptr || !_recording) {
750 751 752 753
        qCDebug(VideoReceiverLog) << "Not recording!";
        return;
    }
    // Wait for data block before unlinking
Gus Grubba's avatar
Gus Grubba committed
754
    gst_pad_add_probe(_sink->teepad, GST_PAD_PROBE_TYPE_IDLE, _unlinkCallBack, this, nullptr);
755 756 757
#endif
}

758
//-----------------------------------------------------------------------------
759 760 761 762 763 764
// 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)
765 766
void
VideoReceiver::_shutdownRecordingBranch()
767 768
{
    gst_bin_remove(GST_BIN(_pipelineStopRec), _sink->queue);
769
    gst_bin_remove(GST_BIN(_pipelineStopRec), _sink->parse);
770 771 772 773 774
    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
775
    _pipelineStopRec = nullptr;
776

777 778 779 780
    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);
781 782

    gst_object_unref(_sink->queue);
783
    gst_object_unref(_sink->parse);
784 785 786 787
    gst_object_unref(_sink->mux);
    gst_object_unref(_sink->filesink);

    delete _sink;
Gus Grubba's avatar
Gus Grubba committed
788
    _sink = nullptr;
789
    _recording = false;
790

791 792 793 794 795
    emit recordingChanged();
    qCDebug(VideoReceiverLog) << "Recording Stopped";
}
#endif

796
//-----------------------------------------------------------------------------
797 798 799 800 801
// -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)
802 803
void
VideoReceiver::_detachRecordingBranch(GstPadProbeInfo* info)
804 805 806 807
{
    Q_UNUSED(info)

    // Also unlinks and unrefs
Gus Grubba's avatar
Gus Grubba committed
808
    gst_bin_remove_many(GST_BIN(_pipeline), _sink->queue, _sink->parse, _sink->mux, _sink->filesink, nullptr);
809 810 811 812 813 814 815 816 817

    // 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
818 819
    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);
820

821 822 823
    // Add handler for EOS event
    GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(_pipelineStopRec));
    gst_bus_enable_sync_message_emission(bus);
824
    g_signal_connect(bus, "sync-message", G_CALLBACK(_onBusMessage), this);
825
    gst_object_unref(bus);
826 827 828 829 830 831 832 833 834 835 836 837 838

    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

839
//-----------------------------------------------------------------------------
840
#if defined(QGC_GST_STREAMING)
841 842
GstPadProbeReturn
VideoReceiver::_unlinkCallBack(GstPad* pad, GstPadProbeInfo* info, gpointer user_data)
843 844
{
    Q_UNUSED(pad);
Gus Grubba's avatar
Gus Grubba committed
845 846
    if(info != nullptr && user_data != nullptr) {
        VideoReceiver* pThis = static_cast<VideoReceiver*>(user_data);
847 848 849 850 851
        // We will only act once
        if(g_atomic_int_compare_and_exchange(&pThis->_sink->removing, FALSE, TRUE)) {
            pThis->_detachRecordingBranch(info);
        }
    }
852 853 854
    return GST_PAD_PROBE_REMOVE;
}
#endif
855

856 857 858 859 860 861
//-----------------------------------------------------------------------------
#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
862
    if(info != nullptr && user_data != nullptr) {
863 864 865 866
        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
867
            VideoReceiver* pThis = static_cast<VideoReceiver*>(user_data);
868
            // reset the clock
Jacob Walser's avatar
Jacob Walser committed
869
            GstClock* clock = gst_pipeline_get_clock(GST_PIPELINE(pThis->_pipeline));
870 871 872 873 874 875 876 877 878 879 880 881 882
            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;
            qCDebug(VideoReceiverLog) << "Got keyframe, stop dropping buffers";
        }
    }

    return GST_PAD_PROBE_REMOVE;
}
#endif

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
//-----------------------------------------------------------------------------
void
VideoReceiver::_updateTimer()
{
#if defined(QGC_GST_STREAMING)
    if(_videoSurface) {
        if(stopping() || starting()) {
            return;
        }
        if(streaming()) {
            if(!_videoRunning) {
                _videoSurface->setLastFrame(0);
                _videoRunning = true;
                emit videoRunningChanged();
            }
        } else {
            if(_videoRunning) {
                _videoRunning = false;
                emit videoRunningChanged();
            }
        }
        if(_videoRunning) {
905 906
            uint32_t timeout = 1;
            if(qgcApp()->toolbox() && qgcApp()->toolbox()->settingsManager()) {
907
                timeout = _videoSettings->rtspTimeout()->rawValue().toUInt();
908
            }
909 910 911
            time_t elapsed = 0;
            time_t lastFrame = _videoSurface->lastFrame();
            if(lastFrame != 0) {
Gus Grubba's avatar
Gus Grubba committed
912
                elapsed = time(nullptr) - _videoSurface->lastFrame();
913
            }
Gus Grubba's avatar
Gus Grubba committed
914
            if(elapsed > static_cast<time_t>(timeout) && _videoSurface) {
915
                stop();
916 917
                // We want to start it back again with _updateTimer
                _stop = false;
918 919
            }
        } else {
920
            if(!_stop && !running() && !_uri.isEmpty() && _videoSettings->streamEnabled()->rawValue().toBool()) {
921 922 923 924 925 926 927
                start();
            }
        }
    }
#endif
}