提交 fb0a664a authored 作者: José Luis Millán's avatar José Luis Millán

RtpMonitor: Scoring refactor

上级 a9fd3ff6
......@@ -83,8 +83,7 @@ namespace RTC
/* Pure virtual methods inherited from RTC::RtpMonitor::Listener. */
public:
void OnRtpMonitorHealthy() override;
void OnRtpMonitorUnhealthy() override;
void OnRtpMonitorScore(uint8_t score) override;
public:
// Passed by argument.
......
......@@ -3,49 +3,76 @@
#include "common.hpp"
#include "RTC/RTCP/ReceiverReport.hpp"
#include "RTC/RtpPacket.hpp"
#include "RTC/RtpStreamSend.hpp"
#include <vector>
namespace RTC
{
class RtpMonitor
{
static constexpr uint8_t MaxScore{ 10 };
static constexpr uint8_t HealthScoreThreshold{ 7 };
public:
static constexpr size_t ScoreTriggerCount{ 8 };
public:
class Listener
{
public:
virtual void OnRtpMonitorHealthy() = 0;
virtual void OnRtpMonitorUnhealthy() = 0;
virtual void OnRtpMonitorScore(uint8_t score) = 0;
};
explicit RtpMonitor(Listener* listener);
explicit RtpMonitor(Listener* listener, const RTC::RtpStreamSend* rtpStream);
void ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report);
void RtpPacketRepaired(RTC::RtpPacket* packet);
bool IsHealthy() const;
uint8_t GetScore() const;
void Reset();
void Dump();
private:
void AddScore(int8_t score);
bool IsHealthyScore(int8_t score);
void AddScore(uint8_t score);
size_t GetRepairedPacketCount() const;
void UpdateReportedLoss(RTC::RTCP::ReceiverReport* report);
void UpdateSourceLoss();
void UpdateSentPackets();
private:
// Passed by argument.
Listener* listener{ nullptr };
std::vector<int8_t> scores;
bool healthy{ true };
const RTC::RtpStream* rtpStream{ nullptr };
// Counter for event notification.
size_t scoreTriggerCounter{ ScoreTriggerCount };
// Scores histogram.
std::vector<uint8_t> scores;
// Rapaired RTP packet map.
std::map<uint16_t, size_t> repairedPackets;
// RTP stream data information for score calculation.
int32_t totalSourceLoss{ 0 };
int32_t totalReportedLoss{ 0 };
size_t totalSentPackets{ 0 };
};
inline bool RtpMonitor::IsHealthy() const
{
return this->healthy;
// Consider it healthy if no score is present.
if (this->scores.empty())
return true;
return GetScore() >= HealthScoreThreshold;
}
inline void RtpMonitor::Reset()
{
this->scores.clear();
this->healthy = true;
}
this->scoreTriggerCounter = ScoreTriggerCount;
this->totalSourceLoss = 0;
this->totalReportedLoss = 0;
this->totalSentPackets = 0;
inline bool RtpMonitor::IsHealthyScore(int8_t score)
{
return score >= 0;
this->repairedPackets.clear();
this->scores.clear();
}
} // namespace RTC
......
......@@ -39,6 +39,7 @@ namespace RTC
const RTC::RtpCodecMimeType& GetMimeType() const;
float GetLossPercentage() const;
uint64_t GetMaxPacketMs() const;
size_t GetExpectedPackets() const;
const std::string& GetId() const;
void RestartStatusCheckTimer();
void StopStatusCheckTimer();
......@@ -128,6 +129,11 @@ namespace RTC
{
return this->rtpStreamId;
}
inline size_t RtpStream::GetExpectedPackets() const
{
return (this->cycles + this->maxSeq) - this->baseSeq + 1;
}
} // namespace RTC
#endif
......@@ -31,8 +31,6 @@ namespace RTC
this->maxRtcpInterval = RTC::RTCP::MaxAudioIntervalMs;
else
this->maxRtcpInterval = RTC::RTCP::MaxVideoIntervalMs;
this->rtpMonitor = new RTC::RtpMonitor(this);
}
Consumer::~Consumer()
......@@ -659,6 +657,8 @@ namespace RTC
RetransmitRtpPacket(packet);
this->rtpMonitor->RtpPacketRepaired(packet);
// Packet repaired after applying RTX.
this->rtpStream->packetsRepaired++;
}
......@@ -700,8 +700,14 @@ namespace RTC
if (IsPaused())
return;
// Ignore reports that do not refer to the main RTP stream. Ie: RTX stream.
if (report->GetSsrc() != this->rtpStream->GetSsrc())
return;
this->rtpStream->ReceiveRtcpReceiverReport(report);
this->rtpMonitor->ReceiveRtcpReceiverReport(report);
if (this->kind == RTC::Media::Kind::VIDEO)
this->rtpMonitor->ReceiveRtcpReceiverReport(report);
}
float Consumer::GetLossPercentage() const
......@@ -742,14 +748,7 @@ namespace RTC
}
}
void Consumer::OnRtpMonitorHealthy()
{
MS_TRACE();
RecalculateTargetProfile();
}
void Consumer::OnRtpMonitorUnhealthy()
void Consumer::OnRtpMonitorScore(uint8_t /*score*/)
{
MS_TRACE();
......@@ -837,6 +836,8 @@ namespace RTC
}
this->encodingContext.reset(RTC::Codecs::GetEncodingContext(codec.mimeType));
this->rtpMonitor = new RTC::RtpMonitor(this, this->rtpStream);
}
void Consumer::RetransmitRtpPacket(RTC::RtpPacket* packet)
......@@ -909,7 +910,7 @@ namespace RTC
newTargetProfile = RtpEncodingParameters::Profile::DEFAULT;
}
// RTP state is unhealty.
else if (!this->rtpMonitor->IsHealthy())
else if (IsEnabled() && !this->rtpMonitor->IsHealthy())
{
// Ongoing probation, abort.
if (IsProbing())
......
......@@ -8,76 +8,238 @@ namespace RTC
{
/* Static. */
static constexpr size_t LossPercentageScoreRatio{ 2 };
static constexpr size_t MaxScore{ 10 };
static constexpr size_t HistogramLength{ 8 };
static constexpr size_t MaxRepairedPacketRetransmission{ 2 };
static constexpr size_t MaxRepairedPacketsLength{ 1000 };
// Score constraints weight.
static constexpr float LossPercentageWeight{ -1.0f };
static constexpr float RepairedPercentageWeight{ 0.5f };
/* Instance methods. */
RtpMonitor::RtpMonitor(Listener* listener) : listener(listener)
RtpMonitor::RtpMonitor(Listener* listener, const RTC::RtpStreamSend* rtpStream)
: listener(listener), rtpStream(rtpStream)
{
MS_TRACE();
}
// A RTCP receiver report triggers a score calculation.
void RtpMonitor::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report)
{
MS_TRACE();
auto fractionLost = report->GetFractionLost();
auto lossPercentage = static_cast<uint8_t>(fractionLost * 100 / 255);
// Calculate packet loss reported since last RR.
auto previousTotalReportedLoss = this->totalReportedLoss;
UpdateReportedLoss(report);
auto reportedLoss = this->totalReportedLoss - previousTotalReportedLoss;
if (reportedLoss < 0)
reportedLoss = 0;
// Calculate source packet loss since last RR.
auto previousTotalSourceLoss = this->totalSourceLoss;
UpdateSourceLoss();
auto sourceLoss = this->totalSourceLoss - previousTotalSourceLoss;
if (sourceLoss < 0)
sourceLoss = 0;
// Calculate effective loss since last report.
size_t currentLoss;
if (reportedLoss < sourceLoss)
currentLoss = 0;
else
currentLoss = reportedLoss - sourceLoss;
// Calculate repaired packets.
auto repairedPacketCount = GetRepairedPacketCount();
// Reset repaired packets map.
this->repairedPackets.clear();
// Calculate packets sent since last RR.
auto previousTotalSentPackets = this->totalSentPackets;
UpdateSentPackets();
auto sentPackets = this->totalSentPackets - previousTotalSentPackets;
MS_ASSERT(
this->totalSentPackets >= previousTotalSentPackets, "less packets sent now than before");
// No packet was sent. Consider lost and repaired packets though.
if (sentPackets == 0)
{
sentPackets = (currentLoss > repairedPacketCount) ? currentLoss : repairedPacketCount;
}
// Nothing to do.
if (sentPackets == 0)
{
return;
}
auto score = MaxScore - static_cast<int8_t>(lossPercentage / LossPercentageScoreRatio);
// There cannot be more loss than sent packets.
if (currentLoss > sentPackets)
{
currentLoss = sentPackets;
}
// There cannot be more repaired than sent packets.
if (repairedPacketCount > sentPackets)
{
repairedPacketCount = sentPackets;
}
this->AddScore(score);
float lossPercentage = currentLoss * 100 / sentPackets;
float repairedPercentage = repairedPacketCount * 100 / sentPackets;
/*
* Calculate score. Starting from a score of 100:
*
* - Each loss porcentual point has a weight of LossPercentageWeight.
* - Each repaired porcentual point has a weight of RepairedPercentageWeight.
*/
float score = 100;
score += lossPercentage * LossPercentageWeight;
score += repairedPercentage * RepairedPercentageWeight;
// Add score to histogram.
this->AddScore(static_cast<uint8_t>(score / 10 + 0.5f));
#ifdef MS_LOG_DEV
MS_DEBUG_TAG(
rtp,
"sentPackets: %zu, currentLoss: %zu, repairedPacketCount: %zu, lossPercentage: %f, repairedPercentage: %f, score: %f ",
sentPackets,
currentLoss,
repairedPacketCount,
lossPercentage,
repairedPercentage,
score);
report->Dump();
this->Dump();
#endif
}
void RtpMonitor::AddScore(int8_t currentScore)
void RtpMonitor::RtpPacketRepaired(RTC::RtpPacket* packet)
{
MS_TRACE();
auto it = this->scores.crbegin();
auto lastScore = MaxScore;
if (this->repairedPackets.size() == MaxRepairedPacketsLength)
this->repairedPackets.erase(this->repairedPackets.begin());
if (it != this->scores.crend())
{
lastScore = *it;
}
this->repairedPackets[packet->GetSequenceNumber()]++;
}
void RtpMonitor::Dump()
{
MS_TRACE();
MS_DUMP("<RtpMonitor>");
MS_DUMP(" score : %" PRIi8, GetScore());
MS_DUMP(" totalSourceLoss : %" PRIi32, this->totalSourceLoss);
MS_DUMP(" totalReportedLoss : %" PRIi32, this->totalReportedLoss);
MS_DUMP(" repairedPackets size : %zu", this->repairedPackets.size());
MS_DUMP("</RtpMonitor>");
}
// Transitioning to unhealthy...
if (IsHealthyScore(lastScore) && !IsHealthyScore(currentScore))
void RtpMonitor::AddScore(uint8_t score)
{
MS_TRACE();
if (this->scores.size() == HistogramLength)
{
this->scores.clear();
this->scores.push_back(currentScore);
this->scores.erase(this->scores.begin());
}
// Transitioning to healthy...
else if (!IsHealthyScore(lastScore) && IsHealthyScore(currentScore))
this->scores.push_back(score);
if (--this->scoreTriggerCounter == 0)
{
this->scores.clear();
this->scores.push_back(currentScore);
this->scoreTriggerCounter = ScoreTriggerCount;
this->listener->OnRtpMonitorScore(GetScore());
}
}
/*
* Scoring mechanism is a weighted average.
*
* The more recent the score is, the more weight it has.
* The oldest score has a weight of 1 and subsequent scores weight is
* increased by one sequentially.
*
* Ie:
* - scores: [1,2,3,4]
* - this->scores = ((1) + (2+2) + (3+3+3) + (4+4+4+4)) / 10 = 2.8 => 3
*/
uint8_t RtpMonitor::GetScore() const
{
MS_TRACE();
size_t weight = 0;
size_t samples = 0;
size_t totalScore = 0;
// HistogramLength healthy or unhealthy scores achieved. Notify listener.
else if (this->scores.size() == HistogramLength - 1)
for (auto& score : this->scores)
{
this->scores.clear();
this->scores.push_back(currentScore);
if (IsHealthyScore(currentScore))
{
this->healthy = true;
this->listener->OnRtpMonitorHealthy();
}
else
{
this->healthy = false;
this->listener->OnRtpMonitorUnhealthy();
}
weight++;
samples += weight;
totalScore += weight * score;
}
else
return static_cast<uint8_t>(std::round(totalScore / samples));
}
/*
* A RTP packet is considered to be repaired if it was resent no more than
* MaxRepairedPacketRetransmission times.
*/
size_t RtpMonitor::GetRepairedPacketCount() const
{
MS_TRACE();
size_t count = 0;
for (auto& it : this->repairedPackets)
{
this->scores.push_back(currentScore);
if (it.second <= MaxRepairedPacketRetransmission)
count++;
}
return count;
}
void RtpMonitor::UpdateReportedLoss(RTC::RTCP::ReceiverReport* report)
{
MS_TRACE();
this->totalReportedLoss = report->GetTotalLost();
}
void RtpMonitor::UpdateSourceLoss()
{
MS_TRACE();
this->totalSourceLoss = static_cast<int32_t>(
this->rtpStream->GetExpectedPackets() - this->rtpStream->transmissionCounter.GetPacketCount());
}
void RtpMonitor::UpdateSentPackets()
{
MS_TRACE();
this->totalSentPackets = this->rtpStream->transmissionCounter.GetPacketCount();
}
} // namespace RTC
......@@ -11,31 +11,20 @@ SCENARIO("RTP Monitor", "[rtp][monitor]")
class TestRtpMonitorListener : public RtpMonitor::Listener
{
public:
virtual void OnRtpMonitorHealthy() override
virtual void OnRtpMonitorScore(uint8_t /*score*/) override
{
INFO("OnHealthy");
this->healthyTriggered = true;
this->scoreTriggered = true;
}
virtual void OnRtpMonitorUnhealthy() override
void Check(bool shouldHaveTriggeredScore)
{
INFO("OnUnhealthy");
REQUIRE(shouldHaveTriggeredScore == this->scoreTriggered);
this->unhealthyTriggered = true;
}
void Check(bool shouldHaveTriggeredHealthy, bool shouldHaveTriggeredUnhealthy)
{
REQUIRE(shouldHaveTriggeredHealthy == this->healthyTriggered);
REQUIRE(shouldHaveTriggeredUnhealthy == this->unhealthyTriggered);
this->healthyTriggered = this->unhealthyTriggered = false;
this->scoreTriggered = false;
}
public:
bool healthyTriggered = false;
bool unhealthyTriggered = false;
bool scoreTriggered = false;
};
// RTCP Receiver Report Packet.
......@@ -58,63 +47,56 @@ SCENARIO("RTP Monitor", "[rtp][monitor]")
if (!report)
FAIL("failed parsing RTCP::ReceiverReport");
SECTION("Four consecutive bad reports trigger unhealthy state")
{
TestRtpMonitorListener listener;
RtpMonitor rtpMonitor(&listener);
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
RtpStream::Params params;
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
params.ssrc = report->GetSsrc();
params.clockRate = 90000;
params.useNack = true;
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
// Create a RtpStreamSend.
RtpStreamSend* rtpStream = new RtpStreamSend(params, 200);
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
// clang-format off
uint8_t rtpBuffer[] =
{
0b10000000, 0b01111011, 0b01010010, 0b00001110,
0b01011011, 0b01101011, 0b11001010, 0b10110101,
0, 0, 0, 2
};
// clang-format on
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
// packet1 [pt:123, seq:21006, timestamp:1533790901]
RtpPacket* packet = RtpPacket::Parse(rtpBuffer, sizeof(rtpBuffer));
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
REQUIRE(packet);
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
SECTION("The eighth report triggers the score")
{
TestRtpMonitorListener listener;
RtpMonitor rtpMonitor(&listener, rtpStream);
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
listener.Check(false, true);
auto sequenceNumber = packet->GetSequenceNumber();
SECTION("Good report after unhealth triggers healty state")
for (size_t counter = 0; counter < RtpMonitor::ScoreTriggerCount; counter++)
{
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(0);
packet->SetSequenceNumber(sequenceNumber++);
rtpStream->ReceivePacket(packet);
rtpMonitor.ReceiveRtcpReceiverReport(report);
}
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
listener.Check(true);
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
SECTION("Next eighth consecutive reports trigger the score")
{
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
for (size_t counter = 0; counter < RtpMonitor::ScoreTriggerCount; counter++)
{
packet->SetSequenceNumber(sequenceNumber++);
rtpStream->ReceivePacket(packet);
rtpMonitor.ReceiveRtcpReceiverReport(report);
}
listener.Check(true, false);
listener.Check(true);
}
}
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论