VideoReceiver.cc 15.5 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 18


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

#include "VideoReceiver.h"
#include <QDebug>
19
#include <QUrl>
20 21
#include <QDir>
#include <QDateTime>
22
#include <QSysInfo>
23

24
VideoReceiver::Sink* VideoReceiver::_sink = NULL;
25 26
GstElement*          VideoReceiver::_pipeline = NULL;
GstElement*          VideoReceiver::_pipeline2 = NULL;
27
GstElement*          VideoReceiver::_tee = NULL;
28

29 30 31
// -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
32
#if defined(QGC_GST_STREAMING)
33 34 35 36 37 38
gboolean VideoReceiver::_eosCB(GstBus* bus, GstMessage* message, gpointer user_data)
{
    Q_UNUSED(bus);
    Q_UNUSED(message);
    Q_UNUSED(user_data);

39 40 41
    gst_bin_remove(GST_BIN(_pipeline2), _sink->queue);
    gst_bin_remove(GST_BIN(_pipeline2), _sink->mux);
    gst_bin_remove(GST_BIN(_pipeline2), _sink->filesink);
42 43 44 45

    gst_element_set_state(_pipeline2, GST_STATE_NULL);
    gst_object_unref(_pipeline2);

46 47 48
    gst_element_set_state(_sink->filesink, GST_STATE_NULL);
    gst_element_set_state(_sink->mux, GST_STATE_NULL);
    gst_element_set_state(_sink->queue, GST_STATE_NULL);
49

50 51 52
    gst_object_unref(_sink->queue);
    gst_object_unref(_sink->mux);
    gst_object_unref(_sink->filesink);
53

54 55
    delete _sink;
    _sink = NULL;
56 57 58

    return true;
}
59
#endif
60

61 62 63 64
// -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 and set up a callback for
65
#if defined(QGC_GST_STREAMING)
66 67 68 69 70 71
GstPadProbeReturn VideoReceiver::_unlinkCB(GstPad* pad, GstPadProbeInfo* info, gpointer user_data)
{
    Q_UNUSED(pad);
    Q_UNUSED(info);
    Q_UNUSED(user_data);

72 73
    // We will only execute once
    if(!g_atomic_int_compare_and_exchange(&_sink->removing, FALSE, TRUE))
74 75 76
        return GST_PAD_PROBE_OK;

    // Also unlinks and unrefs
77
    gst_bin_remove_many(GST_BIN(_pipeline), _sink->queue, _sink->mux, _sink->filesink, NULL);
78 79 80 81

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

83
    // Create temporary pipeline
84 85
    _pipeline2 = gst_pipeline_new("pipe2");

86 87 88
    // Put our elements from the recording branch into the temporary pipeline
    gst_bin_add_many(GST_BIN(_pipeline2), _sink->queue, _sink->mux, _sink->filesink, NULL);
    gst_element_link_many(_sink->queue, _sink->mux, _sink->filesink, NULL);
89

90
    // Add watch for EOS event
91 92 93
    GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline2));
    gst_bus_add_signal_watch(bus);
    g_signal_connect(bus, "message::eos", G_CALLBACK(_eosCB), NULL);
94
    gst_object_unref(bus);
95 96 97 98 99

    if(gst_element_set_state(_pipeline2, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
        qDebug() << "problem starting pipeline2";
    }

100 101 102 103
    // 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);
104 105 106

    return GST_PAD_PROBE_REMOVE;
}
107
#endif
108

109 110 111 112 113 114 115 116 117 118 119 120
// 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 |
//                                        |                                      |
//                                        +--------------------------------------+
void VideoReceiver::startRecording(void)
121
{
122
#if defined(QGC_GST_STREAMING)
123 124 125 126 127
    // exit immediately if we are already recording
    if(_pipeline == NULL || _recording) {
        return;
    }

128 129 130 131
    _sink           = g_new0(Sink, 1);
    _sink->teepad   = gst_element_get_request_pad(_tee, "src_%u");
    _sink->queue    = gst_element_factory_make("queue", NULL);
    _sink->mux      = gst_element_factory_make("matroskamux", NULL);
132 133
    _sink->filesink = gst_element_factory_make("filesink", NULL);
    _sink->removing = false;
134

135 136 137 138 139 140 141 142
    QString fileName;
    if(QSysInfo::WindowsVersion != QSysInfo::WV_None) {
        fileName = _path + "\\QGC-" + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh:mm:ss") + ".mkv";
    } else {
        fileName = _path + "/QGC-" + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh:mm:ss") + ".mkv";
    }
    g_object_set(G_OBJECT(_sink->filesink), "location", qPrintable(fileName), NULL);
    qDebug() << "New video file:" << fileName;
143

144 145 146
    gst_object_ref(_sink->queue);
    gst_object_ref(_sink->mux);
    gst_object_ref(_sink->filesink);
147

148 149
    gst_bin_add_many(GST_BIN(_pipeline), _sink->queue, _sink->mux, _sink->filesink, NULL);
    gst_element_link_many(_sink->queue, _sink->mux, _sink->filesink, NULL);
150

151 152 153
    gst_element_sync_state_with_parent(_sink->queue);
    gst_element_sync_state_with_parent(_sink->mux);
    gst_element_sync_state_with_parent(_sink->filesink);
154

155 156
    GstPad* sinkpad = gst_element_get_static_pad(_sink->queue, "sink");
    gst_pad_link(_sink->teepad, sinkpad);
157 158 159 160
    gst_object_unref(sinkpad);

    _recording = true;
    emit recordingChanged();
161
#endif
162 163
}

