VideoReceiver.cc 41.4 KB
Newer Older
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8
 *
 * 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


/**
 * @file
 *   @brief QGC Video Receiver
Gus Grubba's avatar
Gus Grubba committed
14
 *   @author Gus Grubba <gus@auterion.com>
Gus Grubba's avatar
Gus Grubba committed
15 16 17
 */

#include "VideoReceiver.h"
18

Gus Grubba's avatar
Gus Grubba committed
19
#include <QDebug>
20
#include <QUrl>
21
#include <QDateTime>
22
#include <QSysInfo>
23

24 25
QGC_LOGGING_CATEGORY(VideoReceiverLog, "VideoReceiverLog")

26 27 28 29 30 31 32 33 34
//-----------------------------------------------------------------------------
// Our pipeline look like this:
//
//              +-->queue-->_decoderValve[-->_decoder-->_videoSink]
//              |
// _source-->_tee
//              |
//              +-->queue-->_recorderValve[-->_fileSink]
//
35

Gus Grubba's avatar
Gus Grubba committed
36
VideoReceiver::VideoReceiver(QObject* parent)
37
    : QThread(parent)
38
#if defined(QGC_GST_STREAMING)
39 40 41
    , _removingDecoder(false)
    , _removingRecorder(false)
    , _source(nullptr)
Gus Grubba's avatar
Gus Grubba committed
42
    , _tee(nullptr)
43 44 45
    , _decoderValve(nullptr)
    , _recorderValve(nullptr)
    , _decoder(nullptr)
Gus Grubba's avatar
Gus Grubba committed
46
    , _videoSink(nullptr)
47 48 49 50 51 52
    , _fileSink(nullptr)
    , _pipeline(nullptr)
    , _lastSourceFrameTime(0)
    , _lastVideoFrameTime(0)
    , _resetVideoSink(true)
    , _videoSinkProbeId(0)
53
    , _udpReconnect_us(5000000)
54
    , _shutdown(false)
55
#endif
56 57 58
    , _streaming(false)
    , _decoding(false)
    , _recording(false)
Gus Grubba's avatar
Gus Grubba committed
59
{
60
#if defined(QGC_GST_STREAMING)
61 62 63
    QThread::start();
    connect(&_watchdogTimer, &QTimer::timeout, this, &VideoReceiver::_watchdog);
    _watchdogTimer.start(1000);
64
#endif
Gus Grubba's avatar
Gus Grubba committed
65 66
}

67
VideoReceiver::~VideoReceiver(void)
Gus Grubba's avatar
Gus Grubba committed
68
{
69
#if defined(QGC_GST_STREAMING)
70
    stop();
71 72 73 74
    _post([this](){
        _shutdown = true;
    });
    QThread::wait();
75
#endif
Gus Grubba's avatar
Gus Grubba committed
76 77
}

78
void
79
VideoReceiver::start(const QString& uri, unsigned timeout)
80
{
81
#if defined(QGC_GST_STREAMING)
82 83 84 85 86 87
    if (!_isOurThread()) {
        _post([this, uri, timeout]() {
            start(uri, timeout);
        });
        return;
    }
88

89 90 91 92
    if(_pipeline) {
        qCDebug(VideoReceiverLog) << "Already running!";
        return;
    }
93

94 95 96
    if (uri.isEmpty()) {
        qCDebug(VideoReceiverLog) << "Failed because URI is not specified";
        return;
97 98
    }

99
    qCDebug(VideoReceiverLog) << "Starting";
100

101
    _timeout = timeout;
102

103 104
    bool running    = false;
    bool pipelineUp = false;
105

106 107
    GstElement* decoderQueue = nullptr;
    GstElement* recorderQueue = nullptr;
108

109 110 111 112 113
    do {
        if((_tee = gst_element_factory_make("tee", nullptr)) == nullptr)  {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('tee') failed";
            break;
        }
114

115
        GstPad* pad;
116

117 118 119 120
        if ((pad = gst_element_get_static_pad(_tee, "sink")) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_element_get_static_pad() failed";
            break;
        }
121

122
        _lastSourceFrameTime = 0;
123

124 125 126
        gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_BUFFER, _teeProbe, this, nullptr);
        gst_object_unref(pad);
        pad = nullptr;
127

128 129 130 131
        if((decoderQueue = gst_element_factory_make("queue", nullptr)) == nullptr)  {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('queue') failed";
            break;
        }
132

133 134 135 136
        if((_decoderValve = gst_element_factory_make("valve", nullptr)) == nullptr)  {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('valve') failed";
            break;
        }
137

138
        g_object_set(_decoderValve, "drop", TRUE, nullptr);
139

140 141 142 143
        if((recorderQueue = gst_element_factory_make("queue", nullptr)) == nullptr)  {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('queue') failed";
            break;
        }
144

145 146 147 148
        if((_recorderValve = gst_element_factory_make("valve", nullptr)) == nullptr)  {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('valve') failed";
            break;
        }
149

150
        g_object_set(_recorderValve, "drop", TRUE, nullptr);
151

152 153 154 155
        if ((_pipeline = gst_pipeline_new("receiver")) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_pipeline_new() failed";
            break;
        }
156

157
        g_object_set(_pipeline, "message-forward", TRUE, nullptr);
158

159 160 161 162
        if ((_source = _makeSource(uri)) == nullptr) {
            qCCritical(VideoReceiverLog) << "_makeSource() failed";
            break;
        }
163

164
        g_signal_connect(_source, "pad-added", G_CALLBACK(_onNewPad), this);
165

166
        gst_bin_add_many(GST_BIN(_pipeline), _source, _tee, decoderQueue, _decoderValve, recorderQueue, _recorderValve, nullptr);
167

168
        pipelineUp = true;
169

170 171 172 173
        if(!gst_element_link_many(_tee, decoderQueue, _decoderValve, nullptr)) {
            qCCritical(VideoReceiverLog) << "Unable to link decoder queue";
            break;
        }
174

175 176 177 178
        if(!gst_element_link_many(_tee, recorderQueue, _recorderValve, nullptr)) {
            qCCritical(VideoReceiverLog) << "Unable to link recorder queue";
            break;
        }
179

180
        GstBus* bus = nullptr;
181

182 183 184 185 186 187
        if ((bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline))) != nullptr) {
            gst_bus_enable_sync_message_emission(bus);
            g_signal_connect(bus, "sync-message", G_CALLBACK(_onBusMessage), this);
            gst_object_unref(bus);
            bus = nullptr;
        }
