Unverified 提交 a6857b62 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo 提交者: GitHub

Refactor RTP retransmission buffer in a separate and testable…

Refactor RTP retransmission buffer in a separate and testable RTC::RetransmissionBuffer class (#1023)
上级 181ce8a1
# Changelog
### 3.11.14
* Refactor RTP retransmission buffer in a separate and testable `RTC::RetransmissionBuffer` class ([PR #1023](https://github.com/versatica/mediasoup/pull/1023).
* Update NPM deps.
### 3.11.13
* `AudioLevelObserver`: Use multimap rather than map to avoid conflict if various Producers generate same audio level ([PR #1021](https://github.com/versatica/mediasoup/pull/1021), issue reported by @buptlsp).
......
#ifndef MS_RTC_RTP_RETRANSMISSION_BUFFER_HPP
#define MS_RTC_RTP_RETRANSMISSION_BUFFER_HPP
#include "common.hpp"
#include "RTC/RtpPacket.hpp"
#include <deque>
namespace RTC
{
// Special container that stores `Item`* elements addressable by their `uint16_t`
// sequence number, while only taking as little memory as necessary to store
// the range covering a maximum of `MaxRetransmissionDelayForVideoMs` or
// `MaxRetransmissionDelayForAudioMs` ms.
class RetransmissionBuffer
{
public:
struct Item
{
void Reset();
// Original packet.
std::shared_ptr<RTC::RtpPacket> packet{ nullptr };
// Correct SSRC since original packet may not have the same.
uint32_t ssrc{ 0u };
// Correct sequence number since original packet may not have the same.
uint16_t sequenceNumber{ 0u };
// Correct timestamp since original packet may not have the same.
uint32_t timestamp{ 0u };
// Last time this packet was resent.
uint64_t resentAtMs{ 0u };
// Number of times this packet was resent.
uint8_t sentTimes{ 0u };
};
public:
RetransmissionBuffer(uint16_t maxItems, uint32_t maxRetransmissionDelayMs, uint32_t clockRate);
~RetransmissionBuffer();
Item* Get(uint16_t seq) const;
void Insert(RTC::RtpPacket* packet, std::shared_ptr<RTC::RtpPacket>& sharedPacket);
void Clear();
void Dump() const;
private:
Item* GetOldest() const;
Item* GetNewest() const;
void RemoveOldest();
void RemoveOldest(uint16_t numItems);
void ClearTooOld();
bool IsTooOld(uint32_t timestamp, uint32_t newestTimestamp) const;
Item* FillItem(
Item* item, RTC::RtpPacket* packet, std::shared_ptr<RTC::RtpPacket>& sharedPacket) const;
protected:
// Make buffer protected for testing purposes.
std::deque<Item*> buffer;
private:
// Given as argument.
uint16_t maxItems;
uint32_t maxRetransmissionDelayMs;
uint32_t clockRate;
// Others.
uint16_t startSeq{ 0u };
};
} // namespace RTC
#endif
......@@ -13,6 +13,7 @@
#include "RTC/RTCP/XrDelaySinceLastRr.hpp"
#include "RTC/RTCP/XrReceiverReferenceTime.hpp"
#include "RTC/RtpDictionaries.hpp"
#include "RTC/RtpPacket.hpp"
#include "RTC/RtxStream.hpp"
#include <nlohmann/json.hpp>
#include <string>
......@@ -180,12 +181,18 @@ namespace RTC
Params params;
// Others.
// https://tools.ietf.org/html/rfc3550#appendix-A.1 stuff.
uint16_t maxSeq{ 0u }; // Highest seq. number seen.
uint32_t cycles{ 0u }; // Shifted count of seq. number cycles.
uint32_t baseSeq{ 0u }; // Base seq number.
uint32_t badSeq{ 0u }; // Last 'bad' seq number + 1.
uint32_t maxPacketTs{ 0u }; // Highest timestamp seen.
uint64_t maxPacketMs{ 0u }; // When the packet with highest timestammp was seen.
// Highest seq. number seen.
uint16_t maxSeq{ 0u };
// Shifted count of seq. number cycles.
uint32_t cycles{ 0u };
// Base seq number.
uint32_t baseSeq{ 0u };
// Last 'bad' seq number + 1.
uint32_t badSeq{ 0u };
// Highest timestamp seen.
uint32_t maxPacketTs{ 0u };
// When the packet with highest timestammp was seen.
uint64_t maxPacketMs{ 0u };
uint32_t packetsLost{ 0u };
uint8_t fractionLost{ 0u };
size_t packetsDiscarded{ 0u };
......@@ -195,12 +202,14 @@ namespace RTC
size_t nackPacketCount{ 0u };
size_t pliCount{ 0u };
size_t firCount{ 0u };
size_t repairedPriorScore{ 0u }; // Packets repaired at last interval for score calculation.
size_t retransmittedPriorScore{
0u
}; // Packets retransmitted at last interval for score calculation.
uint64_t lastSenderReportNtpMs{ 0u }; // NTP timestamp in last Sender Report (in ms).
uint32_t lastSenderReportTs{ 0u }; // RTP timestamp in last Sender Report.
// Packets repaired at last interval for score calculation.
size_t repairedPriorScore{ 0u };
// Packets retransmitted at last interval for score calculation.
size_t retransmittedPriorScore{ 0u };
// NTP timestamp in last Sender Report (in ms).
uint64_t lastSenderReportNtpMs{ 0u };
// RTP timestamp in last Sender Report.
uint32_t lastSenderReportTs{ 0u };
float rtt{ 0 };
bool hasRtt{ false };
// Instance of RtxStream.
......
......@@ -93,24 +93,31 @@ namespace RTC
// Passed by argument.
unsigned int sendNackDelayMs{ 0u };
// Others.
uint32_t expectedPrior{ 0u }; // Packets expected at last interval.
uint32_t expectedPriorScore{ 0u }; // Packets expected at last interval for score calculation.
uint32_t receivedPrior{ 0u }; // Packets received at last interval.
uint32_t receivedPriorScore{ 0u }; // Packets received at last interval for score calculation.
uint32_t lastSrTimestamp{ 0u }; // The middle 32 bits out of 64 in the NTP
// timestamp received in the most recent
// sender report.
uint64_t lastSrReceived{ 0u }; // Wallclock time representing the most recent
// sender report arrival.
int32_t transit{ 0u }; // Relative transit time for prev packet.
// Packets expected at last interval.
uint32_t expectedPrior{ 0u };
// Packets expected at last interval for score calculation.
uint32_t expectedPriorScore{ 0u };
// Packets received at last interval.
uint32_t receivedPrior{ 0u };
// Packets received at last interval for score calculation.
uint32_t receivedPriorScore{ 0u };
// The middle 32 bits out of 64 in the NTP timestamp received in the most
// recent sender report.
uint32_t lastSrTimestamp{ 0u };
// Wallclock time representing the most recent sender report arrival.
uint64_t lastSrReceived{ 0u };
// Relative transit time for prev packet.
int32_t transit{ 0u };
uint32_t jitter{ 0u };
uint8_t firSeqNumber{ 0u };
uint32_t reportedPacketLost{ 0u };
std::unique_ptr<RTC::NackGenerator> nackGenerator;
Timer* inactivityCheckPeriodicTimer{ nullptr };
bool inactive{ false };
TransmissionCounter transmissionCounter; // Valid media + valid RTX.
RTC::RtpDataCounter mediaTransmissionCounter; // Just valid media.
// Valid media + valid RTX.
TransmissionCounter transmissionCounter;
// Just valid media.
RTC::RtpDataCounter mediaTransmissionCounter;
};
} // namespace RTC
......
......@@ -2,16 +2,14 @@
#define MS_RTC_RTP_STREAM_SEND_HPP
#include "RTC/RateCalculator.hpp"
#include "RTC/RetransmissionBuffer.hpp"
#include "RTC/RtpStream.hpp"
#include <deque>
namespace RTC
{
class RtpStreamSend : public RTC::RtpStream
{
public:
// Minimum retransmission buffer size (ms).
const static uint32_t MinRetransmissionDelayMs;
// Maximum retransmission buffer size for video (ms).
const static uint32_t MaxRetransmissionDelayForVideoMs;
// Maximum retransmission buffer size for audio (ms).
......@@ -25,47 +23,6 @@ namespace RTC
RTC::RtpStreamSend* rtpStream, RTC::RtpPacket* packet) = 0;
};
public:
struct StorageItem
{
void Reset();
// Original packet.
std::shared_ptr<RTC::RtpPacket> packet{ nullptr };
// Correct SSRC since original packet may not have the same.
uint32_t ssrc{ 0 };
// Correct sequence number since original packet may not have the same.
uint16_t sequenceNumber{ 0 };
// Correct timestamp since original packet may not have the same.
uint32_t timestamp{ 0 };
// Last time this packet was resent.
uint64_t resentAtMs{ 0u };
// Number of times this packet was resent.
uint8_t sentTimes{ 0u };
};
private:
// Special container that stores `StorageItem*` elements addressable by
// their `uint16_t` sequence number, while only taking as little memory as
// necessary to store the range covering a maximum of
// MaxRetransmissionDelayForVideoMs or MaxRetransmissionDelayForAudioMs ms.
class StorageItemBuffer
{
public:
~StorageItemBuffer();
StorageItem* GetFirst() const;
StorageItem* Get(uint16_t seq) const;
size_t GetBufferSize() const;
void Insert(uint16_t seq, StorageItem* storageItem);
void RemoveFirst();
void Clear();
private:
uint16_t startSeq{ 0 };
std::deque<StorageItem*> buffer;
};
public:
RtpStreamSend(
RTC::RtpStreamSend::Listener* listener, RTC::RtpStream::Params& params, std::string& mid);
......@@ -93,25 +50,24 @@ namespace RTC
private:
void StorePacket(RTC::RtpPacket* packet, std::shared_ptr<RTC::RtpPacket>& sharedPacket);
void ClearOldPackets(const RtpPacket* packet);
void ClearBuffer();
void FillRetransmissionContainer(uint16_t seq, uint16_t bitmask);
void UpdateScore(RTC::RTCP::ReceiverReport* report);
private:
uint32_t lostPriorScore{ 0u }; // Packets lost at last interval for score calculation.
uint32_t sentPriorScore{ 0u }; // Packets sent at last interval for score calculation.
StorageItemBuffer storageItemBuffer;
// Packets lost at last interval for score calculation.
uint32_t lostPriorScore{ 0u };
// Packets sent at last interval for score calculation.
uint32_t sentPriorScore{ 0u };
std::string mid;
uint32_t maxRetransmissionDelayMs;
uint32_t retransmissionBufferSize;
uint16_t rtxSeq{ 0u };
RTC::RtpDataCounter transmissionCounter;
uint32_t lastRrTimestamp{ 0u }; // The middle 32 bits out of 64 in the NTP
// timestamp received in the most recent
// receiver reference timestamp.
uint64_t lastRrReceivedMs{ 0u }; // Wallclock time representing the most recent
// receiver reference timestamp arrival.
RTC::RetransmissionBuffer* retransmissionBuffer{ nullptr };
// The middle 32 bits out of 64 in the NTP timestamp received in the most
// recent receiver reference timestamp.
uint32_t lastRrTimestamp{ 0u };
// Wallclock time representing the most recent receiver reference timestamp
// arrival.
uint64_t lastRrReceivedMs{ 0u };
};
} // namespace RTC
......
......@@ -9,7 +9,7 @@
#include <memory> // std::addressof()
#ifdef _WIN32
#include <winsock2.h>
// avoid uv/win.h: error C2628 'intptr_t' followed by 'int' is illegal.
// Avoid uv/win.h: error C2628 'intptr_t' followed by 'int' is illegal.
#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
......@@ -25,15 +25,17 @@ typedef SSIZE_T ssize_t;
using ChannelReadCtx = void*;
using ChannelReadFreeFn = void (*)(uint8_t*, uint32_t, size_t);
// Returns `ChannelReadFree` on successful read that must be used to free `message`.
// Returns `ChannelReadFree` on successful read that must be used to free
// `message`.
using ChannelReadFn = ChannelReadFreeFn (*)(
uint8_t** /* message */,
uint32_t* /* messageLen */,
size_t* /* messageCtx */,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more
// data to read.
// This is `uv_async_t` handle that can be called later with `uv_async_send()`
// when there is more data to read.
const void* /* handle */,
ChannelReadCtx /* ctx */);
ChannelReadCtx /* ctx */
);
using ChannelWriteCtx = void*;
using ChannelWriteFn =
......@@ -41,7 +43,8 @@ using ChannelWriteFn =
using PayloadChannelReadCtx = void*;
using PayloadChannelReadFreeFn = void (*)(uint8_t*, uint32_t, size_t);
// Returns `PayloadChannelReadFree` on successful read that must be used to free `message` and `payload`.
// Returns `PayloadChannelReadFree` on successful read that must be used to free
// `message` and `payload`.
using PayloadChannelReadFn = PayloadChannelReadFreeFn (*)(
uint8_t** /* message */,
uint32_t* /* messageLen */,
......@@ -49,8 +52,8 @@ using PayloadChannelReadFn = PayloadChannelReadFreeFn (*)(
uint8_t** /* payload */,
uint32_t* /* payloadLen */,
size_t* /* payloadCapacity */,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more
// data to read.
// This is `uv_async_t` handle that can be called later with `uv_async_send()`
// when there is more data to read.
const void* /* handle */,
PayloadChannelReadCtx /* ctx */);
......
......@@ -84,6 +84,7 @@ common_sources = [
'src/RTC/PortManager.cpp',
'src/RTC/Producer.cpp',
'src/RTC/RateCalculator.cpp',
'src/RTC/RetransmissionBuffer.cpp',
'src/RTC/Router.cpp',
'src/RTC/RtpListener.cpp',
'src/RTC/RtpObserver.cpp',
......@@ -287,6 +288,7 @@ mediasoup_worker_test = executable(
'test/src/RTC/TestKeyFrameRequestManager.cpp',
'test/src/RTC/TestNackGenerator.cpp',
'test/src/RTC/TestRateCalculator.cpp',
'test/src/RTC/TestRetransmissionBuffer.cpp',
'test/src/RTC/TestRtpPacket.cpp',
'test/src/RTC/TestRtpPacketH264Svc.cpp',
'test/src/RTC/TestRtpStreamSend.cpp',
......
差异被折叠。
......@@ -41,11 +41,15 @@ namespace RTC
// Sanity check. Do not allow spatial layers higher than defined.
if (spatialLayer > this->spatialLayerCounters.size() - 1)
{
spatialLayer = this->spatialLayerCounters.size() - 1;
}
// Sanity check. Do not allow temporal layers higher than defined.
if (temporalLayer > this->spatialLayerCounters[0].size() - 1)
{
temporalLayer = this->spatialLayerCounters[0].size() - 1;
}
auto& counter = this->spatialLayerCounters[spatialLayer][temporalLayer];
......@@ -82,7 +86,9 @@ namespace RTC
auto& counter = this->spatialLayerCounters[spatialLayer][temporalLayer];
if (counter.GetBitrate(nowMs) == 0)
{
return 0u;
}
uint32_t rate{ 0u };
......@@ -191,7 +197,9 @@ namespace RTC
MS_TRACE();
if (this->params.useNack)
{
this->nackGenerator.reset(new RTC::NackGenerator(this, this->sendNackDelayMs));
}
// Run the RTP inactivity periodic timer (use a different timeout if DTX is
// enabled).
......@@ -199,9 +207,13 @@ namespace RTC
this->inactive = false;
if (!this->params.useDtx)
{
this->inactivityCheckPeriodicTimer->Start(InactivityCheckInterval);
}
else
{
this->inactivityCheckPeriodicTimer->Start(InactivityCheckIntervalWithDtx);
}
}
RtpStreamRecv::~RtpStreamRecv()
......@@ -256,7 +268,9 @@ namespace RTC
// Process the packet at codec level.
if (packet->GetPayloadType() == GetPayloadType())
{
RTC::Codecs::Tools::ProcessRtpPacket(packet, GetMimeType());
}
// Pass the packet to the NackGenerator.
if (this->params.useNack)
......@@ -295,7 +309,9 @@ namespace RTC
// Restart the inactivityCheckPeriodicTimer.
if (this->inactivityCheckPeriodicTimer)
{
this->inactivityCheckPeriodicTimer->Restart();
}
return true;
}
......@@ -376,7 +392,9 @@ namespace RTC
// Process the packet at codec level.
if (packet->GetPayloadType() == GetPayloadType())
{
RTC::Codecs::Tools::ProcessRtpPacket(packet, GetMimeType());
}
// Mark the packet as retransmitted.
RTC::RtpStream::PacketRetransmitted(packet);
......@@ -401,7 +419,9 @@ namespace RTC
// Restart the inactivityCheckPeriodicTimer.
if (this->inactivityCheckPeriodicTimer)
{
this->inactivityCheckPeriodicTimer->Restart();
}
return true;
}
......@@ -422,7 +442,9 @@ namespace RTC
->OnRtpStreamNeedWorstRemoteFractionLost(this, worstRemoteFractionLost);
if (worstRemoteFractionLost > 0)
{
MS_DEBUG_TAG(rtcp, "using worst remote fraction lost:%" PRIu8, worstRemoteFractionLost);
}
}
auto* report = new RTC::RTCP::ReceiverReport();
......@@ -435,9 +457,13 @@ namespace RTC
auto expected = GetExpectedPackets();
if (expected > this->mediaTransmissionCounter.GetPacketCount())
{
this->packetsLost = expected - this->mediaTransmissionCounter.GetPacketCount();
}
else
{
this->packetsLost = 0u;
}
// Calculate Fraction Lost.
const uint32_t expectedInterval = expected - this->expectedPrior;
......@@ -452,9 +478,13 @@ namespace RTC
const int32_t lostInterval = expectedInterval - receivedInterval;
if (expectedInterval == 0 || lostInterval <= 0)
{
this->fractionLost = 0;
}
else
{
this->fractionLost = std::round((static_cast<double>(lostInterval << 8) / expectedInterval));
}
// Worst remote fraction lost is not worse than local one.
if (worstRemoteFractionLost <= this->fractionLost)
......@@ -505,7 +535,9 @@ namespace RTC
MS_TRACE();
if (HasRtx())
{
return this->rtxStream->GetRtcpReceiverReport();
}
return nullptr;
}
......@@ -536,7 +568,9 @@ namespace RTC
MS_TRACE();
if (HasRtx())
{
this->rtxStream->ReceiveRtcpSenderReport(report);
}
}
void RtpStreamRecv::ReceiveRtcpXrDelaySinceLastRr(RTC::RTCP::DelaySinceLastRr::SsrcInfo* ssrcInfo)
......@@ -563,18 +597,24 @@ namespace RTC
// If no Receiver Extended Report was received by the remote endpoint yet,
// ignore lastRr and dlrr values in the Sender Extended Report.
if (lastRr && dlrr && (compactNtp > dlrr + lastRr))
{
rtt = compactNtp - dlrr - lastRr;
}
// RTT in milliseconds.
this->rtt = static_cast<float>(rtt >> 16) * 1000;
this->rtt += (static_cast<float>(rtt & 0x0000FFFF) / 65536) * 1000;
if (this->rtt > 0.0f)
{
this->hasRtt = true;
}
// Tell it to the NackGenerator.
if (this->params.useNack)
{
this->nackGenerator->UpdateRtt(static_cast<uint32_t>(this->rtt));
}
}
void RtpStreamRecv::RequestKeyFrame()
......@@ -620,10 +660,14 @@ namespace RTC
MS_TRACE();
if (this->inactivityCheckPeriodicTimer)
{
this->inactivityCheckPeriodicTimer->Stop();
}
if (this->params.useNack)
{
this->nackGenerator->Reset();
}
// Reset jitter.
this->transit = 0;
......@@ -635,7 +679,9 @@ namespace RTC
MS_TRACE();
if (this->inactivityCheckPeriodicTimer && !this->inactive)
{
this->inactivityCheckPeriodicTimer->Restart();
}
}
void RtpStreamRecv::CalculateJitter(uint32_t rtpTimestamp)
......@@ -643,7 +689,9 @@ namespace RTC
MS_TRACE();
if (this->params.clockRate == 0u)
{
return;
}
// NOTE: Based on https://github.com/versatica/mediasoup/issues/1018.
auto transit = static_cast<int>(
......@@ -661,7 +709,9 @@ namespace RTC
this->transit = transit;
if (d < 0)
{
d = -d;
}
this->jitter += (1. / 16.) * (static_cast<double>(d) - this->jitter);
}
......@@ -686,9 +736,13 @@ namespace RTC
uint32_t lost;
if (expected < received)
{
lost = 0;
}
else
{
lost = expected - received;
}
// Calculate number of packets repaired in this interval.
const auto totalRepaired = this->packetsRepaired;
......@@ -703,7 +757,9 @@ namespace RTC
this->retransmittedPriorScore = totatRetransmitted;
if (this->inactive)
{
return;
}
// We didn't expect more packets to come.
if (expected == 0)
......@@ -714,7 +770,9 @@ namespace RTC
}
if (lost > received)
{
lost = received;
}
if (repaired > lost)
{
......@@ -754,7 +812,9 @@ namespace RTC
MS_ASSERT(retransmitted >= repaired, "repaired packets cannot be more than retransmitted ones");
if (retransmitted > 0)
{
repairedWeight *= static_cast<float>(repaired) / retransmitted;
}
lost -= repaired * repairedWeight;
......@@ -826,7 +886,9 @@ namespace RTC
uint16_t shift = *it - seq - 1;
if (shift > 15)
{
break;
}
bitmask |= (1 << shift);
++it;
......
......@@ -43,7 +43,9 @@ Timer::~Timer()
MS_TRACE();
if (!this->closed)
{
Close();
}
}
void Timer::Close()
......@@ -51,7 +53,9 @@ void Timer::Close()
MS_TRACE();
if (this->closed)
{
return;
}
this->closed = true;
......@@ -63,18 +67,24 @@ void Timer::Start(uint64_t timeout, uint64_t repeat)
MS_TRACE();
if (this->closed)
{
MS_THROW_ERROR("closed");
}
this->timeout = timeout;
this->repeat = repeat;
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0)
{
Stop();
}
const int err = uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), timeout, repeat);
if (err != 0)
{
MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err));
}
}
void Timer::Stop()
......@@ -82,12 +92,16 @@ void Timer::Stop()
MS_TRACE();
if (this->closed)
{
MS_THROW_ERROR("closed");
}
const int err = uv_timer_stop(this->uvHandle);
if (err != 0)
{
MS_THROW_ERROR("uv_timer_stop() failed: %s", uv_strerror(err));
}
}
void Timer::Reset()
......@@ -95,19 +109,27 @@ void Timer::Reset()
MS_TRACE();
if (this->closed)
{
MS_THROW_ERROR("closed");
}
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) == 0)
{
return;
}
if (this->repeat == 0u)
{
return;
}
const int err =
uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), this->repeat, this->repeat);
if (err != 0)
{
MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err));
}
}
void Timer::Restart()
......@@ -115,16 +137,22 @@ void Timer::Restart()
MS_TRACE();
if (this->closed)
{
MS_THROW_ERROR("closed");
}
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0)
{
Stop();
}
const int err =
uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), this->timeout, this->repeat);
if (err != 0)
{
MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err));
}
}
inline void Timer::OnUvTimer()
......
#include "common.hpp"
#include "RTC/RetransmissionBuffer.hpp"
#include "RTC/RtpPacket.hpp"
#include <catch2/catch.hpp>
#include <vector>
using namespace RTC;
// Class inheriting from RetransmissionBuffer so we can access its protected
// buffer member.
class MyRetransmissionBuffer : public RetransmissionBuffer
{
public:
struct VerificationItem
{
bool isPresent;
uint16_t sequenceNumber;
uint32_t timestamp;
};
public:
MyRetransmissionBuffer(uint16_t maxItems, uint32_t maxRetransmissionDelayMs, uint32_t clockRate)
: RetransmissionBuffer(maxItems, maxRetransmissionDelayMs, clockRate)
{
}
public:
void Insert(uint16_t seq, uint32_t timestamp)
{
// clang-format off
uint8_t rtpBuffer[] =
{
0b10000000, 0b01111011, 0b01010010, 0b00001110,
0b01011011, 0b01101011, 0b11001010, 0b10110101,
0, 0, 0, 2
};
// clang-format on
auto* packet = RtpPacket::Parse(rtpBuffer, sizeof(rtpBuffer));
packet->SetSequenceNumber(seq);
packet->SetTimestamp(timestamp);
std::shared_ptr<RtpPacket> sharedPacket;
RetransmissionBuffer::Insert(packet, sharedPacket);
}
void AssertBuffer(std::vector<VerificationItem> verificationBuffer)
{
REQUIRE(verificationBuffer.size() == this->buffer.size());
for (size_t idx{ 0u }; idx < verificationBuffer.size(); ++idx)
{
auto& verificationItem = verificationBuffer.at(idx);
auto* item = this->buffer.at(idx);
REQUIRE(verificationItem.isPresent == !!item);
if (item)
{
REQUIRE(verificationItem.sequenceNumber == item->sequenceNumber);
REQUIRE(verificationItem.timestamp == item->timestamp);
}
}
}
};
SCENARIO("RetransmissionBuffer", "[rtp][rtx]")
{
SECTION("proper packets received in order")
{
uint16_t maxItems{ 4 };
uint32_t maxRetransmissionDelayMs{ 2000u };
uint32_t clockRate{ 90000 };
MyRetransmissionBuffer myRetransmissionBuffer(maxItems, maxRetransmissionDelayMs, clockRate);
myRetransmissionBuffer.Insert(10001, 1000000000);
myRetransmissionBuffer.Insert(10002, 1000000000);
myRetransmissionBuffer.Insert(10003, 1000000200);
myRetransmissionBuffer.Insert(10004, 1000000200);
// clang-format off
myRetransmissionBuffer.AssertBuffer(
{
{ true, 10001, 1000000000 },
{ true, 10002, 1000000000 },
{ true, 10003, 1000000200 },
{ true, 10004, 1000000200 }
}
);
// clang-format on
}
SECTION("proper packets received out of order")
{
uint16_t maxItems{ 4 };
uint32_t maxRetransmissionDelayMs{ 2000u };
uint32_t clockRate{ 90000 };
MyRetransmissionBuffer myRetransmissionBuffer(maxItems, maxRetransmissionDelayMs, clockRate);
myRetransmissionBuffer.Insert(20004, 2000000200);
myRetransmissionBuffer.Insert(20001, 2000000000);
myRetransmissionBuffer.Insert(20003, 2000000200);
myRetransmissionBuffer.Insert(20002, 2000000000);
// clang-format off
myRetransmissionBuffer.AssertBuffer(
{
{ true, 20001, 2000000000 },
{ true, 20002, 2000000000 },
{ true, 20003, 2000000200 },
{ true, 20004, 2000000200 }
}
);
// clang-format on
}
SECTION("packet with too new sequence number produces buffer emptying")
{
uint16_t maxItems{ 4 };
uint32_t maxRetransmissionDelayMs{ 2000u };
uint32_t clockRate{ 90000 };
MyRetransmissionBuffer myRetransmissionBuffer(maxItems, maxRetransmissionDelayMs, clockRate);
myRetransmissionBuffer.Insert(30001, 3000000000);
myRetransmissionBuffer.Insert(30002, 3000000000);
myRetransmissionBuffer.Insert(30003, 3000000200);
myRetransmissionBuffer.Insert(40000, 3000003000);
// clang-format off
myRetransmissionBuffer.AssertBuffer(
{
{ true, 40000, 3000003000 }
}
);
// clang-format on
}
SECTION("blank slots are properly created")
{
uint16_t maxItems{ 10 };
uint32_t maxRetransmissionDelayMs{ 2000u };
uint32_t clockRate{ 90000 };
MyRetransmissionBuffer myRetransmissionBuffer(maxItems, maxRetransmissionDelayMs, clockRate);
myRetransmissionBuffer.Insert(40002, 4000000002);
// Packet must be discarded since its timestamp is lower than in seq 40002.
myRetransmissionBuffer.Insert(40003, 4000000001);
// Must produce 1 blank slot.
myRetransmissionBuffer.Insert(40004, 4000000004);
// Discarded (duplicated).
myRetransmissionBuffer.Insert(40002, 4000000002);
// Must produce 4 blank slot.
myRetransmissionBuffer.Insert(40008, 4000000008);
myRetransmissionBuffer.Insert(40006, 4000000006);
// Must produce 1 blank slot at the front.
myRetransmissionBuffer.Insert(40000, 4000000000);
// clang-format off
myRetransmissionBuffer.AssertBuffer(
{
{ true, 40000, 4000000000 },
{ false, 0, 0 },
{ true, 40002, 4000000002 },
{ false, 0, 0 },
{ true, 40004, 4000000004 },
{ false, 0, 0 },
{ true, 40006, 4000000006 },
{ false, 0, 0 },
{ true, 40008, 4000000008 }
}
);
// clang-format on
}
SECTION("packet with too old sequence number is discarded")
{
uint16_t maxItems{ 4 };
uint32_t maxRetransmissionDelayMs{ 2000u };
uint32_t clockRate{ 90000 };
MyRetransmissionBuffer myRetransmissionBuffer(maxItems, maxRetransmissionDelayMs, clockRate);
myRetransmissionBuffer.Insert(10001, 1000000001);
myRetransmissionBuffer.Insert(10002, 1000000002);
myRetransmissionBuffer.Insert(10003, 1000000003);
// Too old seq.
myRetransmissionBuffer.Insert(40000, 1000000000);
// clang-format off
myRetransmissionBuffer.AssertBuffer(
{
{ true, 10001, 1000000001 },
{ true, 10002, 1000000002 },
{ true, 10003, 1000000003 }
}
);
// clang-format on
}
SECTION("packet with too old timestamp is discarded")
{
uint16_t maxItems{ 4 };
uint32_t maxRetransmissionDelayMs{ 2000u };
uint32_t clockRate{ 90000 };
MyRetransmissionBuffer myRetransmissionBuffer(maxItems, maxRetransmissionDelayMs, clockRate);
auto maxDiffTs = static_cast<uint32_t>(maxRetransmissionDelayMs * clockRate / 1000);
myRetransmissionBuffer.Insert(10001, 1000000001);
myRetransmissionBuffer.Insert(10002, 1000000002);
myRetransmissionBuffer.Insert(10003, 1000000003);
// Too old timestamp (subtract 100 to avoid math issues).
myRetransmissionBuffer.Insert(10000, 1000000003 - maxDiffTs - 100);
// clang-format off
myRetransmissionBuffer.AssertBuffer(
{
{ true, 10001, 1000000001 },
{ true, 10002, 1000000002 },
{ true, 10003, 1000000003 }
}
);
// clang-format on
}
}
......@@ -376,10 +376,14 @@ SCENARIO("NACK and RTP packets retransmission", "[rtp][rtcp][nack]")
uint32_t clockRate = 90000;
uint32_t firstTs = 1533790901;
uint32_t diffTs = RtpStreamSend::MaxRetransmissionDelayForVideoMs * clockRate / 1000;
uint32_t secondTs = firstTs + diffTs;
// Make second packet arrive more than MaxRetransmissionDelayForVideoMs later.
uint32_t secondTs = firstTs + diffTs + 100;
// Send a third packet so it will clean old packets from the buffer.
uint32_t thirdTs = firstTs + (2 * diffTs);
auto* packet1 = CreateRtpPacket(rtpBuffer1, 21006, firstTs);
auto* packet2 = CreateRtpPacket(rtpBuffer2, 21007, secondTs);
auto* packet3 = CreateRtpPacket(rtpBuffer3, 21008, thirdTs);
// Create a RtpStreamSend instance.
TestRtpStreamListener testRtpStreamListener1;
......@@ -397,6 +401,7 @@ SCENARIO("NACK and RTP packets retransmission", "[rtp][rtcp][nack]")
// Receive all the packets.
SendRtpPacket({ { stream, params1.ssrc } }, packet1);
SendRtpPacket({ { stream, params1.ssrc } }, packet2);
SendRtpPacket({ { stream, params1.ssrc } }, packet3);
// Create a NACK item that request for all the packets.
RTCP::FeedbackRtpNackPacket nackPacket(0, params1.ssrc);
......
......@@ -19,15 +19,28 @@ int main(int argc, char* argv[])
if (std::getenv("MS_TEST_LOG_LEVEL"))
{
if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "debug")
{
logLevel = LogLevel::LOG_DEBUG;
}
else if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "warn")
{
logLevel = LogLevel::LOG_WARN;
}
else if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "error")
{
logLevel = LogLevel::LOG_ERROR;
}
}
Settings::configuration.logLevel = logLevel;
// Fill logTags based by reading ENVs.
// TODO: Add more on demand.
if (std::getenv("MS_TEST_LOG_TAG_RTP"))
{
Settings::configuration.logTags.rtp = true;
}
// Initialize static stuff.
DepLibUV::ClassInit();
DepOpenSSL::ClassInit();
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论