164
void VideoReceiver::stopRecording(void)
165
{
166
#if defined(QGC_GST_STREAMING)
167 168 169 170 171
    // exit immediately if we are not recording
    if(_pipeline == NULL || !_recording) {
        return;
    }

172
    gst_pad_add_probe(_sink->teepad, GST_PAD_PROBE_TYPE_IDLE, _unlinkCB, _sink, NULL);
173 174 175

    _recording = false;
    emit recordingChanged();
176
#endif
177
}
Gus Grubba's avatar
Gus Grubba committed
178 179 180

VideoReceiver::VideoReceiver(QObject* parent)
    : QObject(parent)
181
#if defined(QGC_GST_STREAMING)
182
    , _recording(false)
Gus Grubba's avatar
Gus Grubba committed
183
    , _videoSink(NULL)
184 185
    , _socket(NULL)
    , _serverPresent(false)
186
#endif
Gus Grubba's avatar
Gus Grubba committed
187
{
188 189 190 191
#if defined(QGC_GST_STREAMING)
    _timer.setSingleShot(true);
    connect(&_timer, &QTimer::timeout, this, &VideoReceiver::_timeout);
#endif
Gus Grubba's avatar
Gus Grubba committed
192 193 194 195
}

VideoReceiver::~VideoReceiver()
{
196
#if defined(QGC_GST_STREAMING)
197 198 199 200 201 202
    stopRecording();
    stop();
    setVideoSink(NULL);
    if(_socket) {
        delete _socket;
    }
203
#endif
Gus Grubba's avatar
Gus Grubba committed
204 205
}

206
#if defined(QGC_GST_STREAMING)
Gus Grubba's avatar
Gus Grubba committed
207 208 209 210 211 212 213 214 215 216 217
void VideoReceiver::setVideoSink(GstElement* sink)
{
    if (_videoSink) {
        gst_object_unref(_videoSink);
        _videoSink = NULL;
    }
    if (sink) {
        _videoSink = sink;
        gst_object_ref_sink(_videoSink);
    }
}
218
#endif
Gus Grubba's avatar
Gus Grubba committed
219

220
#if defined(QGC_GST_STREAMING)
221
static void newPadCB(GstElement* element, GstPad* pad, gpointer data)
222
{
223
    gchar* name;
224 225
    name = gst_pad_get_name(pad);
    g_print("A new pad %s was created\n", name);
226 227
    GstCaps* p_caps = gst_pad_get_pad_template_caps (pad);
    gchar* description = gst_caps_to_string(p_caps);
228 229
    qDebug() << p_caps << ", " << description;
    g_free(description);
230
    GstElement* p_rtph264depay = GST_ELEMENT(data);
231 232 233 234
    if(gst_element_link_pads(element, name, p_rtph264depay, "sink") == false)
        qCritical() << "newPadCB : failed to link elements\n";
    g_free(name);
}
235
#endif
236

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
#if defined(QGC_GST_STREAMING)
void VideoReceiver::_connected()
{
    //-- Server showed up. Now we start the stream.
    _timer.stop();
    delete _socket;
    _socket = NULL;
    _serverPresent = true;
    start();
}
#endif

#if defined(QGC_GST_STREAMING)
void VideoReceiver::_socketError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError);
    delete _socket;
    _socket = NULL;
    //-- Try again in 5 seconds
    _timer.start(5000);
}
#endif

