video_rtp_session.cpp 20.2 KB
Newer Older
1
/*
Guillaume Roguez's avatar
Guillaume Roguez committed
2
 *  Copyright (C) 2004-2018 Savoir-faire Linux Inc.
Guillaume Roguez's avatar
Guillaume Roguez committed
3
 *
4
 *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
5
 *  Author: Guillaume Roguez <Guillaume.Roguez@savoirfairelinux.com>
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
19
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
20 21
 */

22
#include "client/videomanager.h"
23
#include "video_rtp_session.h"
24
#include "video_sender.h"
25
#include "video_receive_thread.h"
26
#include "video_mixer.h"
27
#include "ice_socket.h"
28
#include "socket_pair.h"
Guillaume Roguez's avatar
Guillaume Roguez committed
29
#include "sip/sipvoiplink.h" // for enqueueKeyframeRequest
30
#include "manager.h"
Tristan Matthews's avatar
Tristan Matthews committed
31
#include "logger.h"
32 33
#include "string_utils.h"
#include "call.h"
34
#include "conference.h"
35 36

#include "account_const.h"
37

38 39 40
#include <sstream>
#include <map>
#include <string>
41 42
#include <thread>
#include <chrono>
43

Adrien Béraud's avatar
Adrien Béraud committed
44
namespace ring { namespace video {
45

46 47 48
using std::map;
using std::string;

49 50
constexpr static auto NEWPARAMS_TIMEOUT = std::chrono::milliseconds(1000);

Philippe Gorley's avatar
Philippe Gorley committed
51 52 53
// how long (in seconds) to wait before rechecking for packet loss
static constexpr auto RTCP_PACKET_LOSS_INTERVAL = std::chrono::milliseconds(1000);

54
VideoRtpSession::VideoRtpSession(const string &callID,
Guillaume Roguez's avatar
Guillaume Roguez committed
55 56
                                 const DeviceParams& localVideoParams) :
    RtpSession(callID), localVideoParams_(localVideoParams)
57 58
    , lastRTCPCheck_(std::chrono::system_clock::now())
    , lastLongRTCPCheck_(std::chrono::system_clock::now())
59 60
    , videoBitrateInfo_ {}
    , rtcpCheckerThread_([] { return true; },
61 62
            [this]{ processRtcpChecker(); },
            []{})
Philippe Gorley's avatar
Philippe Gorley committed
63 64
    , packetLossThread_([] { return true; },
            [this]{ processPacketLoss(); },
65
            []{})
66 67 68
{
    setupVideoBitrateInfo(); // reset bitrate
}
69

70
VideoRtpSession::~VideoRtpSession()
71
{ stop(); }
72

73 74 75 76 77 78 79 80 81
/// Setup internal VideoBitrateInfo structure from media descriptors.
///
void
VideoRtpSession::updateMedia(const MediaDescription& send, const MediaDescription& receive)
{
    BaseType::updateMedia(send, receive);
    setupVideoBitrateInfo();
}

82
void VideoRtpSession::startSender()
83
{
84
    if (send_.enabled and not send_.holding) {
85 86 87 88 89
        if (sender_) {
            if (videoLocal_)
                videoLocal_->detach(sender_.get());
            if (videoMixer_)
                videoMixer_->detach(sender_.get());
Adrien Béraud's avatar
Adrien Béraud committed
90
            RING_WARN("Restarting video sender");
91
        }
92

93 94
        if (not conference_) {
            videoLocal_ = getVideoCamera();
95
            if (auto input = Manager::instance().getVideoManager().videoInput.lock()) {
96
                auto newParams = input->switchInput(input_);
97 98 99 100
                try {
                    if (newParams.valid() &&
                        newParams.wait_for(NEWPARAMS_TIMEOUT) == std::future_status::ready)
                        localVideoParams_ = newParams.get();
101
                    else {
102
                        RING_ERR("No valid new video parameters.");
103 104
                        return;
                    }
105
                } catch (const std::exception& e) {
aviau's avatar
aviau committed
106
                    RING_ERR("Exception during retrieving video parameters: %s",
107
                             e.what());
108
                    return;
109
                }
110 111
            } else {
                RING_WARN("Can't lock video input");
112
                return;
113 114 115
            }
        }

116 117 118 119 120

        // be sure to not send any packets before saving last RTP seq value
        socketPair_->stopSendOp();
        if (sender_)
            initSeqVal_ = sender_->getLastSeqValue() + 1;
121
        try {
122 123 124
            sender_.reset();
            socketPair_->stopSendOp(false);
            sender_.reset(new VideoSender(getRemoteRtpUri(), localVideoParams_,
125
                                          send_, *socketPair_, initSeqVal_, mtu_));
126
        } catch (const MediaEncoderException &e) {
Adrien Béraud's avatar
Adrien Béraud committed
127
            RING_ERR("%s", e.what());
128
            send_.enabled = false;
129
        }
130
        auto codecVideo = std::static_pointer_cast<ring::AccountVideoCodecInfo>(send_.codec);
131 132
        auto autoQuality = codecVideo->isAutoQualityEnabled;
        if (autoQuality and not rtcpCheckerThread_.isRunning())
133
            rtcpCheckerThread_.start();
134
        else if (not autoQuality and rtcpCheckerThread_.isRunning())
135
            rtcpCheckerThread_.join();
136
    }
137 138
}

139 140
void
VideoRtpSession::restartSender()
Éloi Bail's avatar
Éloi Bail committed
141
{
142 143
    std::lock_guard<std::recursive_mutex> lock(mutex_);

144 145 146 147
    // ensure that start has been called before restart
    if (not socketPair_)
        return;

148
    startSender();
149
    setupVideoPipeline();
Éloi Bail's avatar
Éloi Bail committed
150 151
}

152 153
void VideoRtpSession::startReceiver()
{
154
    if (receive_.enabled and not receive_.holding) {
155
        if (receiveThread_)
156
            RING_WARN("Restarting video receiver");
Guillaume Roguez's avatar
Guillaume Roguez committed
157
        receiveThread_.reset(
158
            new VideoReceiveThread(callID_, receive_.receiving_sdp, mtu_)
Guillaume Roguez's avatar
Guillaume Roguez committed
159
        );
160

161
        // XXX keyframe requests can timeout if unanswered
162
        receiveThread_->setRequestKeyFrameCallback(&SIPVoIPLink::enqueueKeyframeRequest);
Philippe Gorley's avatar
Philippe Gorley committed
163
        receiveThread_->addIOContext(*socketPair_);
164
        receiveThread_->startLoop();
Philippe Gorley's avatar
Philippe Gorley committed
165
        packetLossThread_.start();
166
    } else {
Adrien Béraud's avatar
Adrien Béraud committed
167
        RING_DBG("Video receiving disabled");
168
        if (receiveThread_)
169
            receiveThread_->detach(videoMixer_.get());
170
        receiveThread_.reset();
Philippe Gorley's avatar
Philippe Gorley committed
171
        packetLossThread_.join();
172
    }
173
}
174

Guillaume Roguez's avatar
Guillaume Roguez committed
175 176
void VideoRtpSession::start(std::unique_ptr<IceSocket> rtp_sock,
                            std::unique_ptr<IceSocket> rtcp_sock)
177 178 179
{
    std::lock_guard<std::recursive_mutex> lock(mutex_);

180
    if (not send_.enabled and not receive_.enabled) {
181 182 183 184
        stop();
        return;
    }

185
    try {
186 187 188 189 190
        if (rtp_sock and rtcp_sock)
            socketPair_.reset(new SocketPair(std::move(rtp_sock), std::move(rtcp_sock)));
        else
            socketPair_.reset(new SocketPair(getRemoteRtpUri().c_str(), receive_.addr.getPort()));

191 192 193 194 195 196
        if (send_.crypto and receive_.crypto) {
            socketPair_->createSRTP(receive_.crypto.getCryptoSuite().c_str(),
                                    receive_.crypto.getSrtpKeyInfo().c_str(),
                                    send_.crypto.getCryptoSuite().c_str(),
                                    send_.crypto.getSrtpKeyInfo().c_str());
        }
197 198
    } catch (const std::runtime_error& e) {
        RING_ERR("Socket creation failed: %s", e.what());
199 200
        return;
    }
201 202 203 204

    startSender();
    startReceiver();

205
    setupVideoPipeline();
206 207
}

208
void VideoRtpSession::stop()
209
{
210
    std::lock_guard<std::recursive_mutex> lock(mutex_);
211
    rtcpCheckerThread_.join();
Philippe Gorley's avatar
Philippe Gorley committed
212
    packetLossThread_.join();
213 214 215 216 217
    if (videoLocal_)
        videoLocal_->detach(sender_.get());

    if (videoMixer_) {
        videoMixer_->detach(sender_.get());
218
        if (receiveThread_)
219
            receiveThread_->detach(videoMixer_.get());
220
    }
221

222
    if (socketPair_)
223
        socketPair_->interrupt();
224

225 226 227 228 229 230 231
    // reset default video quality if exist
    if (videoBitrateInfo_.videoQualityCurrent != SystemCodecInfo::DEFAULT_NO_QUALITY)
        videoBitrateInfo_.videoQualityCurrent = SystemCodecInfo::DEFAULT_CODEC_QUALITY;

    videoBitrateInfo_.videoBitrateCurrent = SystemCodecInfo::DEFAULT_VIDEO_BITRATE;
    storeVideoBitrateInfo();

232
    receiveThread_.reset();
233
    sender_.reset();
234
    socketPair_.reset();
235
    videoLocal_.reset();
236
}
237

238 239
void VideoRtpSession::forceKeyFrame()
{
240
    std::lock_guard<std::recursive_mutex> lock(mutex_);
241
    if (sender_)
242
        sender_->forceKeyFrame();
243 244
}

245 246 247 248 249 250 251 252 253 254 255 256 257
void
VideoRtpSession::setupVideoPipeline()
{
    if (conference_)
        setupConferenceVideoPipeline(*conference_);
    else if (sender_) {
        if (videoLocal_)
            videoLocal_->attach(sender_.get());
    } else {
        videoLocal_.reset();
    }
}

258 259
void
VideoRtpSession::setupConferenceVideoPipeline(Conference& conference)
260
{
261 262 263
    RING_DBG("[call:%s] Setup video pipeline on conference %s", callID_.c_str(),
             conference.getConfID().c_str());
    videoMixer_ = conference.getVideoMixer();
264 265

    if (sender_) {
266 267 268 269
        // Swap sender from local video to conference video mixer
        if (videoLocal_)
            videoLocal_->detach(sender_.get());
        videoMixer_->attach(sender_.get());
270 271
    } else
        RING_WARN("[call:%s] no sender", callID_.c_str());
272 273 274

    if (receiveThread_) {
        receiveThread_->enterConference();
275
        receiveThread_->attach(videoMixer_.get());
276 277
    } else
        RING_WARN("[call:%s] no receiver", callID_.c_str());
278
}
279

280 281
void
VideoRtpSession::enterConference(Conference* conference)
282
{
283
    std::lock_guard<std::recursive_mutex> lock(mutex_);
284 285 286

    exitConference();

287
    conference_ = conference;
288 289
    RING_DBG("[call:%s] enterConference (conf: %s)", callID_.c_str(),
             conference->getConfID().c_str());
Guillaume Roguez's avatar
Guillaume Roguez committed
290

291 292 293
    if (send_.enabled or receiveThread_) {
        videoMixer_ = conference->getVideoMixer();
        videoMixer_->setDimensions(localVideoParams_.width, localVideoParams_.height);
294
        setupConferenceVideoPipeline(*conference_);
295
    }
296 297 298 299
}

void VideoRtpSession::exitConference()
{
300
    std::lock_guard<std::recursive_mutex> lock(mutex_);
301

302 303 304
    if (!conference_)
        return;

305 306
    RING_DBG("[call:%s] exitConference (conf: %s)", callID_.c_str(),
             conference_->getConfID().c_str());
307 308

    if (videoMixer_) {
309
        if (sender_)
310
            videoMixer_->detach(sender_.get());
311 312

        if (receiveThread_) {
313
            receiveThread_->detach(videoMixer_.get());
314 315 316
            receiveThread_->exitConference();
        }

317
        videoMixer_.reset();
318 319
    }

320 321 322
    if (videoLocal_)
        videoLocal_->attach(sender_.get());

323
    conference_ = nullptr;
324 325
}

326 327
bool
VideoRtpSession::useCodec(const ring::AccountVideoCodecInfo* codec) const
Éloi Bail's avatar
Éloi Bail committed
328
{
329
    return sender_->useCodec(codec);
Éloi Bail's avatar
Éloi Bail committed
330 331
}

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

float
VideoRtpSession::checkPeerPacketLoss()
{
    auto rtcpInfoVect = socketPair_->getRtcpInfo();
    unsigned totalLost = 0;
    unsigned fract = 0;
    auto vectSize = rtcpInfoVect.size();

    for (const auto& it : rtcpInfoVect) {
        fract = (ntohl(it.fraction_lost) & 0xff000000)  >> 24;
        totalLost += fract;
    }

    if (vectSize != 0)
        return (float)( 100 * totalLost) / (256.0 * vectSize);
    else
        return NO_PACKET_LOSS_CALCULATED;
}

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
unsigned
VideoRtpSession::getLowerQuality()
{
    // if lower quality was stored we return it
    unsigned quality = videoBitrateInfo_.videoQualityCurrent;
    while ( not histoQuality_.empty()) {
        quality = histoQuality_.back();
        histoQuality_.pop_back();
        if (quality > videoBitrateInfo_.videoQualityCurrent)
            return quality;
    }

    // if no appropriate quality found, calculate it with dichotomie
    quality = (videoBitrateInfo_.videoQualityCurrent + videoBitrateInfo_.videoQualityMin) / 2;
    return quality;
}

unsigned
VideoRtpSession::getLowerBitrate()
{
    // if a lower bitrate was stored we return it
    unsigned bitrate = videoBitrateInfo_.videoBitrateCurrent;
    while ( not histoBitrate_.empty()) {
        bitrate = histoBitrate_.back();
        histoBitrate_.pop_back();
        if (bitrate < videoBitrateInfo_.videoBitrateCurrent)
            return bitrate;
    }

    // if no appropriate bitrate found, calculate it with dichotomie
    bitrate = (videoBitrateInfo_.videoBitrateCurrent + videoBitrateInfo_.videoBitrateMin) / 2;
    return bitrate;
}

386
void
387
VideoRtpSession::adaptQualityAndBitrate()
388
{
389
    bool needToCheckQuality = false;
390 391 392 393 394 395 396
    bool mediaRestartNeeded = false;
    float packetLostRate = 0.0;

    auto rtcpCheckTimer = std::chrono::duration_cast<std::chrono::seconds> (std::chrono::system_clock::now() - lastRTCPCheck_);
    auto rtcpLongCheckTimer = std::chrono::duration_cast<std::chrono::seconds> (std::chrono::system_clock::now() - lastLongRTCPCheck_);

    if (rtcpCheckTimer.count() >= RTCP_CHECKING_INTERVAL) {
397
        needToCheckQuality = true;
398 399 400 401
        lastRTCPCheck_ = std::chrono::system_clock::now();
    }

    if (rtcpLongCheckTimer.count() >= RTCP_LONG_CHECKING_INTERVAL) {
402
        needToCheckQuality = true;
403
        hasReachMaxQuality_ = false;
404
        lastLongRTCPCheck_ = std::chrono::system_clock::now();
405
        // we force iterative bitrate adaptation
406 407 408 409
        videoBitrateInfo_.cptBitrateChecking = 0;
    }


410 411
    if (needToCheckQuality) {

412 413
        videoBitrateInfo_.cptBitrateChecking++;

414
        // packetLostRate is not already available. Do nothing
415
        if ((packetLostRate = checkPeerPacketLoss()) == NO_PACKET_LOSS_CALCULATED) {
416
            // we force iterative bitrate adaptation
417 418
            videoBitrateInfo_.cptBitrateChecking = 0;

419
        // too much packet lost : decrease quality and bitrate
420 421
        } else if (packetLostRate >= videoBitrateInfo_.packetLostThreshold) {

422 423 424 425 426 427 428 429 430
            // calculate new quality by dichotomie
            videoBitrateInfo_.videoQualityCurrent = getLowerQuality();

            // calculate new bitrate by dichotomie
            videoBitrateInfo_.videoBitrateCurrent =  getLowerBitrate();

            // boundaries low
            if (videoBitrateInfo_.videoQualityCurrent > videoBitrateInfo_.videoQualityMin)
                videoBitrateInfo_.videoQualityCurrent = videoBitrateInfo_.videoQualityMin;
431 432 433 434

            if (videoBitrateInfo_.videoBitrateCurrent < videoBitrateInfo_.videoBitrateMin)
                videoBitrateInfo_.videoBitrateCurrent = videoBitrateInfo_.videoBitrateMin;

435 436

            // we force iterative bitrate and quality adaptation
437 438
            videoBitrateInfo_.cptBitrateChecking = 0;

439 440 441 442 443
            // asynchronous A/V media restart
            // we give priority to quality
            if (((videoBitrateInfo_.videoQualityCurrent != SystemCodecInfo::DEFAULT_NO_QUALITY) &&
                    (videoBitrateInfo_.videoQualityCurrent !=  (histoQuality_.empty() ? 0 : histoQuality_.back()))) ||
                ((videoBitrateInfo_.videoQualityCurrent == SystemCodecInfo::DEFAULT_NO_QUALITY) &&
444
                    (videoBitrateInfo_.videoBitrateCurrent !=  (histoBitrate_.empty() ? 0 : histoBitrate_.back())))) {
445
                mediaRestartNeeded = true;
446 447
                hasReachMaxQuality_ = true;
            }
448

449 450

        // no packet lost: increase quality and bitrate
451 452
        } else if ((videoBitrateInfo_.cptBitrateChecking <= videoBitrateInfo_.maxBitrateChecking)
                   and not hasReachMaxQuality_) {
453

454 455 456 457 458
            // calculate new quality by dichotomie
            videoBitrateInfo_.videoQualityCurrent =
                (videoBitrateInfo_.videoQualityCurrent + videoBitrateInfo_.videoQualityMax) / 2;

            // calculate new bitrate by dichotomie
459 460 461
            videoBitrateInfo_.videoBitrateCurrent =
                ( videoBitrateInfo_.videoBitrateCurrent + videoBitrateInfo_.videoBitrateMax) / 2;

462 463 464 465
            // boundaries high
            if (videoBitrateInfo_.videoQualityCurrent < videoBitrateInfo_.videoQualityMax)
                videoBitrateInfo_.videoQualityCurrent = videoBitrateInfo_.videoQualityMax;

466 467 468
            if (videoBitrateInfo_.videoBitrateCurrent > videoBitrateInfo_.videoBitrateMax)
                videoBitrateInfo_.videoBitrateCurrent = videoBitrateInfo_.videoBitrateMax;

469 470 471 472 473 474
            // asynchronous A/V media restart
            // we give priority to quality
            if (((videoBitrateInfo_.videoQualityCurrent != SystemCodecInfo::DEFAULT_NO_QUALITY) &&
                    (videoBitrateInfo_.videoQualityCurrent !=  (histoQuality_.empty() ? 0 : histoQuality_.back()))) ||
                ((videoBitrateInfo_.videoQualityCurrent == SystemCodecInfo::DEFAULT_NO_QUALITY) &&
                    (videoBitrateInfo_.videoBitrateCurrent !=  (histoBitrate_.empty() ? 0 : histoBitrate_.back()))))
475 476 477 478 479 480
                mediaRestartNeeded = true;

            if (videoBitrateInfo_.cptBitrateChecking == videoBitrateInfo_.maxBitrateChecking)
                lastLongRTCPCheck_ = std::chrono::system_clock::now();

        } else {
481
            // nothing we reach maximal tries
482 483 484 485 486 487
        }
    }

    if (mediaRestartNeeded) {
        storeVideoBitrateInfo();
        const auto& cid = callID_;
Éloi Bail's avatar
Éloi Bail committed
488

489
        RING_WARN("[%u/%u] packetLostRate=%f -> change quality to %d bitrate to %d",
Éloi Bail's avatar
Éloi Bail committed
490 491 492
                videoBitrateInfo_.cptBitrateChecking,
                videoBitrateInfo_.maxBitrateChecking,
                packetLostRate,
493
                videoBitrateInfo_.videoQualityCurrent,
Éloi Bail's avatar
Éloi Bail committed
494 495
                videoBitrateInfo_.videoBitrateCurrent);

496 497 498 499 500 501
        runOnMainThread([cid]{
            if (auto call = Manager::instance().callFactory.getCall(cid))
                call->restartMediaSender();
            });
    }
}
502

503
void
504
VideoRtpSession::setupVideoBitrateInfo() {
505 506 507
    auto codecVideo = std::static_pointer_cast<ring::AccountVideoCodecInfo>(send_.codec);
    if (codecVideo) {
        videoBitrateInfo_ = {
508 509 510
            (unsigned)(ring::stoi(codecVideo->getCodecSpecifications()[DRing::Account::ConfProperties::CodecInfo::BITRATE])),
            (unsigned)(ring::stoi(codecVideo->getCodecSpecifications()[DRing::Account::ConfProperties::CodecInfo::MIN_BITRATE])),
            (unsigned)(ring::stoi(codecVideo->getCodecSpecifications()[DRing::Account::ConfProperties::CodecInfo::MAX_BITRATE])),
511 512 513
            (unsigned)(ring::stoi(codecVideo->getCodecSpecifications()[DRing::Account::ConfProperties::CodecInfo::QUALITY])),
            (unsigned)(ring::stoi(codecVideo->getCodecSpecifications()[DRing::Account::ConfProperties::CodecInfo::MIN_QUALITY])),
            (unsigned)(ring::stoi(codecVideo->getCodecSpecifications()[DRing::Account::ConfProperties::CodecInfo::MAX_QUALITY])),
514 515 516 517 518
            videoBitrateInfo_.cptBitrateChecking,
            videoBitrateInfo_.maxBitrateChecking,
            videoBitrateInfo_.packetLostThreshold,
        };
    } else {
519 520 521
        videoBitrateInfo_ = {0, 0, 0, 0, 0, 0, 0,
                             MAX_ADAPTATIVE_BITRATE_ITERATION,
                             PACKET_LOSS_THRESHOLD};
522 523 524 525 526 527 528 529 530 531 532
    }
}

void
VideoRtpSession::storeVideoBitrateInfo() {
    auto codecVideo = std::static_pointer_cast<ring::AccountVideoCodecInfo>(send_.codec);

    if (codecVideo) {
        codecVideo->setCodecSpecifications({
            {DRing::Account::ConfProperties::CodecInfo::BITRATE, ring::to_string(videoBitrateInfo_.videoBitrateCurrent)},
            {DRing::Account::ConfProperties::CodecInfo::MIN_BITRATE, ring::to_string(videoBitrateInfo_.videoBitrateMin)},
533 534 535 536
            {DRing::Account::ConfProperties::CodecInfo::MAX_BITRATE, ring::to_string(videoBitrateInfo_.videoBitrateMax)},
            {DRing::Account::ConfProperties::CodecInfo::QUALITY, ring::to_string(videoBitrateInfo_.videoQualityCurrent)},
            {DRing::Account::ConfProperties::CodecInfo::MIN_QUALITY, ring::to_string(videoBitrateInfo_.videoQualityMin)},
            {DRing::Account::ConfProperties::CodecInfo::MAX_QUALITY, ring::to_string(videoBitrateInfo_.videoQualityMax)}
537
        });
538 539 540 541 542 543 544 545 546 547

        if (histoQuality_.size() > MAX_SIZE_HISTO_QUALITY_)
            histoQuality_.pop_front();

        if (histoBitrate_.size() > MAX_SIZE_HISTO_BITRATE_)
            histoBitrate_.pop_front();

        histoQuality_.push_back(videoBitrateInfo_.videoQualityCurrent);
        histoBitrate_.push_back(videoBitrateInfo_.videoBitrateCurrent);

548 549 550 551 552 553
    }
}

void
VideoRtpSession::processRtcpChecker()
{
554
    adaptQualityAndBitrate();
555 556 557
    rtcpCheckerThread_.wait_for(std::chrono::seconds(RTCP_CHECKING_INTERVAL));
}

Philippe Gorley's avatar
Philippe Gorley committed
558 559 560 561 562 563 564 565 566
void
VideoRtpSession::processPacketLoss()
{
    if (packetLossThread_.wait_for(RTCP_PACKET_LOSS_INTERVAL,
                                   [this]{return socketPair_->rtcpPacketLossDetected();})) {
        receiveThread_->triggerKeyFrameRequest();
    }
}

567
void
568
VideoRtpSession::initRecorder(std::shared_ptr<MediaRecorder>& rec)
569
{
570
    if (receiveThread_) {
571
        receiveThread_->attach(rec.get());
572 573 574
        rec->addStream(receiveThread_->getInfo());
    }
    if (auto vidInput = std::static_pointer_cast<VideoInput>(videoLocal_)) {
575
        vidInput->attach(rec.get());
576 577
        rec->addStream(vidInput->getInfo());
    }
578 579 580 581 582 583 584 585 586
}

void
VideoRtpSession::deinitRecorder(std::shared_ptr<MediaRecorder>& rec)
{
    if (receiveThread_)
        receiveThread_->detach(rec.get());
    if (auto vidInput = std::static_pointer_cast<VideoInput>(videoLocal_))
        vidInput->detach(rec.get());
587 588
}

Guillaume Roguez's avatar
Guillaume Roguez committed
589
}} // namespace ring::video