188

189 190 191 192 193 194 195 196 197 198 199 200
        GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-initial");
        running = gst_element_set_state(_pipeline, GST_STATE_PLAYING) != GST_STATE_CHANGE_FAILURE;
    } while(0);

    if (!running) {
        qCCritical(VideoReceiverLog) << "Failed";

        // In newer versions, the pipeline will clean up all references that are added to it
        if (_pipeline != nullptr) {
            gst_element_set_state(_pipeline, GST_STATE_NULL);
            gst_object_unref(_pipeline);
            _pipeline = nullptr;
201 202
        }

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        // If we failed before adding items to the pipeline, then clean up
        if (!pipelineUp) {
            if (_recorderValve != nullptr) {
                gst_object_unref(_recorderValve);
                _recorderValve = nullptr;
            }

            if (recorderQueue != nullptr) {
                gst_object_unref(recorderQueue);
                recorderQueue = nullptr;
            }

            if (_decoderValve != nullptr) {
                gst_object_unref(_decoderValve);
                _decoderValve = nullptr;
            }

            if (decoderQueue != nullptr) {
                gst_object_unref(decoderQueue);
                decoderQueue = nullptr;
            }

            if (_tee != nullptr) {
                gst_object_unref(_tee);
                _tee = nullptr;
            }

            if (_source != nullptr) {
                gst_object_unref(_source);
                _source = nullptr;
            }
        }
    } else {
        GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-started");
        qCDebug(VideoReceiverLog) << "Started";
238
    }
239 240 241 242 243
#else
    Q_UNUSED(uri);
    Q_UNUSED(timeout);
#endif
}
244

245 246 247 248 249 250 251 252 253 254
void
VideoReceiver::stop(void)
{
#if defined(QGC_GST_STREAMING)
    if (!_isOurThread()) {
        _post([this]() {
            stop();
        });
        return;
    }
255

256
    qCDebug(VideoReceiverLog) << "Stopping";
257

258 259
    if (_pipeline != nullptr) {
        GstBus* bus;
260

261 262
        if ((bus = gst_pipeline_get_bus(GST_PIPELINE(_pipeline))) != nullptr) {
            gst_bus_disable_sync_message_emission(bus);
263

264
            gst_element_send_event(_pipeline, gst_event_new_eos());
265

266
            GstMessage* msg;
267

268 269 270 271 272
            if((msg = gst_bus_timed_pop_filtered(bus, GST_CLOCK_TIME_NONE, (GstMessageType)(GST_MESSAGE_EOS|GST_MESSAGE_ERROR))) != nullptr) {
                if(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_ERROR) {
                    qCCritical(VideoReceiverLog) << "Error stopping pipeline!";
                } else if(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS) {
                    qCDebug(VideoReceiverLog) << "End of stream received!";
273
                }
274 275 276

                gst_message_unref(msg);
                msg = nullptr;
277
            } else {
278
                qCCritical(VideoReceiverLog) << "gst_bus_timed_pop_filtered() failed";
279
            }
280 281 282

            gst_object_unref(bus);
            bus = nullptr;
283
        } else {
284
            qCCritical(VideoReceiverLog) << "gst_pipeline_get_bus() failed";
285 286
        }

287
        gst_element_set_state(_pipeline, GST_STATE_NULL);
288

289 290 291 292
        // FIXME: check if branch is connected and remove all elements from branch
        if (_fileSink != nullptr) {
           _shutdownRecordingBranch();
        }
293

294 295 296
        if (_videoSink != nullptr) {
            _shutdownDecodingBranch();
        }
297

298
        GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-stopped");
299

300 301
        gst_object_unref(_pipeline);
        _pipeline = nullptr;
302

303 304 305 306
        _recorderValve = nullptr;
        _decoderValve = nullptr;
        _tee = nullptr;
        _source = nullptr;
307

308
        _lastSourceFrameTime = 0;
309

310 311 312 313 314
        if (_streaming) {
            _streaming = false;
            emit streamingChanged();
            qCDebug(VideoReceiverLog) << "Streaming stopped";
        }
315 316
    }

317 318
    qCDebug(VideoReceiverLog) << "Stopped";
#endif
319 320
}

321 322
void
VideoReceiver::startDecoding(VideoSink* videoSink)
323
{
324 325 326 327 328 329 330 331
#if defined(QGC_GST_STREAMING)
    if (!_isOurThread()) {
        gst_object_ref(videoSink);
        _post([this, videoSink]() {
            startDecoding(videoSink);
            gst_object_unref(videoSink);
        });
        return;
332 333
    }

334
    qCDebug(VideoReceiverLog) << "Starting decoding";
335

336 337 338 339 340 341
    if (_pipeline == nullptr) {
        if (_videoSink != nullptr) {
            gst_object_unref(_videoSink);
            _videoSink = nullptr;
        }
    }
342

343 344 345 346
    if(_videoSink != nullptr || _decoding) {
        qCDebug(VideoReceiverLog) << "Already decoding!";
        return;
    }
347

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    GstPad* pad;

    if ((pad = gst_element_get_static_pad(videoSink, "sink")) == nullptr) {
        qCCritical(VideoReceiverLog) << "Unable to find sink pad of video sink";
        return;
    }

    _lastVideoFrameTime = 0;
    _resetVideoSink = true;

    _videoSinkProbeId = gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_BUFFER, _videoSinkProbe, this, nullptr);
    gst_object_unref(pad);
    pad = nullptr;

    _videoSink = videoSink;
    gst_object_ref(_videoSink);

    _removingDecoder = false;

    if (!_streaming) {
        return;
    }

    if (!_addDecoder(_decoderValve)) {
        qCCritical(VideoReceiverLog) << "_addDecoder() failed";
        return;
    }

    g_object_set(_decoderValve, "drop", FALSE, nullptr);

    qCDebug(VideoReceiverLog) << "Decoding started";
#else
    Q_UNUSED(videoSink)
#endif
}

void
VideoReceiver::stopDecoding(void)
{
#if defined(QGC_GST_STREAMING)
    if (!_isOurThread()) {
        _post([this]() {
            stopDecoding();
        });
        return;
    }

    qCDebug(VideoReceiverLog) << "Stopping decoding";

    // exit immediately if we are not decoding
    if (_pipeline == nullptr || !_decoding) {
        qCDebug(VideoReceiverLog) << "Not decoding!";
        return;
    }

    g_object_set(_decoderValve, "drop", TRUE, nullptr);

    _removingDecoder = true;

    _unlinkBranch(_decoderValve);
#endif
}