#if defined(QGC_GST_STREAMING)
void VideoReceiver::_timeout()
{
    //-- If socket is live, we got no connection nor a socket error
    if(_socket) {
        delete _socket;
        _socket = NULL;
    }
    //-- 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);
    _socket = new QTcpSocket;
    connect(_socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &VideoReceiver::_socketError);
    connect(_socket, &QTcpSocket::connected, this, &VideoReceiver::_connected);
    //qDebug() << "Trying to connect to:" << url.host() << url.port();
    _socket->connectToHost(url.host(), url.port());
    _timer.start(5000);
}
#endif

282 283 284 285 286 287 288 289 290
// When we finish our pipeline will look like this:
//
//                                   +-->queue-->decoder-->_videosink
//                                   |
//    datasource-->demux-->parser-->tee
//
//                                   ^
//                                   |
//                                   +-Here we will later link elements for recording
Gus Grubba's avatar
Gus Grubba committed
291 292
void VideoReceiver::start()
{
293
#if defined(QGC_GST_STREAMING)
Gus Grubba's avatar
Gus Grubba committed
294 295 296 297 298 299 300 301 302
    if (_uri.isEmpty()) {
        qCritical() << "VideoReceiver::start() failed because URI is not specified";
        return;
    }
    if (_videoSink == NULL) {
        qCritical() << "VideoReceiver::start() failed because video sink is not set";
        return;
    }

303 304
    bool isUdp = _uri.contains("udp://");

Gus Grubba's avatar
Gus Grubba committed
305 306
    stop();

307 308 309 310 311 312
    //-- For RTSP, check to see if server is there first
    if(!_serverPresent && !isUdp) {
        _timer.start(100);
        return;
    }

Gus Grubba's avatar
Gus Grubba committed
313 314 315 316 317 318
    bool running = false;

    GstElement*     dataSource  = NULL;
    GstCaps*        caps        = NULL;
    GstElement*     demux       = NULL;
    GstElement*     parser      = NULL;
319
    GstElement*     queue      = NULL;
Gus Grubba's avatar
Gus Grubba committed
320
    GstElement*     decoder     = NULL;
321

Gus Grubba's avatar
Gus Grubba committed
322 323
    do {
        if ((_pipeline = gst_pipeline_new("receiver")) == NULL) {
324
            qCritical() << "VideoReceiver::start() failed. Error with gst_pipeline_new()";
Gus Grubba's avatar
Gus Grubba committed
325 326 327
            break;
        }

328 329 330 331
        if(isUdp) {
            dataSource = gst_element_factory_make("udpsrc", "udp-source");
        } else {
            dataSource = gst_element_factory_make("rtspsrc", "rtsp-source");
Gus Grubba's avatar
Gus Grubba committed
332 333
        }

334 335
        if (!dataSource) {
            qCritical() << "VideoReceiver::start() failed. Error with data source for gst_element_factory_make()";
Gus Grubba's avatar
Gus Grubba committed
336 337 338
            break;
        }

339 340 341 342 343 344 345
        if(isUdp) {
            if ((caps = gst_caps_from_string("application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264")) == NULL) {
                qCritical() << "VideoReceiver::start() failed. Error with gst_caps_from_string()";
                break;
            }
            g_object_set(G_OBJECT(dataSource), "uri", qPrintable(_uri), "caps", caps, NULL);
        } else {
346
            g_object_set(G_OBJECT(dataSource), "location", qPrintable(_uri), "latency", 0, "udp-reconnect", 1, "timeout", 5000000, NULL);
347
        }
Gus Grubba's avatar
Gus Grubba committed
348 349

        if ((demux = gst_element_factory_make("rtph264depay", "rtp-h264-depacketizer")) == NULL) {
350
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('rtph264depay')";
Gus Grubba's avatar
Gus Grubba committed
351 352 353
            break;
        }

354 355 356 357
        if(!isUdp) {
            g_signal_connect(dataSource, "pad-added", G_CALLBACK(newPadCB), demux);
        }

Gus Grubba's avatar
Gus Grubba committed
358
        if ((parser = gst_element_factory_make("h264parse", "h264-parser")) == NULL) {
359
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('h264parse')";
Gus Grubba's avatar
Gus Grubba committed
360 361 362 363
            break;
        }

        if ((decoder = gst_element_factory_make("avdec_h264", "h264-decoder")) == NULL) {
364
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('avdec_h264')";
Gus Grubba's avatar
Gus Grubba committed
365 366 367
            break;
        }

368
        if((_tee = gst_element_factory_make("tee", NULL)) == NULL)  {
369 370 371
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('tee')";
            break;
        }
Gus Grubba's avatar
Gus Grubba committed
372

373
        if((queue = gst_element_factory_make("queue", NULL)) == NULL)  {
374 375 376
            qCritical() << "VideoReceiver::start() failed. Error with gst_element_factory_make('queue1')";
            break;
        }
377

378
        gst_bin_add_many(GST_BIN(_pipeline), dataSource, demux, parser, _tee, queue, decoder, _videoSink, NULL);
379

380 381
        if(isUdp) {
            // Link the pipeline in front of the tee
382 383
            if(!gst_element_link_many(dataSource, demux, parser, _tee, queue, decoder, _videoSink, NULL)) {
                qCritical() << "Unable to link elements.";
384 385 386
                break;
            }
        } else {
387 388
            if(!gst_element_link_many(demux, parser, _tee, queue, decoder, _videoSink, NULL)) {
                qCritical() << "Unable to link elements.";
389 390
                break;
            }
391 392
        }

393
        dataSource = demux = parser = queue = decoder = NULL;
Gus Grubba's avatar
Gus Grubba committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

        GstBus* bus = NULL;

        if ((bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline))) != NULL) {
            gst_bus_add_watch(bus, _onBusMessage, this);
            gst_object_unref(bus);
            bus = NULL;
        }

        running = gst_element_set_state(_pipeline, GST_STATE_PLAYING) != GST_STATE_CHANGE_FAILURE;

    } while(0);

    if (caps != NULL) {
        gst_caps_unref(caps);
        caps = NULL;
    }

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

        if (decoder != NULL) {
            gst_object_unref(decoder);
            decoder = NULL;
        }

        if (parser != NULL) {
            gst_object_unref(parser);
            parser = NULL;
        }

        if (demux != NULL) {
            gst_object_unref(demux);
            demux = NULL;
        }

        if (dataSource != NULL) {
            gst_object_unref(dataSource);
            dataSource = NULL;
        }

