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 # 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 ### 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). * `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 @@ ...@@ -13,6 +13,7 @@
#include "RTC/RTCP/XrDelaySinceLastRr.hpp" #include "RTC/RTCP/XrDelaySinceLastRr.hpp"
#include "RTC/RTCP/XrReceiverReferenceTime.hpp" #include "RTC/RTCP/XrReceiverReferenceTime.hpp"
#include "RTC/RtpDictionaries.hpp" #include "RTC/RtpDictionaries.hpp"
#include "RTC/RtpPacket.hpp"
#include "RTC/RtxStream.hpp" #include "RTC/RtxStream.hpp"
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <string> #include <string>
...@@ -180,12 +181,18 @@ namespace RTC ...@@ -180,12 +181,18 @@ namespace RTC
Params params; Params params;
// Others. // Others.
// https://tools.ietf.org/html/rfc3550#appendix-A.1 stuff. // https://tools.ietf.org/html/rfc3550#appendix-A.1 stuff.
uint16_t maxSeq{ 0u }; // Highest seq. number seen. // Highest seq. number seen.
uint32_t cycles{ 0u }; // Shifted count of seq. number cycles. uint16_t maxSeq{ 0u };
uint32_t baseSeq{ 0u }; // Base seq number. // Shifted count of seq. number cycles.
uint32_t badSeq{ 0u }; // Last 'bad' seq number + 1. uint32_t cycles{ 0u };
uint32_t maxPacketTs{ 0u }; // Highest timestamp seen. // Base seq number.
uint64_t maxPacketMs{ 0u }; // When the packet with highest timestammp was seen. 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 }; uint32_t packetsLost{ 0u };
uint8_t fractionLost{ 0u }; uint8_t fractionLost{ 0u };
size_t packetsDiscarded{ 0u }; size_t packetsDiscarded{ 0u };
...@@ -195,12 +202,14 @@ namespace RTC ...@@ -195,12 +202,14 @@ namespace RTC
size_t nackPacketCount{ 0u }; size_t nackPacketCount{ 0u };
size_t pliCount{ 0u }; size_t pliCount{ 0u };
size_t firCount{ 0u }; size_t firCount{ 0u };
size_t repairedPriorScore{ 0u }; // Packets repaired at last interval for score calculation. // Packets repaired at last interval for score calculation.
size_t retransmittedPriorScore{ size_t repairedPriorScore{ 0u };
0u // Packets retransmitted at last interval for score calculation.
}; // Packets retransmitted at last interval for score calculation. size_t retransmittedPriorScore{ 0u };
uint64_t lastSenderReportNtpMs{ 0u }; // NTP timestamp in last Sender Report (in ms). // NTP timestamp in last Sender Report (in ms).
uint32_t lastSenderReportTs{ 0u }; // RTP timestamp in last Sender Report. uint64_t lastSenderReportNtpMs{ 0u };
// RTP timestamp in last Sender Report.
uint32_t lastSenderReportTs{ 0u };
float rtt{ 0 }; float rtt{ 0 };
bool hasRtt{ false }; bool hasRtt{ false };
// Instance of RtxStream. // Instance of RtxStream.
......
...@@ -93,24 +93,31 @@ namespace RTC ...@@ -93,24 +93,31 @@ namespace RTC
// Passed by argument. // Passed by argument.
unsigned int sendNackDelayMs{ 0u }; unsigned int sendNackDelayMs{ 0u };
// Others. // Others.
uint32_t expectedPrior{ 0u }; // Packets expected at last interval. // Packets expected at last interval.
uint32_t expectedPriorScore{ 0u }; // Packets expected at last interval for score calculation. uint32_t expectedPrior{ 0u };
uint32_t receivedPrior{ 0u }; // Packets received at last interval. // Packets expected at last interval for score calculation.
uint32_t receivedPriorScore{ 0u }; // Packets received at last interval for score calculation. uint32_t expectedPriorScore{ 0u };
uint32_t lastSrTimestamp{ 0u }; // The middle 32 bits out of 64 in the NTP // Packets received at last interval.
// timestamp received in the most recent uint32_t receivedPrior{ 0u };
// sender report. // Packets received at last interval for score calculation.
uint64_t lastSrReceived{ 0u }; // Wallclock time representing the most recent uint32_t receivedPriorScore{ 0u };
// sender report arrival. // The middle 32 bits out of 64 in the NTP timestamp received in the most
int32_t transit{ 0u }; // Relative transit time for prev packet. // 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 }; uint32_t jitter{ 0u };
uint8_t firSeqNumber{ 0u }; uint8_t firSeqNumber{ 0u };
uint32_t reportedPacketLost{ 0u }; uint32_t reportedPacketLost{ 0u };
std::unique_ptr<RTC::NackGenerator> nackGenerator; std::unique_ptr<RTC::NackGenerator> nackGenerator;
Timer* inactivityCheckPeriodicTimer{ nullptr }; Timer* inactivityCheckPeriodicTimer{ nullptr };
bool inactive{ false }; bool inactive{ false };
TransmissionCounter transmissionCounter; // Valid media + valid RTX. // Valid media + valid RTX.
RTC::RtpDataCounter mediaTransmissionCounter; // Just valid media. TransmissionCounter transmissionCounter;
// Just valid media.
RTC::RtpDataCounter mediaTransmissionCounter;
}; };
} // namespace RTC } // namespace RTC
......
...@@ -2,16 +2,14 @@ ...@@ -2,16 +2,14 @@
#define MS_RTC_RTP_STREAM_SEND_HPP #define MS_RTC_RTP_STREAM_SEND_HPP
#include "RTC/RateCalculator.hpp" #include "RTC/RateCalculator.hpp"
#include "RTC/RetransmissionBuffer.hpp"
#include "RTC/RtpStream.hpp" #include "RTC/RtpStream.hpp"
#include <deque>
namespace RTC namespace RTC
{ {
class RtpStreamSend : public RTC::RtpStream class RtpStreamSend : public RTC::RtpStream
{ {
public: public:
// Minimum retransmission buffer size (ms).
const static uint32_t MinRetransmissionDelayMs;
// Maximum retransmission buffer size for video (ms). // Maximum retransmission buffer size for video (ms).
const static uint32_t MaxRetransmissionDelayForVideoMs; const static uint32_t MaxRetransmissionDelayForVideoMs;
// Maximum retransmission buffer size for audio (ms). // Maximum retransmission buffer size for audio (ms).
...@@ -25,47 +23,6 @@ namespace RTC ...@@ -25,47 +23,6 @@ namespace RTC
RTC::RtpStreamSend* rtpStream, RTC::RtpPacket* packet) = 0; 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: public:
RtpStreamSend( RtpStreamSend(
RTC::RtpStreamSend::Listener* listener, RTC::RtpStream::Params& params, std::string& mid); RTC::RtpStreamSend::Listener* listener, RTC::RtpStream::Params& params, std::string& mid);
...@@ -93,25 +50,24 @@ namespace RTC ...@@ -93,25 +50,24 @@ namespace RTC
private: private:
void StorePacket(RTC::RtpPacket* packet, std::shared_ptr<RTC::RtpPacket>& sharedPacket); 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 FillRetransmissionContainer(uint16_t seq, uint16_t bitmask);
void UpdateScore(RTC::RTCP::ReceiverReport* report); void UpdateScore(RTC::RTCP::ReceiverReport* report);
private: private:
uint32_t lostPriorScore{ 0u }; // Packets lost at last interval for score calculation. // Packets lost at last interval for score calculation.
uint32_t sentPriorScore{ 0u }; // Packets sent at last interval for score calculation. uint32_t lostPriorScore{ 0u };
StorageItemBuffer storageItemBuffer; // Packets sent at last interval for score calculation.
uint32_t sentPriorScore{ 0u };
std::string mid; std::string mid;
uint32_t maxRetransmissionDelayMs;
uint32_t retransmissionBufferSize;
uint16_t rtxSeq{ 0u }; uint16_t rtxSeq{ 0u };
RTC::RtpDataCounter transmissionCounter; RTC::RtpDataCounter transmissionCounter;
uint32_t lastRrTimestamp{ 0u }; // The middle 32 bits out of 64 in the NTP RTC::RetransmissionBuffer* retransmissionBuffer{ nullptr };
// timestamp received in the most recent // The middle 32 bits out of 64 in the NTP timestamp received in the most
// receiver reference timestamp. // recent receiver reference timestamp.
uint64_t lastRrReceivedMs{ 0u }; // Wallclock time representing the most recent uint32_t lastRrTimestamp{ 0u };
// receiver reference timestamp arrival. // Wallclock time representing the most recent receiver reference timestamp
// arrival.
uint64_t lastRrReceivedMs{ 0u };
}; };
} // namespace RTC } // namespace RTC
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
#include <memory> // std::addressof() #include <memory> // std::addressof()
#ifdef _WIN32 #ifdef _WIN32
#include <winsock2.h> #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) #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
#include <BaseTsd.h> #include <BaseTsd.h>
typedef SSIZE_T ssize_t; typedef SSIZE_T ssize_t;
...@@ -25,15 +25,17 @@ typedef SSIZE_T ssize_t; ...@@ -25,15 +25,17 @@ typedef SSIZE_T ssize_t;
using ChannelReadCtx = void*; using ChannelReadCtx = void*;
using ChannelReadFreeFn = void (*)(uint8_t*, uint32_t, size_t); 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 (*)( using ChannelReadFn = ChannelReadFreeFn (*)(
uint8_t** /* message */, uint8_t** /* message */,
uint32_t* /* messageLen */, uint32_t* /* messageLen */,
size_t* /* messageCtx */, size_t* /* messageCtx */,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more // This is `uv_async_t` handle that can be called later with `uv_async_send()`
// data to read. // when there is more data to read.
const void* /* handle */, const void* /* handle */,
ChannelReadCtx /* ctx */); ChannelReadCtx /* ctx */
);
using ChannelWriteCtx = void*; using ChannelWriteCtx = void*;
using ChannelWriteFn = using ChannelWriteFn =
...@@ -41,7 +43,8 @@ using ChannelWriteFn = ...@@ -41,7 +43,8 @@ using ChannelWriteFn =
using PayloadChannelReadCtx = void*; using PayloadChannelReadCtx = void*;
using PayloadChannelReadFreeFn = void (*)(uint8_t*, uint32_t, size_t); 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 (*)( using PayloadChannelReadFn = PayloadChannelReadFreeFn (*)(
uint8_t** /* message */, uint8_t** /* message */,
uint32_t* /* messageLen */, uint32_t* /* messageLen */,
...@@ -49,8 +52,8 @@ using PayloadChannelReadFn = PayloadChannelReadFreeFn (*)( ...@@ -49,8 +52,8 @@ using PayloadChannelReadFn = PayloadChannelReadFreeFn (*)(
uint8_t** /* payload */, uint8_t** /* payload */,
uint32_t* /* payloadLen */, uint32_t* /* payloadLen */,
size_t* /* payloadCapacity */, size_t* /* payloadCapacity */,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more // This is `uv_async_t` handle that can be called later with `uv_async_send()`
// data to read. // when there is more data to read.
const void* /* handle */, const void* /* handle */,
PayloadChannelReadCtx /* ctx */); PayloadChannelReadCtx /* ctx */);
......
...@@ -84,6 +84,7 @@ common_sources = [ ...@@ -84,6 +84,7 @@ common_sources = [
'src/RTC/PortManager.cpp', 'src/RTC/PortManager.cpp',
'src/RTC/Producer.cpp', 'src/RTC/Producer.cpp',
'src/RTC/RateCalculator.cpp', 'src/RTC/RateCalculator.cpp',
'src/RTC/RetransmissionBuffer.cpp',
'src/RTC/Router.cpp', 'src/RTC/Router.cpp',
'src/RTC/RtpListener.cpp', 'src/RTC/RtpListener.cpp',
'src/RTC/RtpObserver.cpp', 'src/RTC/RtpObserver.cpp',
...@@ -287,6 +288,7 @@ mediasoup_worker_test = executable( ...@@ -287,6 +288,7 @@ mediasoup_worker_test = executable(
'test/src/RTC/TestKeyFrameRequestManager.cpp', 'test/src/RTC/TestKeyFrameRequestManager.cpp',
'test/src/RTC/TestNackGenerator.cpp', 'test/src/RTC/TestNackGenerator.cpp',
'test/src/RTC/TestRateCalculator.cpp', 'test/src/RTC/TestRateCalculator.cpp',
'test/src/RTC/TestRetransmissionBuffer.cpp',
'test/src/RTC/TestRtpPacket.cpp', 'test/src/RTC/TestRtpPacket.cpp',
'test/src/RTC/TestRtpPacketH264Svc.cpp', 'test/src/RTC/TestRtpPacketH264Svc.cpp',
'test/src/RTC/TestRtpStreamSend.cpp', 'test/src/RTC/TestRtpStreamSend.cpp',
......
#define MS_CLASS "RTC::RetransmissionBuffer"
// #define MS_LOG_DEV_LEVEL 3
#include "RTC/RetransmissionBuffer.hpp"
#include "Logger.hpp"
#include "RTC/SeqManager.hpp"
namespace RTC
{
/* Instance methods. */
RetransmissionBuffer::RetransmissionBuffer(
uint16_t maxItems, uint32_t maxRetransmissionDelayMs, uint32_t clockRate)
: maxItems(maxItems), maxRetransmissionDelayMs(maxRetransmissionDelayMs), clockRate(clockRate)
{
MS_TRACE();
MS_ASSERT(maxItems > 0u, "maxItems must be greater than 0");
}
RetransmissionBuffer::~RetransmissionBuffer()
{
MS_TRACE();
Clear();
}
RetransmissionBuffer::Item* RetransmissionBuffer::Get(uint16_t seq) const
{
MS_TRACE();
if (this->buffer.empty())
{
return nullptr;
}
if (RTC::SeqManager<uint16_t>::IsSeqLowerThan(seq, this->startSeq))
{
return nullptr;
}
auto idx = static_cast<uint16_t>(seq - this->startSeq);
if (idx > static_cast<uint16_t>(this->buffer.size() - 1))
{
return nullptr;
}
return this->buffer.at(idx);
}
/**
* This method tries to insert given packet into the buffer. Here we assume
* that packet seq number is legitimate according to the content of the buffer.
* We discard the packet if too old and also discard it if its timestamp does
* not properly fit (by ensuring that elements in the buffer are not only
* ordered by increasing seq but also that their timestamp are incremental).
*/
void RetransmissionBuffer::Insert(RTC::RtpPacket* packet, std::shared_ptr<RTC::RtpPacket>& sharedPacket)
{
MS_TRACE();
auto ssrc = packet->GetSsrc();
auto seq = packet->GetSequenceNumber();
auto timestamp = packet->GetTimestamp();
MS_DEBUG_DEV("packet [seq:%" PRIu16 ", timestamp:%" PRIu32 "]", seq, timestamp);
// Buffer is empty, so just insert new item.
if (this->buffer.empty())
{
MS_DEBUG_DEV("buffer empty [seq:%" PRIu16 ", timestamp:%" PRIu32 "]", seq, timestamp);
auto* item = new Item();
this->buffer.push_back(FillItem(item, packet, sharedPacket));
// Packet's seq number becomes startSeq.
this->startSeq = seq;
return;
}
// Clear too old packets in the buffer.
ClearTooOld();
auto* oldestItem = GetOldest();
auto* newestItem = GetNewest();
MS_ASSERT(oldestItem != nullptr, "oldest item doesn't exist");
MS_ASSERT(newestItem != nullptr, "newest item doesn't exist");
// Packet arrived in order (its seq is higher than seq of the newest stored
// packet) so will become the newest one in the buffer.
if (RTC::SeqManager<uint16_t>::IsSeqHigherThan(seq, newestItem->sequenceNumber))
{
MS_DEBUG_DEV("packet in order [seq:%" PRIu16 ", timestamp:%" PRIu32 "]", seq, timestamp);
// Ensure that the timestamp of the packet is equal or higher than the
// timestamp of the newest stored packet.
if (RTC::SeqManager<uint32_t>::IsSeqLowerThan(timestamp, newestItem->timestamp))
{
MS_WARN_TAG(
rtp,
"packet has higher seq but less timestamp than newest packet in the buffer, discarding it [ssrc:%" PRIu32
", seq:%" PRIu16 ", timestamp:%" PRIu32 "]",
ssrc,
seq,
timestamp);
return;
}
// Calculate how many blank slots it would be necessary to add when
// pushing new item to the back of the buffer.
auto numBlankSlots = static_cast<uint16_t>(seq - newestItem->sequenceNumber - 1);
// We may have to remove oldest items not to exceed the maximum size of
// the buffer.
if (this->buffer.size() + numBlankSlots + 1 > this->maxItems)
{
auto numItemsToRemove =
static_cast<uint16_t>(this->buffer.size() + numBlankSlots + 1 - this->maxItems);
// If num of items to be removed exceed buffer size minus one (needed to
// allocate current packet) then we must clear the entire buffer.
if (numItemsToRemove > this->buffer.size() - 1)
{
MS_WARN_TAG(
rtp,
"packet has too high seq and forces buffer emptying [ssrc:%" PRIu32 ", seq:%" PRIu16
", timestamp:%" PRIu32 "]",
ssrc,
seq,
timestamp);
numBlankSlots = 0u;
Clear();
}
else
{
MS_DEBUG_DEV(
"calling RemoveOldest(%" PRIu16 ") [bufferSize:%zu, numBlankSlots:%" PRIu16
", maxItems:%" PRIu16 "]",
numItemsToRemove,
this->buffer.size(),
numBlankSlots,
this->maxItems);
RemoveOldest(numItemsToRemove);
}
}
// Push blank slots to the back.
for (uint16_t i{ 0u }; i < numBlankSlots; ++i)
{
this->buffer.push_back(nullptr);
}
// Push the packet, which becomes the newest one in the buffer.
auto* item = new Item();
this->buffer.push_back(FillItem(item, packet, sharedPacket));
}
// Packet arrived out order and its seq is less than seq of the oldest
// stored packet, so will become the oldest one in the buffer.
else if (RTC::SeqManager<uint16_t>::IsSeqLowerThan(seq, oldestItem->sequenceNumber))
{
MS_DEBUG_DEV(
"packet out of order and older than oldest packet in the buffer [seq:%" PRIu16
", timestamp:%" PRIu32 "]",
seq,
timestamp);
// Ensure that packet is not too old to be stored.
if (IsTooOld(timestamp, newestItem->timestamp))
{
MS_WARN_DEV(
"packet too old, discarding it [seq:%" PRIu16 ", timestamp:%" PRIu32 "]", seq, timestamp);
return;
}
// Ensure that the timestamp of the packet is equal or less than the
// timestamp of the oldest stored packet.
if (RTC::SeqManager<uint32_t>::IsSeqHigherThan(timestamp, oldestItem->timestamp))
{
MS_WARN_TAG(
rtp,
"packet has less seq but higher timestamp than oldest packet in the buffer, discarding it [ssrc:%" PRIu32
", seq:%" PRIu16 ", timestamp:%" PRIu32 "]",
ssrc,
seq,
timestamp);
return;
}
// Calculate how many blank slots it would be necessary to add when
// pushing new item to the fton of the buffer.
auto numBlankSlots = static_cast<uint16_t>(oldestItem->sequenceNumber - seq - 1);
// If adding this packet (and needed blank slots) to the front makes the
// buffer exceed its max size, discard this packet.
if (this->buffer.size() + numBlankSlots + 1 > this->maxItems)
{
MS_WARN_TAG(
rtp,
"discarding received old packet to not exceed max buffer size [ssrc:%" PRIu32
", seq:%" PRIu16 ", timestamp:%" PRIu32 "]",
ssrc,
seq,
timestamp);
return;
}
// Push blank slots to the front.
for (uint16_t i{ 0u }; i < numBlankSlots; ++i)
{
this->buffer.push_front(nullptr);
}
// Insert the packet, which becomes the oldest one in the buffer.
auto* item = new Item();
this->buffer.push_front(FillItem(item, packet, sharedPacket));
// Packet's seq number becomes startSeq.
this->startSeq = seq;
}
// Otherwise packet must be inserted between oldest and newest stored items
// so there is already an allocated slot for it.
else
{
MS_DEBUG_DEV(
"packet out of order and in between oldest and newest packets in the buffer [seq:%" PRIu16
", timestamp:%" PRIu32 "]",
seq,
timestamp);
// Let's check if an item already exist in same position. If so, assume
// it's duplicated.
auto* item = Get(seq);
if (item)
{
MS_DEBUG_DEV(
"packet already in the buffer, discarding [seq:%" PRIu16 ", timestamp:%" PRIu32 "]",
seq,
timestamp);
return;
}
// idx is the intended position of the received packet in the buffer.
auto idx = static_cast<uint16_t>(seq - this->startSeq);
// Validate that packet timestamp is equal or higher than the timestamp of
// the immediate older packet (if any).
for (auto idx2 = static_cast<int32_t>(idx - 1); idx2 >= 0; --idx2)
{
auto* olderItem = this->buffer.at(idx2);
// Blank slot, continue.
if (!olderItem)
{
continue;
}
// We are done.
if (timestamp >= olderItem->timestamp)
{
break;
}
else
{
MS_WARN_TAG(
rtp,
"packet timestamp is less than timestamp of immediate older packet in the buffer, discarding it [ssrc:%" PRIu32
", seq:%" PRIu16 ", timestamp:%" PRIu32 "]",
ssrc,
seq,
timestamp);
return;
}
}
// Validate that packet timestamp is equal or less than the timestamp of
// the immediate newer packet (if any).
for (auto idx2 = static_cast<size_t>(idx + 1); idx2 < this->buffer.size(); ++idx2)
{
auto* newerItem = this->buffer.at(idx2);
// Blank slot, continue.
if (!newerItem)
{
continue;
}
// We are done.
if (timestamp <= newerItem->timestamp)
{
break;
}
else
{
MS_WARN_TAG(
rtp,
"packet timestamp is higher than timestamp of immediate newer packet in the buffer, discarding it [ssrc:%" PRIu32
", seq:%" PRIu16 ", timestamp:%" PRIu32 "]",
ssrc,
seq,
timestamp);
return;
}
}
// Store the packet.
item = new Item();
this->buffer[idx] = FillItem(item, packet, sharedPacket);
}
MS_ASSERT(
this->buffer.size() <= this->maxItems,
"buffer contains %zu items (more than %" PRIu16 " max items)",
this->buffer.size(),
this->maxItems);
}
void RetransmissionBuffer::Clear()
{
MS_TRACE();
for (auto* item : this->buffer)
{
if (!item)
{
continue;
}
// Reset the stored item (decrease RTP packet shared pointer counter).
item->Reset();
delete item;
}
this->buffer.clear();
this->startSeq = 0u;
}
void RetransmissionBuffer::Dump() const
{
MS_TRACE();
MS_DUMP("<RetransmissionBuffer>");
MS_DUMP(" buffer [size:%zu, maxSize:%" PRIu16 "]", this->buffer.size(), this->maxItems);
if (this->buffer.size() > 0)
{
const auto* oldestItem = GetOldest();
const auto* newestItem = GetNewest();
MS_DUMP(
" oldest item [seq:%" PRIu16 ", timestamp:%" PRIu32 "]",
oldestItem->sequenceNumber,
oldestItem->timestamp);
MS_DUMP(
" newest item [seq:%" PRIu16 ", timestamp:%" PRIu32 "]",
newestItem->sequenceNumber,
newestItem->timestamp);
MS_DUMP(
" buffer window: %" PRIu32 "ms",
static_cast<uint32_t>(newestItem->timestamp * 1000 / this->clockRate) -
static_cast<uint32_t>(oldestItem->timestamp * 1000 / this->clockRate));
}
MS_DUMP("</RetransmissionBuffer>");
}
RetransmissionBuffer::Item* RetransmissionBuffer::GetOldest() const
{
MS_TRACE();
return this->Get(this->startSeq);
}
RetransmissionBuffer::Item* RetransmissionBuffer::GetNewest() const
{
MS_TRACE();
return this->Get(this->startSeq + this->buffer.size() - 1);
}
void RetransmissionBuffer::RemoveOldest()
{
MS_TRACE();
if (this->buffer.empty())
{
return;
}
auto* item = this->buffer.at(0);
// Reset the stored item (decrease RTP packet shared pointer counter).
item->Reset();
delete item;
this->buffer.pop_front();
this->startSeq++;
MS_DEBUG_DEV("removed 1 item from the front");
// Remove all nullptr elements from the beginning of the buffer.
// NOTE: Calling front on an empty container is undefined.
size_t numItemsRemoved{ 0u };
while (!this->buffer.empty() && this->buffer.front() == nullptr)
{
this->buffer.pop_front();
this->startSeq++;
++numItemsRemoved;
}
if (numItemsRemoved)
{
MS_DEBUG_DEV("removed 1 blank slot from the front");
}
// If we emptied the full buffer, reset startSeq.
if (this->buffer.empty())
{
this->startSeq = 0u;
}
}
void RetransmissionBuffer::RemoveOldest(uint16_t numItems)
{
MS_TRACE();
MS_ASSERT(
numItems <= this->buffer.size(),
"attempting to remove more items than current buffer size [numItems:%" PRIu16
", bufferSize:%zu]",
numItems,
this->buffer.size());
auto intendedBufferSize = this->buffer.size() - numItems;
while (this->buffer.size() > intendedBufferSize)
{
RemoveOldest();
}
}
void RetransmissionBuffer::ClearTooOld()
{
MS_TRACE();
const auto* newestItem = GetNewest();
if (!newestItem)
{
return;
}
RetransmissionBuffer::Item* oldestItem{ nullptr };
// Go through all buffer items starting with the first and free all items
// that contain too old packets.
while ((oldestItem = GetOldest()))
{
if (IsTooOld(oldestItem->timestamp, newestItem->timestamp))
{
RemoveOldest();
}
// If current oldest stored packet is not too old, exit the loop since we
// know that packets stored after it are guaranteed to be newer.
else
{
break;
}
}
}
bool RetransmissionBuffer::IsTooOld(uint32_t timestamp, uint32_t newestTimestamp) const
{
MS_TRACE();
if (RTC::SeqManager<uint32_t>::IsSeqHigherThan(timestamp, newestTimestamp))
{
return false;
}
const int64_t diffTs = newestTimestamp - timestamp;
return static_cast<uint32_t>(diffTs * 1000 / this->clockRate) > this->maxRetransmissionDelayMs;
}
RetransmissionBuffer::Item* RetransmissionBuffer::FillItem(
RetransmissionBuffer::Item* item,
RTC::RtpPacket* packet,
std::shared_ptr<RTC::RtpPacket>& sharedPacket) const
{
MS_TRACE();
// Store original packet into the item. Only clone once and only if
// necessary.
//
// NOTE: This must be done BEFORE assigning item->packet = sharedPacket,
// otherwise the value being copied in item->packet will remain nullptr.
// This is because we are copying an **empty** shared_ptr into another
// shared_ptr (item->packet), so future value assigned via reset() in the
// former doesn't update the value in the copy.
if (!sharedPacket.get())
{
sharedPacket.reset(packet->Clone());
}
// Store original packet and some extra info into the item.
item->packet = sharedPacket;
item->ssrc = packet->GetSsrc();
item->sequenceNumber = packet->GetSequenceNumber();
item->timestamp = packet->GetTimestamp();
return item;
}
void RetransmissionBuffer::Item::Reset()
{
MS_TRACE();
this->packet.reset();
this->ssrc = 0u;
this->sequenceNumber = 0u;
this->timestamp = 0u;
this->resentAtMs = 0u;
this->sentTimes = 0u;
}
} // namespace RTC
...@@ -41,11 +41,15 @@ namespace RTC ...@@ -41,11 +41,15 @@ namespace RTC
// Sanity check. Do not allow spatial layers higher than defined. // Sanity check. Do not allow spatial layers higher than defined.
if (spatialLayer > this->spatialLayerCounters.size() - 1) if (spatialLayer > this->spatialLayerCounters.size() - 1)
{
spatialLayer = this->spatialLayerCounters.size() - 1; spatialLayer = this->spatialLayerCounters.size() - 1;
}
// Sanity check. Do not allow temporal layers higher than defined. // Sanity check. Do not allow temporal layers higher than defined.
if (temporalLayer > this->spatialLayerCounters[0].size() - 1) if (temporalLayer > this->spatialLayerCounters[0].size() - 1)
{
temporalLayer = this->spatialLayerCounters[0].size() - 1; temporalLayer = this->spatialLayerCounters[0].size() - 1;
}
auto& counter = this->spatialLayerCounters[spatialLayer][temporalLayer]; auto& counter = this->spatialLayerCounters[spatialLayer][temporalLayer];
...@@ -82,7 +86,9 @@ namespace RTC ...@@ -82,7 +86,9 @@ namespace RTC
auto& counter = this->spatialLayerCounters[spatialLayer][temporalLayer]; auto& counter = this->spatialLayerCounters[spatialLayer][temporalLayer];
if (counter.GetBitrate(nowMs) == 0) if (counter.GetBitrate(nowMs) == 0)
{
return 0u; return 0u;
}
uint32_t rate{ 0u }; uint32_t rate{ 0u };
...@@ -191,7 +197,9 @@ namespace RTC ...@@ -191,7 +197,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
if (this->params.useNack) if (this->params.useNack)
{
this->nackGenerator.reset(new RTC::NackGenerator(this, this->sendNackDelayMs)); this->nackGenerator.reset(new RTC::NackGenerator(this, this->sendNackDelayMs));
}
// Run the RTP inactivity periodic timer (use a different timeout if DTX is // Run the RTP inactivity periodic timer (use a different timeout if DTX is
// enabled). // enabled).
...@@ -199,10 +207,14 @@ namespace RTC ...@@ -199,10 +207,14 @@ namespace RTC
this->inactive = false; this->inactive = false;
if (!this->params.useDtx) if (!this->params.useDtx)
{
this->inactivityCheckPeriodicTimer->Start(InactivityCheckInterval); this->inactivityCheckPeriodicTimer->Start(InactivityCheckInterval);
}
else else
{
this->inactivityCheckPeriodicTimer->Start(InactivityCheckIntervalWithDtx); this->inactivityCheckPeriodicTimer->Start(InactivityCheckIntervalWithDtx);
} }
}
RtpStreamRecv::~RtpStreamRecv() RtpStreamRecv::~RtpStreamRecv()
{ {
...@@ -256,7 +268,9 @@ namespace RTC ...@@ -256,7 +268,9 @@ namespace RTC
// Process the packet at codec level. // Process the packet at codec level.
if (packet->GetPayloadType() == GetPayloadType()) if (packet->GetPayloadType() == GetPayloadType())
{
RTC::Codecs::Tools::ProcessRtpPacket(packet, GetMimeType()); RTC::Codecs::Tools::ProcessRtpPacket(packet, GetMimeType());
}
// Pass the packet to the NackGenerator. // Pass the packet to the NackGenerator.
if (this->params.useNack) if (this->params.useNack)
...@@ -295,7 +309,9 @@ namespace RTC ...@@ -295,7 +309,9 @@ namespace RTC
// Restart the inactivityCheckPeriodicTimer. // Restart the inactivityCheckPeriodicTimer.
if (this->inactivityCheckPeriodicTimer) if (this->inactivityCheckPeriodicTimer)
{
this->inactivityCheckPeriodicTimer->Restart(); this->inactivityCheckPeriodicTimer->Restart();
}
return true; return true;
} }
...@@ -376,7 +392,9 @@ namespace RTC ...@@ -376,7 +392,9 @@ namespace RTC
// Process the packet at codec level. // Process the packet at codec level.
if (packet->GetPayloadType() == GetPayloadType()) if (packet->GetPayloadType() == GetPayloadType())
{
RTC::Codecs::Tools::ProcessRtpPacket(packet, GetMimeType()); RTC::Codecs::Tools::ProcessRtpPacket(packet, GetMimeType());
}
// Mark the packet as retransmitted. // Mark the packet as retransmitted.
RTC::RtpStream::PacketRetransmitted(packet); RTC::RtpStream::PacketRetransmitted(packet);
...@@ -401,7 +419,9 @@ namespace RTC ...@@ -401,7 +419,9 @@ namespace RTC
// Restart the inactivityCheckPeriodicTimer. // Restart the inactivityCheckPeriodicTimer.
if (this->inactivityCheckPeriodicTimer) if (this->inactivityCheckPeriodicTimer)
{
this->inactivityCheckPeriodicTimer->Restart(); this->inactivityCheckPeriodicTimer->Restart();
}
return true; return true;
} }
...@@ -422,8 +442,10 @@ namespace RTC ...@@ -422,8 +442,10 @@ namespace RTC
->OnRtpStreamNeedWorstRemoteFractionLost(this, worstRemoteFractionLost); ->OnRtpStreamNeedWorstRemoteFractionLost(this, worstRemoteFractionLost);
if (worstRemoteFractionLost > 0) if (worstRemoteFractionLost > 0)
{
MS_DEBUG_TAG(rtcp, "using worst remote fraction lost:%" PRIu8, worstRemoteFractionLost); MS_DEBUG_TAG(rtcp, "using worst remote fraction lost:%" PRIu8, worstRemoteFractionLost);
} }
}
auto* report = new RTC::RTCP::ReceiverReport(); auto* report = new RTC::RTCP::ReceiverReport();
...@@ -435,9 +457,13 @@ namespace RTC ...@@ -435,9 +457,13 @@ namespace RTC
auto expected = GetExpectedPackets(); auto expected = GetExpectedPackets();
if (expected > this->mediaTransmissionCounter.GetPacketCount()) if (expected > this->mediaTransmissionCounter.GetPacketCount())
{
this->packetsLost = expected - this->mediaTransmissionCounter.GetPacketCount(); this->packetsLost = expected - this->mediaTransmissionCounter.GetPacketCount();
}
else else
{
this->packetsLost = 0u; this->packetsLost = 0u;
}
// Calculate Fraction Lost. // Calculate Fraction Lost.
const uint32_t expectedInterval = expected - this->expectedPrior; const uint32_t expectedInterval = expected - this->expectedPrior;
...@@ -452,9 +478,13 @@ namespace RTC ...@@ -452,9 +478,13 @@ namespace RTC
const int32_t lostInterval = expectedInterval - receivedInterval; const int32_t lostInterval = expectedInterval - receivedInterval;
if (expectedInterval == 0 || lostInterval <= 0) if (expectedInterval == 0 || lostInterval <= 0)
{
this->fractionLost = 0; this->fractionLost = 0;
}
else else
{
this->fractionLost = std::round((static_cast<double>(lostInterval << 8) / expectedInterval)); this->fractionLost = std::round((static_cast<double>(lostInterval << 8) / expectedInterval));
}
// Worst remote fraction lost is not worse than local one. // Worst remote fraction lost is not worse than local one.
if (worstRemoteFractionLost <= this->fractionLost) if (worstRemoteFractionLost <= this->fractionLost)
...@@ -505,7 +535,9 @@ namespace RTC ...@@ -505,7 +535,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
if (HasRtx()) if (HasRtx())
{
return this->rtxStream->GetRtcpReceiverReport(); return this->rtxStream->GetRtcpReceiverReport();
}
return nullptr; return nullptr;
} }
...@@ -536,8 +568,10 @@ namespace RTC ...@@ -536,8 +568,10 @@ namespace RTC
MS_TRACE(); MS_TRACE();
if (HasRtx()) if (HasRtx())
{
this->rtxStream->ReceiveRtcpSenderReport(report); this->rtxStream->ReceiveRtcpSenderReport(report);
} }
}
void RtpStreamRecv::ReceiveRtcpXrDelaySinceLastRr(RTC::RTCP::DelaySinceLastRr::SsrcInfo* ssrcInfo) void RtpStreamRecv::ReceiveRtcpXrDelaySinceLastRr(RTC::RTCP::DelaySinceLastRr::SsrcInfo* ssrcInfo)
{ {
...@@ -563,19 +597,25 @@ namespace RTC ...@@ -563,19 +597,25 @@ namespace RTC
// If no Receiver Extended Report was received by the remote endpoint yet, // If no Receiver Extended Report was received by the remote endpoint yet,
// ignore lastRr and dlrr values in the Sender Extended Report. // ignore lastRr and dlrr values in the Sender Extended Report.
if (lastRr && dlrr && (compactNtp > dlrr + lastRr)) if (lastRr && dlrr && (compactNtp > dlrr + lastRr))
{
rtt = compactNtp - dlrr - lastRr; rtt = compactNtp - dlrr - lastRr;
}
// RTT in milliseconds. // RTT in milliseconds.
this->rtt = static_cast<float>(rtt >> 16) * 1000; this->rtt = static_cast<float>(rtt >> 16) * 1000;
this->rtt += (static_cast<float>(rtt & 0x0000FFFF) / 65536) * 1000; this->rtt += (static_cast<float>(rtt & 0x0000FFFF) / 65536) * 1000;
if (this->rtt > 0.0f) if (this->rtt > 0.0f)
{
this->hasRtt = true; this->hasRtt = true;
}
// Tell it to the NackGenerator. // Tell it to the NackGenerator.
if (this->params.useNack) if (this->params.useNack)
{
this->nackGenerator->UpdateRtt(static_cast<uint32_t>(this->rtt)); this->nackGenerator->UpdateRtt(static_cast<uint32_t>(this->rtt));
} }
}
void RtpStreamRecv::RequestKeyFrame() void RtpStreamRecv::RequestKeyFrame()
{ {
...@@ -620,10 +660,14 @@ namespace RTC ...@@ -620,10 +660,14 @@ namespace RTC
MS_TRACE(); MS_TRACE();
if (this->inactivityCheckPeriodicTimer) if (this->inactivityCheckPeriodicTimer)
{
this->inactivityCheckPeriodicTimer->Stop(); this->inactivityCheckPeriodicTimer->Stop();
}
if (this->params.useNack) if (this->params.useNack)
{
this->nackGenerator->Reset(); this->nackGenerator->Reset();
}
// Reset jitter. // Reset jitter.
this->transit = 0; this->transit = 0;
...@@ -635,15 +679,19 @@ namespace RTC ...@@ -635,15 +679,19 @@ namespace RTC
MS_TRACE(); MS_TRACE();
if (this->inactivityCheckPeriodicTimer && !this->inactive) if (this->inactivityCheckPeriodicTimer && !this->inactive)
{
this->inactivityCheckPeriodicTimer->Restart(); this->inactivityCheckPeriodicTimer->Restart();
} }
}
void RtpStreamRecv::CalculateJitter(uint32_t rtpTimestamp) void RtpStreamRecv::CalculateJitter(uint32_t rtpTimestamp)
{ {
MS_TRACE(); MS_TRACE();
if (this->params.clockRate == 0u) if (this->params.clockRate == 0u)
{
return; return;
}
// NOTE: Based on https://github.com/versatica/mediasoup/issues/1018. // NOTE: Based on https://github.com/versatica/mediasoup/issues/1018.
auto transit = static_cast<int>( auto transit = static_cast<int>(
...@@ -661,7 +709,9 @@ namespace RTC ...@@ -661,7 +709,9 @@ namespace RTC
this->transit = transit; this->transit = transit;
if (d < 0) if (d < 0)
{
d = -d; d = -d;
}
this->jitter += (1. / 16.) * (static_cast<double>(d) - this->jitter); this->jitter += (1. / 16.) * (static_cast<double>(d) - this->jitter);
} }
...@@ -686,9 +736,13 @@ namespace RTC ...@@ -686,9 +736,13 @@ namespace RTC
uint32_t lost; uint32_t lost;
if (expected < received) if (expected < received)
{
lost = 0; lost = 0;
}
else else
{
lost = expected - received; lost = expected - received;
}
// Calculate number of packets repaired in this interval. // Calculate number of packets repaired in this interval.
const auto totalRepaired = this->packetsRepaired; const auto totalRepaired = this->packetsRepaired;
...@@ -703,7 +757,9 @@ namespace RTC ...@@ -703,7 +757,9 @@ namespace RTC
this->retransmittedPriorScore = totatRetransmitted; this->retransmittedPriorScore = totatRetransmitted;
if (this->inactive) if (this->inactive)
{
return; return;
}
// We didn't expect more packets to come. // We didn't expect more packets to come.
if (expected == 0) if (expected == 0)
...@@ -714,7 +770,9 @@ namespace RTC ...@@ -714,7 +770,9 @@ namespace RTC
} }
if (lost > received) if (lost > received)
{
lost = received; lost = received;
}
if (repaired > lost) if (repaired > lost)
{ {
...@@ -754,7 +812,9 @@ namespace RTC ...@@ -754,7 +812,9 @@ namespace RTC
MS_ASSERT(retransmitted >= repaired, "repaired packets cannot be more than retransmitted ones"); MS_ASSERT(retransmitted >= repaired, "repaired packets cannot be more than retransmitted ones");
if (retransmitted > 0) if (retransmitted > 0)
{
repairedWeight *= static_cast<float>(repaired) / retransmitted; repairedWeight *= static_cast<float>(repaired) / retransmitted;
}
lost -= repaired * repairedWeight; lost -= repaired * repairedWeight;
...@@ -826,7 +886,9 @@ namespace RTC ...@@ -826,7 +886,9 @@ namespace RTC
uint16_t shift = *it - seq - 1; uint16_t shift = *it - seq - 1;
if (shift > 15) if (shift > 15)
{
break; break;
}
bitmask |= (1 << shift); bitmask |= (1 << shift);
++it; ++it;
......
...@@ -11,163 +11,19 @@ namespace RTC ...@@ -11,163 +11,19 @@ namespace RTC
{ {
/* Static. */ /* Static. */
// Limit retransmission buffer max size to 2500 items.
static constexpr size_t RetransmissionBufferMaxItems{ 2500u };
// 17: 16 bit mask + the initial sequence number. // 17: 16 bit mask + the initial sequence number.
static constexpr size_t MaxRequestedPackets{ 17u }; static constexpr size_t MaxRequestedPackets{ 17u };
thread_local static std::vector<RTC::RtpStreamSend::StorageItem*> RetransmissionContainer( thread_local static std::vector<RTC::RetransmissionBuffer::Item*> RetransmissionContainer(
MaxRequestedPackets + 1); MaxRequestedPackets + 1);
static constexpr uint32_t DefaultRtt{ 100u }; static constexpr uint32_t DefaultRtt{ 100u };
static constexpr uint16_t MaxSeq = std::numeric_limits<uint16_t>::max();
/* Class Static. */ /* Class Static. */
const uint32_t RtpStreamSend::MinRetransmissionDelayMs{ 200u };
const uint32_t RtpStreamSend::MaxRetransmissionDelayForVideoMs{ 2000u }; const uint32_t RtpStreamSend::MaxRetransmissionDelayForVideoMs{ 2000u };
const uint32_t RtpStreamSend::MaxRetransmissionDelayForAudioMs{ 1000u }; const uint32_t RtpStreamSend::MaxRetransmissionDelayForAudioMs{ 1000u };
void RtpStreamSend::StorageItem::Reset()
{
MS_TRACE();
this->packet.reset();
this->ssrc = 0;
this->sequenceNumber = 0;
this->timestamp = 0;
this->resentAtMs = 0;
this->sentTimes = 0;
}
RtpStreamSend::StorageItem* RtpStreamSend::StorageItemBuffer::GetFirst() const
{
auto* storageItem = this->Get(this->startSeq);
MS_ASSERT(storageItem, "first storage item is missing");
MS_ASSERT(storageItem->packet, "storage item does not contain original packet");
return storageItem;
}
RtpStreamSend::StorageItem* RtpStreamSend::StorageItemBuffer::Get(uint16_t seq) const
{
if (RTC::SeqManager<uint16_t>::IsSeqLowerThan(seq, this->startSeq))
{
return nullptr;
}
auto idx{ static_cast<uint16_t>(seq - this->startSeq) };
if (this->buffer.empty() || idx > static_cast<uint16_t>(this->buffer.size() - 1))
{
return nullptr;
}
return this->buffer.at(idx);
}
size_t RtpStreamSend::StorageItemBuffer::GetBufferSize() const
{
return this->buffer.size();
}
void RtpStreamSend::StorageItemBuffer::Insert(uint16_t seq, StorageItem* storageItem)
{
if (this->buffer.empty())
{
this->startSeq = seq;
this->buffer.push_back(storageItem);
}
// Packet sequence number is higher than startSeq.
else if (RTC::SeqManager<uint16_t>::IsSeqHigherThan(seq, this->startSeq))
{
auto idx{ static_cast<uint16_t>(seq - this->startSeq) };
// Packet arrived out of order, so we already have a slot allocated for it.
if (idx <= static_cast<uint16_t>(this->buffer.size() - 1))
{
MS_ASSERT(this->buffer[idx] == nullptr, "must insert into empty slot");
this->buffer[idx] = storageItem;
}
else
{
// Calculate how many elements would it be necessary to add when pushing new item
// to the back of the deque.
auto addToBack = static_cast<uint16_t>(seq - (this->startSeq + this->buffer.size() - 1));
// Packets can arrive out of order, add blank slots.
for (uint16_t i{ 1 }; i < addToBack; ++i)
{
this->buffer.push_back(nullptr);
}
this->buffer.push_back(storageItem);
}
}
// Packet sequence number is the same or lower than startSeq.
else
{
// Calculate how many elements would it be necessary to add when pushing new item
// to the front of the deque.
auto addToFront = static_cast<uint16_t>(this->startSeq - seq);
// Packets can arrive out of order, add blank slots.
for (uint16_t i{ 1 }; i < addToFront; ++i)
{
this->buffer.push_front(nullptr);
}
this->buffer.push_front(storageItem);
this->startSeq = seq;
}
MS_ASSERT(
this->buffer.size() <= MaxSeq,
"StorageItemBuffer contains more than %" PRIu16 " entries",
MaxSeq);
}
void RtpStreamSend::StorageItemBuffer::RemoveFirst()
{
MS_ASSERT(!this->buffer.empty(), "buffer is empty");
auto* storageItem = this->buffer[0];
delete storageItem;
this->buffer[0] = nullptr;
// Remove all `nullptr` elements from the beginning of the buffer.
// NOTE: Calling front on an empty container is undefined.
while (!this->buffer.empty() && this->buffer.front() == nullptr)
{
this->buffer.pop_front();
this->startSeq++;
}
}
void RtpStreamSend::StorageItemBuffer::Clear()
{
for (auto* storageItem : this->buffer)
{
if (!storageItem)
{
continue;
}
// Reset the storage item (decrease RTP packet shared pointer counter).
storageItem->Reset();
delete storageItem;
}
this->buffer.clear();
this->startSeq = 0;
}
RtpStreamSend::StorageItemBuffer::~StorageItemBuffer()
{
Clear();
}
/* Instance methods. */ /* Instance methods. */
RtpStreamSend::RtpStreamSend( RtpStreamSend::RtpStreamSend(
...@@ -176,20 +32,22 @@ namespace RTC ...@@ -176,20 +32,22 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (this->params.useNack)
{
uint32_t maxRetransmissionDelayMs;
switch (params.mimeType.type) switch (params.mimeType.type)
{ {
case RTC::RtpCodecMimeType::Type::VIDEO: case RTC::RtpCodecMimeType::Type::VIDEO:
{ {
this->maxRetransmissionDelayMs = RtpStreamSend::MaxRetransmissionDelayForVideoMs; maxRetransmissionDelayMs = RtpStreamSend::MaxRetransmissionDelayForVideoMs;
this->retransmissionBufferSize = RtpStreamSend::MaxRetransmissionDelayForVideoMs;
break; break;
} }
case RTC::RtpCodecMimeType::Type::AUDIO: case RTC::RtpCodecMimeType::Type::AUDIO:
{ {
this->maxRetransmissionDelayMs = RtpStreamSend::MaxRetransmissionDelayForAudioMs; maxRetransmissionDelayMs = RtpStreamSend::MaxRetransmissionDelayForAudioMs;
this->retransmissionBufferSize = RtpStreamSend::MaxRetransmissionDelayForAudioMs;
break; break;
} }
...@@ -199,14 +57,19 @@ namespace RTC ...@@ -199,14 +57,19 @@ namespace RTC
MS_ABORT("codec mimeType not set"); MS_ABORT("codec mimeType not set");
} }
} }
this->retransmissionBuffer = new RTC::RetransmissionBuffer(
RetransmissionBufferMaxItems, maxRetransmissionDelayMs, params.clockRate);
}
} }
RtpStreamSend::~RtpStreamSend() RtpStreamSend::~RtpStreamSend()
{ {
MS_TRACE(); MS_TRACE();
// Clear the RTP buffer. // Delete retransmission buffer.
ClearBuffer(); delete this->retransmissionBuffer;
this->retransmissionBuffer = nullptr;
} }
void RtpStreamSend::FillJsonStats(json& jsonObject) void RtpStreamSend::FillJsonStats(json& jsonObject)
...@@ -236,6 +99,9 @@ namespace RTC ...@@ -236,6 +99,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(
packet->GetSsrc() == this->params.ssrc, "RTP packet SSRC does not match the encodings SSRC");
// Call the parent method. // Call the parent method.
if (!RtpStream::ReceiveStreamPacket(packet)) if (!RtpStream::ReceiveStreamPacket(packet))
{ {
...@@ -243,7 +109,7 @@ namespace RTC ...@@ -243,7 +109,7 @@ namespace RTC
} }
// If NACK is enabled, store the packet into the buffer. // If NACK is enabled, store the packet into the buffer.
if (this->params.useNack) if (this->retransmissionBuffer)
{ {
StorePacket(packet, sharedPacket); StorePacket(packet, sharedPacket);
} }
...@@ -268,16 +134,16 @@ namespace RTC ...@@ -268,16 +134,16 @@ namespace RTC
FillRetransmissionContainer(item->GetPacketId(), item->GetLostPacketBitmask()); FillRetransmissionContainer(item->GetPacketId(), item->GetLostPacketBitmask());
for (auto* storageItem : RetransmissionContainer) for (auto* item : RetransmissionContainer)
{ {
if (!storageItem) if (!item)
{ {
break; break;
} }
// Note that this is an already RTX encoded packet if RTX is used // Note that this is an already RTX encoded packet if RTX is used
// (FillRetransmissionContainer() did it). // (FillRetransmissionContainer() did it).
auto packet = storageItem->packet; auto packet = item->packet;
// Retransmit the packet. // Retransmit the packet.
static_cast<RTC::RtpStreamSend::Listener*>(this->listener) static_cast<RTC::RtpStreamSend::Listener*>(this->listener)
...@@ -287,7 +153,7 @@ namespace RTC ...@@ -287,7 +153,7 @@ namespace RTC
RTC::RtpStream::PacketRetransmitted(packet.get()); RTC::RtpStream::PacketRetransmitted(packet.get());
// Mark the packet as repaired (only if this is the first retransmission). // Mark the packet as repaired (only if this is the first retransmission).
if (storageItem->sentTimes == 1) if (item->sentTimes == 1)
{ {
RTC::RtpStream::PacketRepaired(packet.get()); RTC::RtpStream::PacketRepaired(packet.get());
} }
...@@ -295,7 +161,7 @@ namespace RTC ...@@ -295,7 +161,7 @@ namespace RTC
if (HasRtx()) if (HasRtx())
{ {
// Restore the packet. // Restore the packet.
packet->RtxDecode(RtpStream::GetPayloadType(), storageItem->ssrc); packet->RtxDecode(RtpStream::GetPayloadType(), item->ssrc);
} }
} }
} }
...@@ -362,15 +228,6 @@ namespace RTC ...@@ -362,15 +228,6 @@ namespace RTC
this->hasRtt = true; this->hasRtt = true;
} }
// Smoothly change retransmission buffer size towards RTT + 100ms, but not
// more than this->maxRetransmissionDelayMs.
auto newRetransmissionBufferSize = static_cast<uint32_t>(this->rtt + 100.0);
auto avgRetransmissionBufferSize =
(this->retransmissionBufferSize * 7 + newRetransmissionBufferSize) / 8;
this->retransmissionBufferSize = std::max(
std::min(avgRetransmissionBufferSize, this->maxRetransmissionDelayMs),
RtpStreamSend::MinRetransmissionDelayMs);
this->packetsLost = report->GetTotalLost(); this->packetsLost = report->GetTotalLost();
this->fractionLost = report->GetFractionLost(); this->fractionLost = report->GetFractionLost();
...@@ -460,7 +317,11 @@ namespace RTC ...@@ -460,7 +317,11 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
ClearBuffer(); // Clear retransmission buffer.
if (this->retransmissionBuffer)
{
this->retransmissionBuffer->Clear();
}
} }
void RtpStreamSend::Resume() void RtpStreamSend::Resume()
...@@ -495,9 +356,6 @@ namespace RTC ...@@ -495,9 +356,6 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(
packet->GetSsrc() == this->params.ssrc, "RTP packet SSRC does not match the encodings SSRC");
if (packet->GetSize() > RTC::MtuSize) if (packet->GetSize() > RTC::MtuSize)
{ {
MS_WARN_TAG( MS_WARN_TAG(
...@@ -510,101 +368,7 @@ namespace RTC ...@@ -510,101 +368,7 @@ namespace RTC
return; return;
} }
// Check if RTP packet is too old to be stored. this->retransmissionBuffer->Insert(packet, sharedPacket);
if (this->storageItemBuffer.GetBufferSize() > 0)
{
auto* storageItem = this->storageItemBuffer.GetFirst();
// Processing RTP packet is older than first one.
if (RTC::SeqManager<uint32_t>::IsSeqLowerThan(packet->GetTimestamp(), storageItem->timestamp))
{
const uint32_t diffTs{ storageItem->timestamp - packet->GetTimestamp() };
// RTP packet is older than the retransmission buffer size.
if (static_cast<uint32_t>(diffTs * 1000 / this->params.clockRate) >= this->retransmissionBufferSize)
{
return;
}
}
}
this->ClearOldPackets(packet);
auto seq = packet->GetSequenceNumber();
auto* storageItem = this->storageItemBuffer.Get(seq);
// The buffer item is already used. Check whether we should replace its
// storage with the new packet or just ignore it (if duplicated packet).
if (storageItem)
{
if (packet->GetTimestamp() == storageItem->timestamp)
{
return;
}
// Reset the storage item.
storageItem->Reset();
}
// Allocate new buffer item.
else
{
// Allocate a new storage item.
storageItem = new StorageItem();
this->storageItemBuffer.Insert(seq, storageItem);
}
// Only clone once and only if necessary.
if (!sharedPacket.get())
{
sharedPacket.reset(packet->Clone());
}
// Store original packet and some extra info into the storage item.
storageItem->packet = sharedPacket;
storageItem->ssrc = packet->GetSsrc();
storageItem->sequenceNumber = packet->GetSequenceNumber();
storageItem->timestamp = packet->GetTimestamp();
}
void RtpStreamSend::ClearOldPackets(const RtpPacket* packet)
{
MS_TRACE();
auto clockRate{ this->params.clockRate };
const auto bufferSize = this->storageItemBuffer.GetBufferSize();
// Go through all buffer items starting with the first and free all storage
// items that contain packets older than this->maxRetransmissionDelayMs.
for (size_t i{ 0 }; i < bufferSize && this->storageItemBuffer.GetBufferSize() != 0; ++i)
{
auto* storageItem = this->storageItemBuffer.GetFirst();
const uint32_t diffTs{ packet->GetTimestamp() - storageItem->timestamp };
// Processing RTP packet is older than first one.
if (RTC::SeqManager<uint32_t>::IsSeqLowerThan(packet->GetTimestamp(), storageItem->timestamp))
{
break;
}
// First RTP packet is recent enough.
if (static_cast<uint32_t>(diffTs * 1000 / clockRate) < this->retransmissionBufferSize)
{
break;
}
// Unfill the buffer start item.
this->storageItemBuffer.RemoveFirst();
}
}
void RtpStreamSend::ClearBuffer()
{
MS_TRACE();
// Reset buffer.
this->storageItemBuffer.Clear();
} }
// This method looks for the requested RTP packets and inserts them into the // This method looks for the requested RTP packets and inserts them into the
...@@ -612,6 +376,12 @@ namespace RTC ...@@ -612,6 +376,12 @@ namespace RTC
// //
// If RTX is used the stored packet will be RTX encoded now (if not already // If RTX is used the stored packet will be RTX encoded now (if not already
// encoded in a previous resend). // encoded in a previous resend).
//
// NOTE: This method doesn't verify whether requested stored packet is too
// old, why? Because, if we verified it, we would do it by comparing its
// timestamp with the newest one in the retransmission buffer. However we
// already clean old packets upon receipt of any new packet (see Insert()
// method in RetransmissionBuffer class).
void RtpStreamSend::FillRetransmissionContainer(uint16_t seq, uint16_t bitmask) void RtpStreamSend::FillRetransmissionContainer(uint16_t seq, uint16_t bitmask)
{ {
MS_TRACE(); MS_TRACE();
...@@ -620,7 +390,7 @@ namespace RTC ...@@ -620,7 +390,7 @@ namespace RTC
RetransmissionContainer[0] = nullptr; RetransmissionContainer[0] = nullptr;
// If NACK is not supported, exit. // If NACK is not supported, exit.
if (!this->params.useNack) if (!this->retransmissionBuffer)
{ {
MS_WARN_TAG(rtx, "NACK not supported"); MS_WARN_TAG(rtx, "NACK not supported");
...@@ -640,7 +410,6 @@ namespace RTC ...@@ -640,7 +410,6 @@ namespace RTC
bool isFirstPacket{ true }; bool isFirstPacket{ true };
bool firstPacketSent{ false }; bool firstPacketSent{ false };
uint8_t bitmaskCounter{ 0 }; uint8_t bitmaskCounter{ 0 };
bool tooOldPacketFound{ false };
while (requested || bitmask != 0) while (requested || bitmask != 0)
{ {
...@@ -648,57 +417,36 @@ namespace RTC ...@@ -648,57 +417,36 @@ namespace RTC
if (requested) if (requested)
{ {
auto* storageItem = this->storageItemBuffer.Get(currentSeq); auto* item = this->retransmissionBuffer->Get(currentSeq);
std::shared_ptr<RTC::RtpPacket> packet{ nullptr }; std::shared_ptr<RTC::RtpPacket> packet{ nullptr };
uint32_t diffMs;
// Calculate the elapsed time between the max timestamp seen and the // Calculate the elapsed time between the max timestamp seen and the
// requested packet's timestamp (in ms). // requested packet's timestamp (in ms).
if (storageItem) if (item)
{ {
packet = storageItem->packet; packet = item->packet;
// Put correct info into the packet. // Put correct info into the packet.
packet->SetSsrc(storageItem->ssrc); packet->SetSsrc(item->ssrc);
packet->SetSequenceNumber(storageItem->sequenceNumber); packet->SetSequenceNumber(item->sequenceNumber);
packet->SetTimestamp(storageItem->timestamp); packet->SetTimestamp(item->timestamp);
// Update MID RTP extension value. // Update MID RTP extension value.
if (!this->mid.empty()) if (!this->mid.empty())
{ {
packet->UpdateMid(mid); packet->UpdateMid(mid);
} }
const uint32_t diffTs = this->maxPacketTs - packet->GetTimestamp();
diffMs = diffTs * 1000 / this->params.clockRate;
} }
// Packet not found. // Packet not found.
if (!storageItem) if (!item)
{ {
// Do nothing. // Do nothing.
} }
// Don't resend the packet if older than this->maxRetransmissionDelayMs ms.
else if (diffMs > this->maxRetransmissionDelayMs)
{
if (!tooOldPacketFound)
{
MS_WARN_TAG(
rtx,
"ignoring retransmission for too old packet "
"[seq:%" PRIu16 ", max age:%" PRIu32 "ms, packet age:%" PRIu32 "ms]",
packet->GetSequenceNumber(),
this->maxRetransmissionDelayMs,
diffMs);
tooOldPacketFound = true;
}
}
// Don't resent the packet if it was resent in the last RTT ms. // Don't resent the packet if it was resent in the last RTT ms.
// clang-format off // clang-format off
else if ( else if (
storageItem->resentAtMs != 0u && item->resentAtMs != 0u &&
nowMs - storageItem->resentAtMs <= static_cast<uint64_t>(rtt) nowMs - item->resentAtMs <= static_cast<uint64_t>(rtt)
) )
// clang-format on // clang-format on
{ {
...@@ -722,13 +470,13 @@ namespace RTC ...@@ -722,13 +470,13 @@ namespace RTC
} }
// Save when this packet was resent. // Save when this packet was resent.
storageItem->resentAtMs = nowMs; item->resentAtMs = nowMs;
// Increase the number of times this packet was sent. // Increase the number of times this packet was sent.
storageItem->sentTimes++; item->sentTimes++;
// Store the storage item in the container and then increment its index. // Store the item in the container and then increment its index.
RetransmissionContainer[containerIdx++] = storageItem; RetransmissionContainer[containerIdx++] = item;
sent = true; sent = true;
......
...@@ -43,7 +43,9 @@ Timer::~Timer() ...@@ -43,7 +43,9 @@ Timer::~Timer()
MS_TRACE(); MS_TRACE();
if (!this->closed) if (!this->closed)
{
Close(); Close();
}
} }
void Timer::Close() void Timer::Close()
...@@ -51,7 +53,9 @@ void Timer::Close() ...@@ -51,7 +53,9 @@ void Timer::Close()
MS_TRACE(); MS_TRACE();
if (this->closed) if (this->closed)
{
return; return;
}
this->closed = true; this->closed = true;
...@@ -63,18 +67,24 @@ void Timer::Start(uint64_t timeout, uint64_t repeat) ...@@ -63,18 +67,24 @@ void Timer::Start(uint64_t timeout, uint64_t repeat)
MS_TRACE(); MS_TRACE();
if (this->closed) if (this->closed)
{
MS_THROW_ERROR("closed"); MS_THROW_ERROR("closed");
}
this->timeout = timeout; this->timeout = timeout;
this->repeat = repeat; this->repeat = repeat;
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0) if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0)
{
Stop(); Stop();
}
const int err = uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), timeout, repeat); const int err = uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), timeout, repeat);
if (err != 0) if (err != 0)
{
MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err));
}
} }
void Timer::Stop() void Timer::Stop()
...@@ -82,12 +92,16 @@ void Timer::Stop() ...@@ -82,12 +92,16 @@ void Timer::Stop()
MS_TRACE(); MS_TRACE();
if (this->closed) if (this->closed)
{
MS_THROW_ERROR("closed"); MS_THROW_ERROR("closed");
}
const int err = uv_timer_stop(this->uvHandle); const int err = uv_timer_stop(this->uvHandle);
if (err != 0) if (err != 0)
{
MS_THROW_ERROR("uv_timer_stop() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_timer_stop() failed: %s", uv_strerror(err));
}
} }
void Timer::Reset() void Timer::Reset()
...@@ -95,19 +109,27 @@ void Timer::Reset() ...@@ -95,19 +109,27 @@ void Timer::Reset()
MS_TRACE(); MS_TRACE();
if (this->closed) if (this->closed)
{
MS_THROW_ERROR("closed"); MS_THROW_ERROR("closed");
}
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) == 0) if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) == 0)
{
return; return;
}
if (this->repeat == 0u) if (this->repeat == 0u)
{
return; return;
}
const int err = const int err =
uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), this->repeat, this->repeat); uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), this->repeat, this->repeat);
if (err != 0) if (err != 0)
{
MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err));
}
} }
void Timer::Restart() void Timer::Restart()
...@@ -115,16 +137,22 @@ void Timer::Restart() ...@@ -115,16 +137,22 @@ void Timer::Restart()
MS_TRACE(); MS_TRACE();
if (this->closed) if (this->closed)
{
MS_THROW_ERROR("closed"); MS_THROW_ERROR("closed");
}
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0) if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0)
{
Stop(); Stop();
}
const int err = const int err =
uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), this->timeout, this->repeat); uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), this->timeout, this->repeat);
if (err != 0) if (err != 0)
{
MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err));
}
} }
inline void Timer::OnUvTimer() 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]") ...@@ -376,10 +376,14 @@ SCENARIO("NACK and RTP packets retransmission", "[rtp][rtcp][nack]")
uint32_t clockRate = 90000; uint32_t clockRate = 90000;
uint32_t firstTs = 1533790901; uint32_t firstTs = 1533790901;
uint32_t diffTs = RtpStreamSend::MaxRetransmissionDelayForVideoMs * clockRate / 1000; 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* packet1 = CreateRtpPacket(rtpBuffer1, 21006, firstTs);
auto* packet2 = CreateRtpPacket(rtpBuffer2, 21007, secondTs); auto* packet2 = CreateRtpPacket(rtpBuffer2, 21007, secondTs);
auto* packet3 = CreateRtpPacket(rtpBuffer3, 21008, thirdTs);
// Create a RtpStreamSend instance. // Create a RtpStreamSend instance.
TestRtpStreamListener testRtpStreamListener1; TestRtpStreamListener testRtpStreamListener1;
...@@ -397,6 +401,7 @@ SCENARIO("NACK and RTP packets retransmission", "[rtp][rtcp][nack]") ...@@ -397,6 +401,7 @@ SCENARIO("NACK and RTP packets retransmission", "[rtp][rtcp][nack]")
// Receive all the packets. // Receive all the packets.
SendRtpPacket({ { stream, params1.ssrc } }, packet1); SendRtpPacket({ { stream, params1.ssrc } }, packet1);
SendRtpPacket({ { stream, params1.ssrc } }, packet2); SendRtpPacket({ { stream, params1.ssrc } }, packet2);
SendRtpPacket({ { stream, params1.ssrc } }, packet3);
// Create a NACK item that request for all the packets. // Create a NACK item that request for all the packets.
RTCP::FeedbackRtpNackPacket nackPacket(0, params1.ssrc); RTCP::FeedbackRtpNackPacket nackPacket(0, params1.ssrc);
......
...@@ -19,15 +19,28 @@ int main(int argc, char* argv[]) ...@@ -19,15 +19,28 @@ int main(int argc, char* argv[])
if (std::getenv("MS_TEST_LOG_LEVEL")) if (std::getenv("MS_TEST_LOG_LEVEL"))
{ {
if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "debug") if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "debug")
{
logLevel = LogLevel::LOG_DEBUG; logLevel = LogLevel::LOG_DEBUG;
}
else if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "warn") else if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "warn")
{
logLevel = LogLevel::LOG_WARN; logLevel = LogLevel::LOG_WARN;
}
else if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "error") else if (std::string(std::getenv("MS_TEST_LOG_LEVEL")) == "error")
{
logLevel = LogLevel::LOG_ERROR; logLevel = LogLevel::LOG_ERROR;
} }
}
Settings::configuration.logLevel = logLevel; 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. // Initialize static stuff.
DepLibUV::ClassInit(); DepLibUV::ClassInit();
DepOpenSSL::ClassInit(); DepOpenSSL::ClassInit();
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论