void
VideoReceiver::startRecording(const QString& videoFile, FILE_FORMAT format)
{
#if defined(QGC_GST_STREAMING)
    if (!_isOurThread()) {
        _post([this, videoFile, format]() {
            startRecording(videoFile, format);
        });
        return;
    }

    qCDebug(VideoReceiverLog) << "Starting recording";

    // exit immediately if we are already recording
    if (_pipeline == nullptr || _recording) {
        qCDebug(VideoReceiverLog) << "Already recording!";
        return;
    }

    qCDebug(VideoReceiverLog) << "New video file:" << videoFile;

    if ((_fileSink = _makeFileSink(videoFile, format)) == nullptr) {
        qCCritical(VideoReceiverLog) << "_makeFileSink() failed";
        return;
    }

    _removingRecorder = false;

    gst_object_ref(_fileSink);

    gst_bin_add(GST_BIN(_pipeline), _fileSink);

    if (!gst_element_link(_recorderValve, _fileSink)) {
        qCCritical(VideoReceiverLog) << "Failed to link valve and file sink";
        return;
    }

    gst_element_sync_state_with_parent(_fileSink);

    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-with-filesink");

    // 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;

    if ((probepad  = gst_element_get_static_pad(_recorderValve, "src")) == nullptr) {
        qCCritical(VideoReceiverLog) << "gst_element_get_static_pad() failed";
        return;
    }

    gst_pad_add_probe(probepad, GST_PAD_PROBE_TYPE_BUFFER, _keyframeWatch, this, nullptr); // to drop the buffers until key frame is received
    gst_object_unref(probepad);
    probepad = nullptr;

    g_object_set(_recorderValve, "drop", FALSE, nullptr);

    _recording = true;

    emit recordingChanged();

    qCDebug(VideoReceiverLog) << "Recording started";
#else
    Q_UNUSED(videoFile)
    Q_UNUSED(format)
#endif
}

//-----------------------------------------------------------------------------
void
VideoReceiver::stopRecording(void)
{
#if defined(QGC_GST_STREAMING)
    if (!_isOurThread()) {
        _post([this]() {
            stopRecording();
        });
        return;
    }

    qCDebug(VideoReceiverLog) << "Stopping recording";

    // exit immediately if we are not recording
    if (_pipeline == nullptr || !_recording) {
        qCDebug(VideoReceiverLog) << "Not recording!";
        return;
    }

    g_object_set(_recorderValve, "drop", TRUE, nullptr);

    _removingRecorder = true;

    _unlinkBranch(_recorderValve);
#endif
}

void
VideoReceiver::takeScreenshot(const QString& imageFile)
{
#if defined(QGC_GST_STREAMING)
    if (!_isOurThread()) {
        _post([this, imageFile]() {
            takeScreenshot(imageFile);
        });
        return;
    }

    // FIXME: AV: record screenshot here
    emit screenshotComplete();
#else
    Q_UNUSED(imageFile);
#endif
}

#if defined(QGC_GST_STREAMING)
const char* VideoReceiver::_kFileMux[FILE_FORMAT_MAX - FILE_FORMAT_MIN] = {
    "matroskamux",
    "qtmux",
    "mp4mux"
};

void
VideoReceiver::_watchdog(void)
{
    _post([this](){
        if(_pipeline == nullptr) {
            return;
        }

        const qint64 now = QDateTime::currentSecsSinceEpoch();

        if (_lastSourceFrameTime == 0) {
            _lastSourceFrameTime = now;
        }

        if (now - _lastSourceFrameTime > _timeout) {
            emit timeout();
        }

        if (_decoding && !_removingDecoder) {
            if (_lastVideoFrameTime == 0) {
                _lastVideoFrameTime = now;
            }

            if (now - _lastVideoFrameTime > _timeout * 2) {
                emit timeout();
            }
        }
    });
}

void
VideoReceiver::_handleEOS(void)
{
    if(_pipeline == nullptr) {
        qCWarning(VideoReceiverLog) << "We should not be here";
        return;
    }

    if (!_streaming) {
        stop();
    } else {
        if(_decoding && _removingDecoder) {
            _shutdownDecodingBranch();
        } else if(_recording && _removingRecorder) {
            _shutdownRecordingBranch();
        } else {
            qCWarning(VideoReceiverLog) << "Unexpected EOS!";
            stop();
        }
    }
}