435 436
        if (_tee != NULL) {
            gst_object_unref(_tee);
437 438 439
            dataSource = NULL;
        }

440 441
        if (queue != NULL) {
            gst_object_unref(queue);
442 443 444
            dataSource = NULL;
        }

Gus Grubba's avatar
Gus Grubba committed
445 446 447 448 449
        if (_pipeline != NULL) {
            gst_object_unref(_pipeline);
            _pipeline = NULL;
        }
    }
450
    qDebug() << "Video Receiver started.";
451
#endif
Gus Grubba's avatar
Gus Grubba committed
452 453 454 455
}

void VideoReceiver::stop()
{
456
#if defined(QGC_GST_STREAMING)
Gus Grubba's avatar
Gus Grubba committed
457
    if (_pipeline != NULL) {
458
        qDebug() << "Stopping pipeline";
Gus Grubba's avatar
Gus Grubba committed
459 460 461
        gst_element_set_state(_pipeline, GST_STATE_NULL);
        gst_object_unref(_pipeline);
        _pipeline = NULL;
462
        _serverPresent = false;
Gus Grubba's avatar
Gus Grubba committed
463
    }
464
#endif
Gus Grubba's avatar
Gus Grubba committed
465 466 467 468 469 470 471 472
}

void VideoReceiver::setUri(const QString & uri)
{
    stop();
    _uri = uri;
}

473 474 475 476 477 478
void VideoReceiver::setVideoSavePath(const QString & path)
{
    _path = path;
    qDebug() << "New Path:" << _path;
}

479
#if defined(QGC_GST_STREAMING)
Gus Grubba's avatar
Gus Grubba committed
480 481 482 483
void VideoReceiver::_onBusMessage(GstMessage* msg)
{
    switch (GST_MESSAGE_TYPE(msg)) {
    case GST_MESSAGE_EOS:
484
        stop();
Gus Grubba's avatar
Gus Grubba committed
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        break;
    case GST_MESSAGE_ERROR:
        do {
            gchar* debug;
            GError* error;
            gst_message_parse_error(msg, &error, &debug);
            g_free(debug);
            qCritical() << error->message;
            g_error_free(error);
        } while(0);
        stop();
        break;
    default:
        break;
    }
}
501
#endif
Gus Grubba's avatar
Gus Grubba committed
502

503
#if defined(QGC_GST_STREAMING)
Gus Grubba's avatar
Gus Grubba committed
504 505 506 507 508 509 510 511
gboolean VideoReceiver::_onBusMessage(GstBus* bus, GstMessage* msg, gpointer data)
{
    Q_UNUSED(bus)
    Q_ASSERT(msg != NULL && data != NULL);
    VideoReceiver* pThis = (VideoReceiver*)data;
    pThis->_onBusMessage(msg);
    return TRUE;
}
512
#endif