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

RtpMonitor: Scoring refactor

上级 a9fd3ff6
...@@ -83,8 +83,7 @@ namespace RTC ...@@ -83,8 +83,7 @@ namespace RTC
/* Pure virtual methods inherited from RTC::RtpMonitor::Listener. */ /* Pure virtual methods inherited from RTC::RtpMonitor::Listener. */
public: public:
void OnRtpMonitorHealthy() override; void OnRtpMonitorScore(uint8_t score) override;
void OnRtpMonitorUnhealthy() override;
public: public:
// Passed by argument. // Passed by argument.
......
...@@ -3,49 +3,76 @@ ...@@ -3,49 +3,76 @@
#include "common.hpp" #include "common.hpp"
#include "RTC/RTCP/ReceiverReport.hpp" #include "RTC/RTCP/ReceiverReport.hpp"
#include "RTC/RtpPacket.hpp"
#include "RTC/RtpStreamSend.hpp"
#include <vector> #include <vector>
namespace RTC namespace RTC
{ {
class RtpMonitor class RtpMonitor
{ {
static constexpr uint8_t MaxScore{ 10 };
static constexpr uint8_t HealthScoreThreshold{ 7 };
public:
static constexpr size_t ScoreTriggerCount{ 8 };
public: public:
class Listener class Listener
{ {
public: public:
virtual void OnRtpMonitorHealthy() = 0; virtual void OnRtpMonitorScore(uint8_t score) = 0;
virtual void OnRtpMonitorUnhealthy() = 0;
}; };
explicit RtpMonitor(Listener* listener); explicit RtpMonitor(Listener* listener, const RTC::RtpStreamSend* rtpStream);
void ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report); void ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report);
void RtpPacketRepaired(RTC::RtpPacket* packet);
bool IsHealthy() const; bool IsHealthy() const;
uint8_t GetScore() const;
void Reset(); void Reset();
void Dump();
private: private:
void AddScore(int8_t score); void AddScore(uint8_t score);
bool IsHealthyScore(int8_t score); size_t GetRepairedPacketCount() const;
void UpdateReportedLoss(RTC::RTCP::ReceiverReport* report);
void UpdateSourceLoss();
void UpdateSentPackets();
private: private:
// Passed by argument.
Listener* listener{ nullptr }; Listener* listener{ nullptr };
std::vector<int8_t> scores; const RTC::RtpStream* rtpStream{ nullptr };
bool healthy{ true }; // 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 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() inline void RtpMonitor::Reset()
{ {
this->scores.clear(); this->scoreTriggerCounter = ScoreTriggerCount;
this->healthy = true; this->totalSourceLoss = 0;
} this->totalReportedLoss = 0;
this->totalSentPackets = 0;
inline bool RtpMonitor::IsHealthyScore(int8_t score) this->repairedPackets.clear();
{ this->scores.clear();
return score >= 0;
} }
} // namespace RTC } // namespace RTC
......
...@@ -39,6 +39,7 @@ namespace RTC ...@@ -39,6 +39,7 @@ namespace RTC
const RTC::RtpCodecMimeType& GetMimeType() const; const RTC::RtpCodecMimeType& GetMimeType() const;
float GetLossPercentage() const; float GetLossPercentage() const;
uint64_t GetMaxPacketMs() const; uint64_t GetMaxPacketMs() const;
size_t GetExpectedPackets() const;
const std::string& GetId() const; const std::string& GetId() const;
void RestartStatusCheckTimer(); void RestartStatusCheckTimer();
void StopStatusCheckTimer(); void StopStatusCheckTimer();
...@@ -128,6 +129,11 @@ namespace RTC ...@@ -128,6 +129,11 @@ namespace RTC
{ {
return this->rtpStreamId; return this->rtpStreamId;
} }
inline size_t RtpStream::GetExpectedPackets() const
{
return (this->cycles + this->maxSeq) - this->baseSeq + 1;
}
} // namespace RTC } // namespace RTC
#endif #endif
...@@ -31,8 +31,6 @@ namespace RTC ...@@ -31,8 +31,6 @@ namespace RTC
this->maxRtcpInterval = RTC::RTCP::MaxAudioIntervalMs; this->maxRtcpInterval = RTC::RTCP::MaxAudioIntervalMs;
else else
this->maxRtcpInterval = RTC::RTCP::MaxVideoIntervalMs; this->maxRtcpInterval = RTC::RTCP::MaxVideoIntervalMs;
this->rtpMonitor = new RTC::RtpMonitor(this);
} }
Consumer::~Consumer() Consumer::~Consumer()
...@@ -659,6 +657,8 @@ namespace RTC ...@@ -659,6 +657,8 @@ namespace RTC
RetransmitRtpPacket(packet); RetransmitRtpPacket(packet);
this->rtpMonitor->RtpPacketRepaired(packet);
// Packet repaired after applying RTX. // Packet repaired after applying RTX.
this->rtpStream->packetsRepaired++; this->rtpStream->packetsRepaired++;
} }
...@@ -700,8 +700,14 @@ namespace RTC ...@@ -700,8 +700,14 @@ namespace RTC
if (IsPaused()) if (IsPaused())
return; 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->rtpStream->ReceiveRtcpReceiverReport(report);
this->rtpMonitor->ReceiveRtcpReceiverReport(report);
if (this->kind == RTC::Media::Kind::VIDEO)
this->rtpMonitor->ReceiveRtcpReceiverReport(report);
} }
float Consumer::GetLossPercentage() const float Consumer::GetLossPercentage() const
...@@ -742,14 +748,7 @@ namespace RTC ...@@ -742,14 +748,7 @@ namespace RTC
} }
} }
void Consumer::OnRtpMonitorHealthy() void Consumer::OnRtpMonitorScore(uint8_t /*score*/)
{
MS_TRACE();
RecalculateTargetProfile();
}
void Consumer::OnRtpMonitorUnhealthy()
{ {
MS_TRACE(); MS_TRACE();
...@@ -837,6 +836,8 @@ namespace RTC ...@@ -837,6 +836,8 @@ namespace RTC
} }
this->encodingContext.reset(RTC::Codecs::GetEncodingContext(codec.mimeType)); this->encodingContext.reset(RTC::Codecs::GetEncodingContext(codec.mimeType));
this->rtpMonitor = new RTC::RtpMonitor(this, this->rtpStream);
} }
void Consumer::RetransmitRtpPacket(RTC::RtpPacket* packet) void Consumer::RetransmitRtpPacket(RTC::RtpPacket* packet)
...@@ -909,7 +910,7 @@ namespace RTC ...@@ -909,7 +910,7 @@ namespace RTC
newTargetProfile = RtpEncodingParameters::Profile::DEFAULT; newTargetProfile = RtpEncodingParameters::Profile::DEFAULT;
} }
// RTP state is unhealty. // RTP state is unhealty.
else if (!this->rtpMonitor->IsHealthy()) else if (IsEnabled() && !this->rtpMonitor->IsHealthy())
{ {
// Ongoing probation, abort. // Ongoing probation, abort.
if (IsProbing()) if (IsProbing())
......
...@@ -8,76 +8,238 @@ namespace RTC ...@@ -8,76 +8,238 @@ namespace RTC
{ {
/* Static. */ /* Static. */
static constexpr size_t LossPercentageScoreRatio{ 2 };
static constexpr size_t MaxScore{ 10 };
static constexpr size_t HistogramLength{ 8 }; 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. */ /* Instance methods. */
RtpMonitor::RtpMonitor(Listener* listener) : listener(listener) RtpMonitor::RtpMonitor(Listener* listener, const RTC::RtpStreamSend* rtpStream)
: listener(listener), rtpStream(rtpStream)
{ {
MS_TRACE(); MS_TRACE();
} }
// A RTCP receiver report triggers a score calculation.
void RtpMonitor::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report) void RtpMonitor::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report)
{ {
MS_TRACE(); MS_TRACE();
auto fractionLost = report->GetFractionLost(); // Calculate packet loss reported since last RR.
auto lossPercentage = static_cast<uint8_t>(fractionLost * 100 / 255); 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(); MS_TRACE();
auto it = this->scores.crbegin(); if (this->repairedPackets.size() == MaxRepairedPacketsLength)
auto lastScore = MaxScore; this->repairedPackets.erase(this->repairedPackets.begin());
if (it != this->scores.crend()) this->repairedPackets[packet->GetSequenceNumber()]++;
{ }
lastScore = *it;
} 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... void RtpMonitor::AddScore(uint8_t score)
if (IsHealthyScore(lastScore) && !IsHealthyScore(currentScore)) {
MS_TRACE();
if (this->scores.size() == HistogramLength)
{ {
this->scores.clear(); this->scores.erase(this->scores.begin());
this->scores.push_back(currentScore);
} }
// Transitioning to healthy... this->scores.push_back(score);
else if (!IsHealthyScore(lastScore) && IsHealthyScore(currentScore))
if (--this->scoreTriggerCounter == 0)
{ {
this->scores.clear(); this->scoreTriggerCounter = ScoreTriggerCount;
this->scores.push_back(currentScore); 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. for (auto& score : this->scores)
else if (this->scores.size() == HistogramLength - 1)
{ {
this->scores.clear(); weight++;
this->scores.push_back(currentScore); samples += weight;
totalScore += weight * score;
if (IsHealthyScore(currentScore))
{
this->healthy = true;
this->listener->OnRtpMonitorHealthy();
}
else
{
this->healthy = false;
this->listener->OnRtpMonitorUnhealthy();
}
} }
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 } // namespace RTC
...@@ -11,31 +11,20 @@ SCENARIO("RTP Monitor", "[rtp][monitor]") ...@@ -11,31 +11,20 @@ SCENARIO("RTP Monitor", "[rtp][monitor]")
class TestRtpMonitorListener : public RtpMonitor::Listener class TestRtpMonitorListener : public RtpMonitor::Listener
{ {
public: public:
virtual void OnRtpMonitorHealthy() override virtual void OnRtpMonitorScore(uint8_t /*score*/) override
{ {
INFO("OnHealthy"); this->scoreTriggered = true;
this->healthyTriggered = true;
} }
virtual void OnRtpMonitorUnhealthy() override void Check(bool shouldHaveTriggeredScore)
{ {
INFO("OnUnhealthy"); REQUIRE(shouldHaveTriggeredScore == this->scoreTriggered);
this->unhealthyTriggered = true; this->scoreTriggered = false;
}
void Check(bool shouldHaveTriggeredHealthy, bool shouldHaveTriggeredUnhealthy)
{
REQUIRE(shouldHaveTriggeredHealthy == this->healthyTriggered);
REQUIRE(shouldHaveTriggeredUnhealthy == this->unhealthyTriggered);
this->healthyTriggered = this->unhealthyTriggered = false;
} }
public: public:
bool healthyTriggered = false; bool scoreTriggered = false;
bool unhealthyTriggered = false;
}; };
// RTCP Receiver Report Packet. // RTCP Receiver Report Packet.
...@@ -58,63 +47,56 @@ SCENARIO("RTP Monitor", "[rtp][monitor]") ...@@ -58,63 +47,56 @@ SCENARIO("RTP Monitor", "[rtp][monitor]")
if (!report) if (!report)
FAIL("failed parsing RTCP::ReceiverReport"); FAIL("failed parsing RTCP::ReceiverReport");
SECTION("Four consecutive bad reports trigger unhealthy state") RtpStream::Params params;
{
TestRtpMonitorListener listener;
RtpMonitor rtpMonitor(&listener);
report->SetFractionLost(255); /* 100% */
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(255); /* 100% */ params.ssrc = report->GetSsrc();
rtpMonitor.ReceiveRtcpReceiverReport(report); params.clockRate = 90000;
params.useNack = true;
report->SetFractionLost(255); /* 100% */ // Create a RtpStreamSend.
rtpMonitor.ReceiveRtcpReceiverReport(report); RtpStreamSend* rtpStream = new RtpStreamSend(params, 200);
report->SetFractionLost(255); /* 100% */ // clang-format off
rtpMonitor.ReceiveRtcpReceiverReport(report); uint8_t rtpBuffer[] =
{
0b10000000, 0b01111011, 0b01010010, 0b00001110,
0b01011011, 0b01101011, 0b11001010, 0b10110101,
0, 0, 0, 2
};
// clang-format on
report->SetFractionLost(255); /* 100% */ // packet1 [pt:123, seq:21006, timestamp:1533790901]
rtpMonitor.ReceiveRtcpReceiverReport(report); RtpPacket* packet = RtpPacket::Parse(rtpBuffer, sizeof(rtpBuffer));
report->SetFractionLost(255); /* 100% */ REQUIRE(packet);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(255); /* 100% */ SECTION("The eighth report triggers the score")
rtpMonitor.ReceiveRtcpReceiverReport(report); {
TestRtpMonitorListener listener;
RtpMonitor rtpMonitor(&listener, rtpStream);
report->SetFractionLost(255); /* 100% */ auto sequenceNumber = packet->GetSequenceNumber();
rtpMonitor.ReceiveRtcpReceiverReport(report);
listener.Check(false, true);
SECTION("Good report after unhealth triggers healty state") for (size_t counter = 0; counter < RtpMonitor::ScoreTriggerCount; counter++)
{ {
report->SetFractionLost(0); packet->SetSequenceNumber(sequenceNumber++);
rtpMonitor.ReceiveRtcpReceiverReport(report); rtpStream->ReceivePacket(packet);
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(0);
rtpMonitor.ReceiveRtcpReceiverReport(report); rtpMonitor.ReceiveRtcpReceiverReport(report);
}
report->SetFractionLost(0); listener.Check(true);
rtpMonitor.ReceiveRtcpReceiverReport(report);
report->SetFractionLost(0); SECTION("Next eighth consecutive reports trigger the score")
rtpMonitor.ReceiveRtcpReceiverReport(report); {
report->SetFractionLost(0); for (size_t counter = 0; counter < RtpMonitor::ScoreTriggerCount; counter++)
rtpMonitor.ReceiveRtcpReceiverReport(report); {
packet->SetSequenceNumber(sequenceNumber++);
rtpStream->ReceivePacket(packet);
rtpMonitor.ReceiveRtcpReceiverReport(report);
}
listener.Check(true, false); listener.Check(true);
} }
} }
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论