GstElement*
VideoReceiver::_makeSource(const QString& uri)
{
    if (uri.isEmpty()) {
        qCCritical(VideoReceiverLog) << "Failed because URI is not specified";
        return nullptr;
    }

    bool isTaisync  = uri.contains("tsusb://");
    bool isUdp264   = uri.contains("udp://");
    bool isRtsp     = uri.contains("rtsp://");
    bool isUdp265   = uri.contains("udp265://");
    bool isTcpMPEGTS= uri.contains("tcp://");
    bool isUdpMPEGTS= uri.contains("mpegts://");

    GstElement* source  = nullptr;
    GstElement* buffer  = nullptr;
    GstElement* tsdemux = nullptr;
    GstElement* parser  = nullptr;
    GstElement* bin     = nullptr;
    GstElement* srcbin  = nullptr;

    do {
        QUrl url(uri);

        if(isTcpMPEGTS) {
            if ((source = gst_element_factory_make("tcpclientsrc", "source")) != nullptr) {
                g_object_set(static_cast<gpointer>(source), "host", qPrintable(url.host()), "port", url.port(), nullptr);
            }
        } else if (isRtsp) {
            if ((source = gst_element_factory_make("rtspsrc", "source")) != nullptr) {
                g_object_set(static_cast<gpointer>(source), "location", qPrintable(uri), "latency", 17, "udp-reconnect", 1, "timeout", _udpReconnect_us, NULL);
            }
        } else if(isUdp264 || isUdp265 || isUdpMPEGTS || isTaisync) {
            if ((source = gst_element_factory_make("udpsrc", "source")) != nullptr) {
619 620 621 622 623 624
                g_object_set(static_cast<gpointer>(source), "uri", QString("udp://%1:%2").arg(qPrintable(url.host()), QString::number(url.port())).toUtf8().data(), nullptr);

                GstCaps* caps = nullptr;

                if(isUdp264) {
                    if ((caps = gst_caps_from_string("application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264")) == nullptr) {
625
                        qCCritical(VideoReceiverLog) << "gst_caps_from_string() failed";
626 627
                        break;
                    }
628
                } else if (isUdp265) {
629
                    if ((caps = gst_caps_from_string("application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H265")) == nullptr) {
630
                        qCCritical(VideoReceiverLog) << "gst_caps_from_string() failed";
631 632 633 634 635 636 637 638 639 640 641
                        break;
                    }
                }

                if (caps != nullptr) {
                    g_object_set(static_cast<gpointer>(source), "caps", caps, nullptr);
                    gst_caps_unref(caps);
                    caps = nullptr;
                }
            }
        } else {
642
            qCDebug(VideoReceiverLog) << "URI is not recognized";
643 644 645
        }

        if (!source) {
646
            qCCritical(VideoReceiverLog) << "gst_element_factory_make() for data source failed";
647 648 649
            break;
        }

650 651 652 653 654 655 656 657 658 659 660 661
        if ((bin = gst_bin_new("sourcebin")) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_bin_new('sourcebin') failed";
            break;
        }

        if ((parser = gst_element_factory_make("parsebin", "parser")) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('parsebin') failed";
            break;
        }

        gst_bin_add_many(GST_BIN(bin), source, parser, nullptr);

662
        // FIXME: AV: Android does not determine MPEG2-TS via parsebin - have to explicitly state which demux to use
663
        // FIXME: AV: tsdemux handling is a bit ugly - let's try to find elegant solution for that later
664
        if (isTcpMPEGTS || isUdpMPEGTS) {
665 666
            if ((tsdemux = gst_element_factory_make("tsdemux", nullptr)) == nullptr) {
                qCCritical(VideoReceiverLog) << "gst_element_factory_make('tsdemux') failed";
667 668
                break;
            }
669 670 671 672 673

            gst_bin_add(GST_BIN(bin), tsdemux);

            if (!gst_element_link(source, tsdemux)) {
                qCCritical(VideoReceiverLog) << "gst_element_link() failed";
674 675
                break;
            }
676

677 678
            source = tsdemux;
            tsdemux = nullptr;
679 680 681 682 683 684 685 686
        }

        int probeRes = 0;

        gst_element_foreach_src_pad(source, _padProbe, &probeRes);

        if (probeRes & 1) {
            if (probeRes & 2) {
687
                if ((buffer = gst_element_factory_make("rtpjitterbuffer", nullptr)) == nullptr) {
688
                    qCCritical(VideoReceiverLog) << "gst_element_factory_make('rtpjitterbuffer') failed";
689 690 691 692 693 694
                    break;
                }

                gst_bin_add(GST_BIN(bin), buffer);

                if (!gst_element_link_many(source, buffer, parser, nullptr)) {
695
                    qCCritical(VideoReceiverLog) << "gst_element_link() failed";
696 697 698 699
                    break;
                }
            } else {
                if (!gst_element_link(source, parser)) {
700
                    qCCritical(VideoReceiverLog) << "gst_element_link() failed";
701 702 703 704 705 706 707 708 709
                    break;
                }
            }
        } else {
            g_signal_connect(source, "pad-added", G_CALLBACK(_linkPadWithOptionalBuffer), parser);
        }

        g_signal_connect(parser, "pad-added", G_CALLBACK(_wrapWithGhostPad), nullptr);

710
        source = tsdemux = buffer = parser = nullptr;
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725

        srcbin = bin;
        bin = nullptr;
    } while(0);

    if (bin != nullptr) {
        gst_object_unref(bin);
        bin = nullptr;
    }

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

726 727 728 729 730
    if (tsdemux != nullptr) {
        gst_object_unref(tsdemux);
        tsdemux = nullptr;
    }

731 732 733 734 735 736 737 738 739 740 741 742 743
    if (buffer != nullptr) {
        gst_object_unref(buffer);
        buffer = nullptr;
    }

    if (source != nullptr) {
        gst_object_unref(source);
        source = nullptr;
    }

    return srcbin;
}

744 745
GstElement*
VideoReceiver::_makeDecoder(GstCaps* caps, GstElement* videoSink)
746
{
747
    GstElement* decoder = nullptr;
748

749 750 751 752 753
    do {
        if ((decoder = gst_element_factory_make("decodebin", nullptr)) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('decodebin') failed";
            break;
        }
754

755 756
        g_signal_connect(decoder, "autoplug-query", G_CALLBACK(_autoplugQuery), videoSink);
    } while(0);
757

758
    return decoder;
759 760
}

761 762
GstElement*
VideoReceiver::_makeFileSink(const QString& videoFile, FILE_FORMAT format)
763
{
764 765 766 767 768
    GstElement* fileSink = nullptr;
    GstElement* mux = nullptr;
    GstElement* sink = nullptr;
    GstElement* bin = nullptr;
    bool releaseElements = true;
769

770 771 772 773 774
    do{
        if (format < FILE_FORMAT_MIN || format >= FILE_FORMAT_MAX) {
            qCCritical(VideoReceiverLog) << "Unsupported file format";
            break;
        }
775

776 777 778 779
        if ((mux = gst_element_factory_make(_kFileMux[format - FILE_FORMAT_MIN], nullptr)) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('" << _kFileMux[format - FILE_FORMAT_MIN] << "') failed";
            break;
        }
780

781 782 783 784
        if ((sink = gst_element_factory_make("filesink", nullptr)) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_element_factory_make('filesink') failed";
            break;
        }
785

786
        g_object_set(static_cast<gpointer>(sink), "location", qPrintable(videoFile), nullptr);
787

788 789 790 791
        if ((bin = gst_bin_new("sinkbin")) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_bin_new('sinkbin') failed";
            break;
        }
792

793
        GstPadTemplate* padTemplate;
794

795 796 797 798
        if ((padTemplate = gst_element_class_get_pad_template(GST_ELEMENT_GET_CLASS(mux), "video_%u")) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_element_class_get_pad_template(mux) failed";
            break;
        }
799

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
        // FIXME: AV: pad handling is potentially leaking (and other similar places too!)
        GstPad* pad;

        if ((pad = gst_element_request_pad(mux, padTemplate, nullptr, nullptr)) == nullptr) {
            qCCritical(VideoReceiverLog) << "gst_element_request_pad(mux) failed";
            break;
        }

        gst_bin_add_many(GST_BIN(bin), mux, sink, nullptr);

        releaseElements = false;

        GstPad* ghostpad = gst_ghost_pad_new("sink", pad);

        gst_element_add_pad(bin, ghostpad);

        gst_object_unref(pad);
        pad = nullptr;

        if (!gst_element_link(mux, sink)) {
            qCCritical(VideoReceiverLog) << "gst_element_link() failed";
            break;
        }

        fileSink = bin;
        bin = nullptr;
    } while(0);

    if (releaseElements) {
        if (sink != nullptr) {
            gst_object_unref(sink);
            sink = nullptr;
        }

        if (mux != nullptr) {
            gst_object_unref(mux);
            mux = nullptr;
        }
838 839
    }

840 841 842 843
    if (bin != nullptr) {
        gst_object_unref(bin);
        bin = nullptr;
    }
844

845 846
    return fileSink;
}
847

848
void
849
VideoReceiver::_onNewSourcePad(GstPad* pad)
Gus Grubba's avatar
Gus Grubba committed
850
{
851 852 853
    // FIXME: check for caps - if this is not video stream (and preferably - one of these which we have to support) then simply skip it
    if(!gst_element_link(_source, _tee)) {
        qCCritical(VideoReceiverLog) << "Unable to link source";
854 855
        return;
    }
856 857 858 859 860 861 862 863 864 865

    if (!_streaming) {
        _streaming = true;
        qCDebug(VideoReceiverLog) << "Streaming started";
        emit streamingChanged();
    }

    gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, _eosProbe, this, nullptr);

    if (_videoSink == nullptr) {
866 867
        return;
    }
868

869 870 871 872 873 874 875 876 877 878 879
    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-with-new-source-pad");

    if (!_addDecoder(_decoderValve)) {
        qCCritical(VideoReceiverLog) << "_addDecoder() failed";
        return;
    }

    g_object_set(_decoderValve, "drop", FALSE, nullptr);

    qCDebug(VideoReceiverLog) << "Decoding started";
}
880

881 882 883 884
void
VideoReceiver::_onNewDecoderPad(GstPad* pad)
{
    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-with-new-decoder-pad");
885

886 887
    if (!_addVideoSink(pad)) {
        qCCritical(VideoReceiverLog) << "_addVideoSink() failed";
888
    }
889
}
890

891 892 893 894 895 896 897 898
bool
VideoReceiver::_addDecoder(GstElement* src)
{
    GstPad* srcpad;

    if ((srcpad = gst_element_get_static_pad(src, "src")) == nullptr) {
        qCCritical(VideoReceiverLog) << "gst_element_get_static_pad() failed";
        return false;
Gus Grubba's avatar
Gus Grubba committed
899
    }
900

901 902 903 904 905 906 907
    GstCaps* caps;

    if ((caps = gst_pad_query_caps(srcpad, nullptr)) == nullptr) {
        qCCritical(VideoReceiverLog) << "gst_pad_query_caps() failed";
        gst_object_unref(srcpad);
        srcpad = nullptr;
        return false;
Gus Grubba's avatar
Gus Grubba committed
908
    }
909 910 911 912 913 914 915 916 917

    gst_object_unref(srcpad);
    srcpad = nullptr;

    if ((_decoder = _makeDecoder(caps, _videoSink)) == nullptr) {
        qCCritical(VideoReceiverLog) << "_makeDecoder() failed";
        gst_caps_unref(caps);
        caps = nullptr;
        return false;
918
    }
Gus Grubba's avatar
Gus Grubba committed
919

920
    gst_object_ref(_decoder);
921

922 923
    gst_caps_unref(caps);
    caps = nullptr;
924

925 926 927 928
    // FIXME: AV: check if srcpad exists - if it does then no need to wait for new pad
    //    int probeRes = 0;
    //    gst_element_foreach_src_pad(source, _padProbe, &probeRes);
    g_signal_connect(_decoder, "pad-added", G_CALLBACK(_onNewPad), this);
Gus Grubba's avatar
Gus Grubba committed
929

930
    gst_bin_add(GST_BIN(_pipeline), _decoder);
931

932
    gst_element_sync_state_with_parent(_decoder);
Gus Grubba's avatar
Gus Grubba committed
933

934
    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-with-decoder");
935

936 937 938 939
    if (!gst_element_link(src, _decoder)) {
        qCCritical(VideoReceiverLog) << "Unable to link decoder";
        return false;
    }
Gus Grubba's avatar
Gus Grubba committed
940

941 942
    return true;
}
Gus Grubba's avatar
Gus Grubba committed
943

944 945 946 947
bool
VideoReceiver::_addVideoSink(GstPad* pad)
{
    GstCaps* caps = gst_pad_query_caps(pad, nullptr);
948

949 950 951 952 953 954 955 956 957 958
    gst_object_ref(_videoSink); // gst_bin_add() will steal one reference

    gst_bin_add(GST_BIN(_pipeline), _videoSink);

    if(!gst_element_link(_decoder, _videoSink)) {
        gst_bin_remove(GST_BIN(_pipeline), _videoSink);
        qCCritical(VideoReceiverLog) << "Unable to link video sink";
        if (caps != nullptr) {
            gst_caps_unref(caps);
            caps = nullptr;
959
        }
960 961
        return false;
    }
962

963
    gst_element_sync_state_with_parent(_videoSink);
964

965
    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-with-videosink");
966

967 968
    if (caps != nullptr) {
        GstStructure* s = gst_caps_get_structure(caps, 0);
969

970 971 972 973 974
        if (s != nullptr) {
            gint width, height;
            gst_structure_get_int(s, "width", &width);
            gst_structure_get_int(s, "height", &height);
            _setVideoSize(QSize(width, height));
975 976
        }

977 978 979 980 981
        gst_caps_unref(caps);
        caps = nullptr;
    } else {
        _setVideoSize(QSize(0, 0));
    }
982

983 984
    _decoding = true;
    emit decodingChanged();
Gus Grubba's avatar
Gus Grubba committed
985

986 987
    return true;
}
Gus Grubba's avatar
Gus Grubba committed
988

989 990 991 992 993
void
VideoReceiver::_noteTeeFrame(void)
{
    _lastSourceFrameTime = QDateTime::currentSecsSinceEpoch();
}
Gus Grubba's avatar
Gus Grubba committed
994

995 996 997 998 999
void
VideoReceiver::_noteVideoSinkFrame(void)
{
    _lastVideoFrameTime = QDateTime::currentSecsSinceEpoch();
}
Gus Grubba's avatar
Gus Grubba committed
1000

1001 1002 1003 1004 1005 1006 1007
void
VideoReceiver::_noteEndOfStream(void)
{
    if (_streaming) {
        _streaming = false;
    }
}
Gus Grubba's avatar
Gus Grubba committed
1008

1009 1010 1011 1012 1013 1014
// -Unlink the branch from the src pad
// -Send an EOS event at the beginning of that branch
void
VideoReceiver::_unlinkBranch(GstElement* from)
{
    GstPad* src;
Gus Grubba's avatar
Gus Grubba committed
1015

1016 1017 1018 1019
    if ((src = gst_element_get_static_pad(from, "src")) == nullptr) {
        qCCritical(VideoReceiverLog) << "gst_element_get_static_pad() failed";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
1020

1021
    GstPad* sink;
Gus Grubba's avatar
Gus Grubba committed
1022

1023 1024 1025 1026 1027 1028
    if ((sink = gst_pad_get_peer(src)) == nullptr) {
        gst_object_unref(src);
        src = nullptr;
        qCCritical(VideoReceiverLog) << "gst_pad_get_peer() failed";
        return;
    }
1029

1030 1031 1032 1033 1034 1035 1036 1037
    if (!gst_pad_unlink(src, sink)) {
        gst_object_unref(src);
        src = nullptr;
        gst_object_unref(sink);
        sink = nullptr;
        qCCritical(VideoReceiverLog) << "gst_pad_unlink() failed";
        return;
    }
1038

1039 1040
    gst_object_unref(src);
    src = nullptr;
1041

1042 1043
    // Send EOS at the beginning of the branch
    const gboolean ret = gst_pad_send_event(sink, gst_event_new_eos());
1044

1045 1046 1047 1048 1049
    gst_object_unref(sink);
    sink = nullptr;

    if (ret) {
        qCDebug(VideoReceiverLog) << "Branch EOS was sent";
1050
    } else {
1051
        qCCritical(VideoReceiverLog) << "Branch EOS was NOT sent";
Gus Grubba's avatar
Gus Grubba committed
1052 1053 1054
    }
}

1055
void
1056
VideoReceiver::_shutdownDecodingBranch(void)
Gus Grubba's avatar
Gus Grubba committed
1057
{
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    if (_decoder != nullptr) {
        GstObject* parent;

        if ((parent = gst_element_get_parent(_decoder)) != nullptr) {
            gst_bin_remove(GST_BIN(_pipeline), _decoder);
            gst_element_set_state(_decoder, GST_STATE_NULL);
            gst_object_unref(parent);
            parent = nullptr;
        }

        gst_object_unref(_decoder);
        _decoder = nullptr;
1070
    }
1071 1072 1073 1074 1075 1076 1077

    if (_videoSinkProbeId != 0) {
        GstPad* sinkpad;
        if ((sinkpad = gst_element_get_static_pad(_videoSink, "sink")) != nullptr) {
            gst_pad_remove_probe(sinkpad, _videoSinkProbeId);
            gst_object_unref(sinkpad);
            sinkpad = nullptr;
1078
        }
1079
        _videoSinkProbeId = 0;
Gus Grubba's avatar
Gus Grubba committed
1080
    }
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104

    _lastVideoFrameTime = 0;

    GstObject* parent;

    if ((parent = gst_element_get_parent(_videoSink)) != nullptr) {
        gst_bin_remove(GST_BIN(_pipeline), _videoSink);
        gst_element_set_state(_videoSink, GST_STATE_NULL);
        gst_object_unref(parent);
        parent = nullptr;
    }

    gst_object_unref(_videoSink);
    _videoSink = nullptr;

    _removingDecoder = false;

    if (_decoding) {
        _decoding = false;
        emit decodingChanged();
        qCDebug(VideoReceiverLog) << "Decoding stopped";
    }

    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-decoding-stopped");
Gus Grubba's avatar
Gus Grubba committed
1105 1106
}

1107
void
1108
VideoReceiver::_shutdownRecordingBranch(void)
Gus Grubba's avatar
Gus Grubba committed
1109
{
1110 1111 1112 1113
    gst_bin_remove(GST_BIN(_pipeline), _fileSink);
    gst_element_set_state(_fileSink, GST_STATE_NULL);
    gst_object_unref(_fileSink);
    _fileSink = nullptr;
Gus Grubba's avatar
Gus Grubba committed
1114

1115 1116 1117 1118 1119 1120
    _removingRecorder = false;

    if (_recording) {
        _recording = false;
        emit recordingChanged();
        qCDebug(VideoReceiverLog) << "Recording stopped";
1121
    }
1122 1123

    GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(_pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline-recording-stopped");
1124 1125
}

1126 1127 1128 1129
bool
VideoReceiver::_isOurThread(void)
{
    return QThread::currentThread() == (QThread*)this;
1130 1131
}

1132
void
1133 1134 1135 1136 1137
VideoReceiver::_post(Task t)
{
    QMutexLocker lock(&_taskQueueSync);
    _taskQueue.enqueue(t);
    _taskQueueUpdate.wakeOne();
Gus Grubba's avatar
Gus Grubba committed
1138 1139
}

1140
void
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
VideoReceiver::run(void)
{
    while(!_shutdown) {
        _taskQueueSync.lock();

        while (_taskQueue.isEmpty()) {
            _taskQueueUpdate.wait(&_taskQueueSync);
        }

        Task t = _taskQueue.dequeue();

        _taskQueueSync.unlock();

        t();
1155
    }
1156 1157
}

1158 1159
gboolean
VideoReceiver::_onBusMessage(GstBus* bus, GstMessage* msg, gpointer data)
Gus Grubba's avatar
Gus Grubba committed
1160 1161
{
    Q_UNUSED(bus)
Gus Grubba's avatar
Gus Grubba committed
1162
    Q_ASSERT(msg != nullptr && data != nullptr);
Gus Grubba's avatar
Gus Grubba committed
1163
    VideoReceiver* pThis = (VideoReceiver*)data;
1164

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    switch (GST_MESSAGE_TYPE(msg)) {
    case GST_MESSAGE_ERROR:
        do {
            gchar* debug;
            GError* error;

            gst_message_parse_error(msg, &error, &debug);

            if (debug != nullptr) {
                g_free(debug);
                debug = nullptr;
            }

            if (error != nullptr) {
                qCCritical(VideoReceiverLog) << error->message;
                g_error_free(error);
                error = nullptr;
            }

            pThis->_post([pThis](){
                pThis->stop();
            });
        } while(0);
1188
        break;
1189 1190 1191 1192
    case GST_MESSAGE_EOS:
        pThis->_post([pThis](){
            pThis->_handleEOS();
        });
1193
        break;
1194 1195 1196 1197 1198 1199
    case GST_MESSAGE_ELEMENT:
        do {
            const GstStructure* s = gst_message_get_structure (msg);

            if (!gst_structure_has_name (s, "GstBinForwarded")) {
                break;
1200
            }
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218

            GstMessage* forward_msg = nullptr;

            gst_structure_get(s, "message", GST_TYPE_MESSAGE, &forward_msg, NULL);

            if (forward_msg == nullptr) {
                break;
            }

            if (GST_MESSAGE_TYPE(forward_msg) == GST_MESSAGE_EOS) {
                pThis->_post([pThis](){
                    pThis->_handleEOS();
                });
            }

            gst_message_unref(forward_msg);
            forward_msg = nullptr;
        } while(0);
1219
        break;
1220 1221 1222 1223
    default:
        break;
    }

Gus Grubba's avatar
Gus Grubba committed
1224 1225
    return TRUE;
}
1226

1227
void
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
VideoReceiver::_onNewPad(GstElement* element, GstPad* pad, gpointer data)
{
    VideoReceiver* self = static_cast<VideoReceiver*>(data);

    if (element == self->_source) {
        self->_onNewSourcePad(pad);
    } else if (element == self->_decoder) {
        self->_onNewDecoderPad(pad);
    } else {
        qCDebug(VideoReceiverLog) << "Unexpected call!";
    }
}

void
VideoReceiver::_wrapWithGhostPad(GstElement* element, GstPad* pad, gpointer data)
1243
{
1244 1245 1246 1247
    gchar* name;

    if ((name = gst_pad_get_name(pad)) == nullptr) {
        qCCritical(VideoReceiverLog) << "gst_pad_get_name() failed";
1248 1249 1250
        return;
    }

1251 1252 1253 1254 1255 1256 1257
    GstPad* ghostpad;

    if ((ghostpad = gst_ghost_pad_new(name, pad)) == nullptr) {
        qCCritical(VideoReceiverLog) << "gst_ghost_pad_new() failed";
        g_free(name);
        name = nullptr;
        return;
1258 1259
    }

1260 1261
    g_free(name);
    name = nullptr;
1262

1263
    gst_pad_set_active(ghostpad, TRUE);
1264

1265 1266
    if (!gst_element_add_pad(GST_ELEMENT_PARENT(element), ghostpad)) {
        qCCritical(VideoReceiverLog) << "gst_element_add_pad() failed";
1267 1268 1269
    }
}

1270 1271
void
VideoReceiver::_linkPadWithOptionalBuffer(GstElement* element, GstPad* pad, gpointer data)
1272
{
1273
    bool isRtpPad = false;
1274

1275
    GstCaps* filter;
1276

1277 1278
    if ((filter = gst_caps_from_string("application/x-rtp")) != nullptr) {
        GstCaps* caps = gst_pad_query_caps(pad, nullptr);
1279

1280 1281 1282 1283 1284 1285
        if (caps != nullptr) {
            if (!gst_caps_is_any(caps) && gst_caps_can_intersect(caps, filter)) {
                isRtpPad = true;
            }
            gst_caps_unref(caps);
            caps = nullptr;
1286 1287
        }

1288 1289 1290
        gst_caps_unref(filter);
        filter = nullptr;
    }
1291

1292 1293
    if (isRtpPad) {
        GstElement* buffer;
1294

1295 1296
        if ((buffer = gst_element_factory_make("rtpjitterbuffer", nullptr)) != nullptr) {
            gst_bin_add(GST_BIN(GST_ELEMENT_PARENT(element)), buffer);
1297

1298
            gst_element_sync_state_with_parent(buffer);
1299

1300
            GstPad* sinkpad = gst_element_get_static_pad(buffer, "sink");
1301

1302 1303
            if (sinkpad != nullptr) {
                const GstPadLinkReturn ret = gst_pad_link(pad, sinkpad);
1304

1305 1306
                gst_object_unref(sinkpad);
                sinkpad = nullptr;
1307

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
                if (ret == GST_PAD_LINK_OK) {
                    pad = gst_element_get_static_pad(buffer, "src");
                    element = buffer;
                } else {
                    qCDebug(VideoReceiverLog) << "Partially failed - gst_pad_link()";
                }
            } else {
                qCDebug(VideoReceiverLog) << "Partially failed - gst_element_get_static_pad()";
            }
        } else {
            qCDebug(VideoReceiverLog) << "Partially failed - gst_element_factory_make('rtpjitterbuffer')";
1319
        }
1320
    }
1321

1322
    gchar* name;
1323

1324 1325 1326
    if ((name = gst_pad_get_name(pad)) != nullptr) {
        if(gst_element_link_pads(element, name, GST_ELEMENT(data), "sink") == false) {
            qCCritical(VideoReceiverLog) << "gst_element_link_pads() failed";
1327 1328
        }

1329 1330 1331 1332
        g_free(name);
        name = nullptr;
    } else {
        qCCritical(VideoReceiverLog) << "gst_pad_get_name() failed";
1333 1334 1335
    }
}

1336 1337
gboolean
VideoReceiver::_padProbe(GstElement* element, GstPad* pad, gpointer user_data)
1338
{
1339
    int* probeRes = (int*)user_data;
1340

1341
    *probeRes |= 1;
1342

1343
    GstCaps* filter = gst_caps_from_string("application/x-rtp");
1344

1345 1346
    if (filter != nullptr) {
        GstCaps* caps = gst_pad_query_caps(pad, nullptr);
1347

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
        if (caps != nullptr) {
            if (!gst_caps_is_any(caps) && gst_caps_can_intersect(caps, filter)) {
                *probeRes |= 2;
            }

            gst_caps_unref(caps);
            caps = nullptr;
        }

        gst_caps_unref(filter);
        filter = nullptr;
    }
1360

1361 1362
    return TRUE;
}
1363

1364 1365 1366 1367
gboolean
VideoReceiver::_autoplugQueryCaps(GstElement* bin, GstPad* pad, GstElement* element, GstQuery* query, gpointer data)
{
    GstElement* glupload = (GstElement* )data;
1368

1369
    GstPad* sinkpad;
1370

1371 1372 1373
    if ((sinkpad = gst_element_get_static_pad(glupload, "sink")) == nullptr) {
        qCCritical(VideoReceiverLog) << "No sink pad found";
        return FALSE;
1374
    }
1375

1376
    GstCaps* filter;
1377

1378
    gst_query_parse_caps(query, &filter);
1379

1380
    GstCaps* sinkcaps = gst_pad_query_caps(sinkpad, filter);
1381

1382
    gst_query_set_caps_result(query, sinkcaps);
1383

1384
    const gboolean ret = !gst_caps_is_empty(sinkcaps);
1385

1386 1387
    gst_caps_unref(sinkcaps);
    sinkcaps = nullptr;
1388

1389 1390
    gst_object_unref(sinkpad);
    sinkpad = nullptr;
1391

1392
    return ret;
1393 1394
}

1395 1396
gboolean
VideoReceiver::_autoplugQueryContext(GstElement* bin, GstPad* pad, GstElement* element, GstQuery* query, gpointer data)
1397
{
1398
    GstElement* glsink = (GstElement* )data;
1399

1400
    GstPad* sinkpad;
1401

1402 1403 1404 1405
    if ((sinkpad = gst_element_get_static_pad(glsink, "sink")) == nullptr){
        qCCritical(VideoReceiverLog) << "No sink pad found";
        return FALSE;
    }
1406

1407
    const gboolean ret = gst_pad_query(sinkpad, query);
1408

1409 1410
    gst_object_unref(sinkpad);
    sinkpad = nullptr;
1411

1412
    return ret;
1413 1414
}

1415 1416
gboolean
VideoReceiver::_autoplugQuery(GstElement* bin, GstPad* pad, GstElement* element, GstQuery* query, gpointer data)
1417
{
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
    gboolean ret;

    switch (GST_QUERY_TYPE(query)) {
    case GST_QUERY_CAPS:
        ret = _autoplugQueryCaps(bin, pad, element, query, data);
        break;
    case GST_QUERY_CONTEXT:
        ret = _autoplugQueryContext(bin, pad, element, query, data);
        break;
    default:
        ret = FALSE;
        break;
    }

    return ret;
1433 1434
}

1435
GstPadProbeReturn
1436
VideoReceiver::_teeProbe(GstPad* pad, GstPadProbeInfo* info, gpointer user_data)
1437 1438
{
    Q_UNUSED(pad);
1439 1440 1441
    Q_UNUSED(info)

    if(user_data != nullptr) {
Gus Grubba's avatar
Gus Grubba committed
1442
        VideoReceiver* pThis = static_cast<VideoReceiver*>(user_data);
1443
        pThis->_noteTeeFrame();
1444
    }
1445 1446

    return GST_PAD_PROBE_OK;
1447
}
1448

1449 1450 1451
GstPadProbeReturn
VideoReceiver::_videoSinkProbe(GstPad* pad, GstPadProbeInfo* info, gpointer user_data)
{
1452
    if(user_data != nullptr) {
1453
        VideoReceiver* pThis = static_cast<VideoReceiver*>(user_data);
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481

        if (pThis->_resetVideoSink) {
            pThis->_resetVideoSink = false;

// FIXME: AV: this makes MPEG2-TS playing smooth but breaks RTSP
//            gst_pad_send_event(pad, gst_event_new_flush_start());
//            gst_pad_send_event(pad, gst_event_new_flush_stop(TRUE));

//            GstBuffer* buf;

//            if ((buf = gst_pad_probe_info_get_buffer(info)) != nullptr) {
//                GstSegment* seg;

//                if ((seg = gst_segment_new()) != nullptr) {
//                    gst_segment_init(seg, GST_FORMAT_TIME);

//                    seg->start = buf->pts;

//                    gst_pad_send_event(pad, gst_event_new_segment(seg));

//                    gst_segment_free(seg);
//                    seg = nullptr;
//                }

//                gst_pad_set_offset(pad, -static_cast<gint64>(buf->pts));
//            }
        }

1482 1483 1484 1485 1486 1487
        pThis->_noteVideoSinkFrame();
    }

    return GST_PAD_PROBE_OK;
}

1488
GstPadProbeReturn
1489
VideoReceiver::_eosProbe(GstPad* pad, GstPadProbeInfo* info, gpointer user_data)
1490 1491
{
    Q_UNUSED(pad);
1492
    Q_ASSERT(user_data != nullptr);
1493

1494 1495
    if(info != nullptr) {
        GstEvent* event = gst_pad_probe_info_get_event(info);
1496

1497 1498 1499
        if (GST_EVENT_TYPE(event) == GST_EVENT_EOS) {
            VideoReceiver* pThis = static_cast<VideoReceiver*>(user_data);
            pThis->_noteEndOfStream();
1500 1501 1502
        }
    }

1503
    return GST_PAD_PROBE_OK;
1504 1505
}

1506 1507
GstPadProbeReturn
VideoReceiver::_keyframeWatch(GstPad* pad, GstPadProbeInfo* info, gpointer user_data)
1508
{
1509 1510 1511
    if (info == nullptr || user_data == nullptr) {
        qCCritical(VideoReceiverLog) << "Invalid arguments";
        return GST_PAD_PROBE_DROP;
1512 1513
    }

1514 1515 1516 1517
    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;
1518 1519
    }

1520 1521
    // set media file '0' offset to current timeline position - we don't want to touch other elements in the graph, except these which are downstream!
    gst_pad_set_offset(pad, -static_cast<gint64>(buf->pts));
1522

1523 1524 1525
    VideoReceiver* pThis = static_cast<VideoReceiver*>(user_data);

    qCDebug(VideoReceiverLog) << "Got keyframe, stop dropping buffers";
1526

1527 1528 1529 1530 1531
    pThis->recordingStarted();

    return GST_PAD_PROBE_REMOVE;
}
#endif