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

Simulcast: proper RTP timestamp rewrite based on SenderReport NTP offset (#302)

This avoids lipsync issues. This PR also takes into account cases in which the key frame of the switched stream has a RTP timestamp lower than the last sent and fixes it be gradually decreasing the sent timestamp.
上级 cb8a393d
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
"test": "npm run test:node && npm run test:worker", "test": "npm run test:node && npm run test:worker",
"test:node": "make -C worker && jest", "test:node": "make -C worker && jest",
"test:worker": "make test -C worker", "test:worker": "make test -C worker",
"coverage:node": "make -C worker && jest --coverage && opn coverage/lcov-report/index.html", "coverage:node": "make -C worker && jest --coverage && open-cli coverage/lcov-report/index.html",
"postinstall": "make -C worker" "postinstall": "make -C worker"
}, },
"jest": { "jest": {
...@@ -55,7 +55,7 @@ ...@@ -55,7 +55,7 @@
"gulp-clang-format": "^1.0.27", "gulp-clang-format": "^1.0.27",
"jest": "^24.8.0", "jest": "^24.8.0",
"jest-tobetype": "^1.2.3", "jest-tobetype": "^1.2.3",
"opn-cli": "^4.1.0" "open-cli": "^5.0.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"clang-tools-prebuilt": "^0.1.4" "clang-tools-prebuilt": "^0.1.4"
......
...@@ -61,6 +61,7 @@ namespace RTC ...@@ -61,6 +61,7 @@ namespace RTC
virtual void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) = 0; virtual void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) = 0;
virtual void ProducerRtpStreamScore( virtual void ProducerRtpStreamScore(
RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) = 0; RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) = 0;
virtual void ProducerRtcpSenderReport(RTC::RtpStream* rtpStream, bool first) = 0;
void ProducerClosed(); void ProducerClosed();
virtual void SetExternallyManagedBitrate(); virtual void SetExternallyManagedBitrate();
virtual int16_t GetBitratePriority() const; virtual int16_t GetBitratePriority() const;
......
...@@ -21,6 +21,7 @@ namespace RTC ...@@ -21,6 +21,7 @@ namespace RTC
void ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override; void ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override; void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void ProducerRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override; void ProducerRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override;
void ProducerRtcpSenderReport(RTC::RtpStream* rtpStream, bool first) override;
void SendRtpPacket(RTC::RtpPacket* packet) override; void SendRtpPacket(RTC::RtpPacket* packet) override;
void GetRtcp(RTC::RTCP::CompoundPacket* packet, RTC::RtpStreamSend* rtpStream, uint64_t now) override; void GetRtcp(RTC::RTCP::CompoundPacket* packet, RTC::RtpStreamSend* rtpStream, uint64_t now) override;
std::vector<RTC::RtpStreamSend*> GetRtpStreams() override; std::vector<RTC::RtpStreamSend*> GetRtpStreams() override;
......
...@@ -30,6 +30,8 @@ namespace RTC ...@@ -30,6 +30,8 @@ namespace RTC
RTC::Producer* producer, RTC::RtpStream* rtpStream, uint32_t mappedSsrc) = 0; RTC::Producer* producer, RTC::RtpStream* rtpStream, uint32_t mappedSsrc) = 0;
virtual void OnProducerRtpStreamScore( virtual void OnProducerRtpStreamScore(
RTC::Producer* producer, RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) = 0; RTC::Producer* producer, RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) = 0;
virtual void OnProducerRtcpSenderReport(
RTC::Producer* producer, RTC::RtpStream* rtpStream, bool first) = 0;
virtual void OnProducerRtpPacketReceived(RTC::Producer* producer, RTC::RtpPacket* packet) = 0; virtual void OnProducerRtpPacketReceived(RTC::Producer* producer, RTC::RtpPacket* packet) = 0;
virtual void OnProducerSendRtcpPacket(RTC::Producer* producer, RTC::RTCP::Packet* packet) = 0; virtual void OnProducerSendRtcpPacket(RTC::Producer* producer, RTC::RTCP::Packet* packet) = 0;
virtual void OnProducerNeedWorstRemoteFractionLost( virtual void OnProducerNeedWorstRemoteFractionLost(
......
...@@ -46,6 +46,14 @@ namespace RTC ...@@ -46,6 +46,14 @@ namespace RTC
RTC::Producer* producer, RTC::Producer* producer,
RTC::RtpStream* rtpStream, RTC::RtpStream* rtpStream,
uint32_t mappedSsrc) override; uint32_t mappedSsrc) override;
void OnTransportProducerRtpStreamScore(
RTC::Transport* transport,
RTC::Producer* producer,
RTC::RtpStream* rtpStream,
uint8_t score,
uint8_t previousScore) override;
void OnTransportProducerRtcpSenderReport(
RTC::Transport* transport, RTC::Producer* producer, RTC::RtpStream* rtpStream, bool first) override;
void OnTransportProducerRtpPacketReceived( void OnTransportProducerRtpPacketReceived(
RTC::Transport* transport, RTC::Producer* producer, RTC::RtpPacket* packet) override; RTC::Transport* transport, RTC::Producer* producer, RTC::RtpPacket* packet) override;
void OnTransportNeedWorstRemoteFractionLost( void OnTransportNeedWorstRemoteFractionLost(
...@@ -53,12 +61,6 @@ namespace RTC ...@@ -53,12 +61,6 @@ namespace RTC
RTC::Producer* producer, RTC::Producer* producer,
uint32_t mappedSsrc, uint32_t mappedSsrc,
uint8_t& worstRemoteFractionLost) override; uint8_t& worstRemoteFractionLost) override;
void OnTransportProducerRtpStreamScore(
RTC::Transport* transport,
RTC::Producer* producer,
RTC::RtpStream* rtpStream,
uint8_t score,
uint8_t previousScore) override;
void OnTransportNewConsumer( void OnTransportNewConsumer(
RTC::Transport* transport, RTC::Consumer* consumer, std::string& producerId) override; RTC::Transport* transport, RTC::Consumer* consumer, std::string& producerId) override;
void OnTransportConsumerClosed(RTC::Transport* transport, RTC::Consumer* consumer) override; void OnTransportConsumerClosed(RTC::Transport* transport, RTC::Consumer* consumer) override;
......
...@@ -79,6 +79,9 @@ namespace RTC ...@@ -79,6 +79,9 @@ namespace RTC
uint8_t GetFractionLost() const; uint8_t GetFractionLost() const;
float GetLossPercentage() const; float GetLossPercentage() const;
uint64_t GetMaxPacketMs() const; uint64_t GetMaxPacketMs() const;
uint32_t GetMaxPacketTs() const;
uint64_t GetSenderReportNtpMs() const;
uint32_t GetSenderReportTs() const;
uint8_t GetScore() const; uint8_t GetScore() const;
protected: protected:
...@@ -86,7 +89,7 @@ namespace RTC ...@@ -86,7 +89,7 @@ namespace RTC
void UpdateScore(uint8_t score); void UpdateScore(uint8_t score);
void PacketRetransmitted(RTC::RtpPacket* packet); void PacketRetransmitted(RTC::RtpPacket* packet);
void PacketRepaired(RTC::RtpPacket* packet); void PacketRepaired(RTC::RtpPacket* packet);
uint32_t GetExpectedPackets(); uint32_t GetExpectedPackets() const;
private: private:
void InitSeq(uint16_t seq); void InitSeq(uint16_t seq);
...@@ -115,6 +118,8 @@ namespace RTC ...@@ -115,6 +118,8 @@ namespace RTC
size_t repairedPrior{ 0 }; // Packets repaired at last interval. size_t repairedPrior{ 0 }; // Packets repaired at last interval.
size_t retransmittedPrior{ 0 }; // Packets retransmitted at last interval. size_t retransmittedPrior{ 0 }; // Packets retransmitted at last interval.
uint32_t expectedPrior{ 0 }; // Packets expected at last interval. uint32_t expectedPrior{ 0 }; // Packets expected at last interval.
uint64_t lastSenderReportNtpMs{ 0 }; // NTP timestamp in last Sender Report (in ms).
uint32_t lastSenderReporTs{ 0 }; // RTP timestamp in last Sender Report.
private: private:
// Score related. // Score related.
...@@ -206,15 +211,30 @@ namespace RTC ...@@ -206,15 +211,30 @@ namespace RTC
return this->maxPacketMs; return this->maxPacketMs;
} }
inline uint32_t RtpStream::GetExpectedPackets() inline uint32_t RtpStream::GetMaxPacketTs() const
{ {
return (this->cycles + this->maxSeq) - this->baseSeq + 1; return this->maxPacketTs;
}
inline uint64_t RtpStream::GetSenderReportNtpMs() const
{
return this->lastSenderReportNtpMs;
}
inline uint32_t RtpStream::GetSenderReportTs() const
{
return this->lastSenderReporTs;
} }
inline uint8_t RtpStream::GetScore() const inline uint8_t RtpStream::GetScore() const
{ {
return this->score; return this->score;
} }
inline uint32_t RtpStream::GetExpectedPackets() const
{
return (this->cycles + this->maxSeq) - this->baseSeq + 1;
}
} // namespace RTC } // namespace RTC
#endif #endif
...@@ -22,6 +22,7 @@ namespace RTC ...@@ -22,6 +22,7 @@ namespace RTC
void ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override; void ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override; void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void ProducerRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override; void ProducerRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override;
void ProducerRtcpSenderReport(RTC::RtpStream* rtpStream, bool first) override;
void SendRtpPacket(RTC::RtpPacket* packet) override; void SendRtpPacket(RTC::RtpPacket* packet) override;
std::vector<RTC::RtpStreamSend*> GetRtpStreams() override; std::vector<RTC::RtpStreamSend*> GetRtpStreams() override;
void GetRtcp(RTC::RTCP::CompoundPacket* packet, RTC::RtpStreamSend* rtpStream, uint64_t now) override; void GetRtcp(RTC::RTCP::CompoundPacket* packet, RTC::RtpStreamSend* rtpStream, uint64_t now) override;
......
...@@ -23,6 +23,7 @@ namespace RTC ...@@ -23,6 +23,7 @@ namespace RTC
void ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override; void ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override; void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void ProducerRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override; void ProducerRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override;
void ProducerRtcpSenderReport(RTC::RtpStream* rtpStream, bool first) override;
void SetExternallyManagedBitrate() override; void SetExternallyManagedBitrate() override;
int16_t GetBitratePriority() const override; int16_t GetBitratePriority() const override;
uint32_t UseAvailableBitrate(uint32_t bitrate) override; uint32_t UseAvailableBitrate(uint32_t bitrate) override;
...@@ -50,10 +51,12 @@ namespace RTC ...@@ -50,10 +51,12 @@ namespace RTC
bool RecalculateTargetLayers(int16_t& newTargetSpatialLayer, int16_t& newTargetTemporalLayer) const; bool RecalculateTargetLayers(int16_t& newTargetSpatialLayer, int16_t& newTargetTemporalLayer) const;
void UpdateTargetLayers(int16_t newTargetSpatialLayer, int16_t newTargetTemporalLayer); void UpdateTargetLayers(int16_t newTargetSpatialLayer, int16_t newTargetTemporalLayer);
void UpdateCurrentLayers(); void UpdateCurrentLayers();
bool CanSwitchToSpatialLayer(int16_t spatialLayer) const;
void EmitScore() const; void EmitScore() const;
void EmitLayersChange() const; void EmitLayersChange() const;
RTC::RtpStream* GetProducerCurrentRtpStream() const; RTC::RtpStream* GetProducerCurrentRtpStream() const;
RTC::RtpStream* GetProducerTargetRtpStream() const; RTC::RtpStream* GetProducerTargetRtpStream() const;
RTC::RtpStream* GetProducerTsReferenceRtpStream() const;
/* Pure virtual methods inherited from RtpStreamSend::Listener. */ /* Pure virtual methods inherited from RtpStreamSend::Listener. */
public: public:
...@@ -70,7 +73,6 @@ namespace RTC ...@@ -70,7 +73,6 @@ namespace RTC
bool keyFrameSupported{ false }; bool keyFrameSupported{ false };
bool syncRequired{ false }; bool syncRequired{ false };
RTC::SeqManager<uint16_t> rtpSeqManager; RTC::SeqManager<uint16_t> rtpSeqManager;
RTC::SeqManager<uint32_t> rtpTimestampManager;
int16_t preferredSpatialLayer{ -1 }; int16_t preferredSpatialLayer{ -1 };
int16_t preferredTemporalLayer{ -1 }; int16_t preferredTemporalLayer{ -1 };
int16_t provisionalTargetSpatialLayer{ -1 }; int16_t provisionalTargetSpatialLayer{ -1 };
...@@ -79,8 +81,12 @@ namespace RTC ...@@ -79,8 +81,12 @@ namespace RTC
int16_t targetTemporalLayer{ -1 }; int16_t targetTemporalLayer{ -1 };
int16_t currentSpatialLayer{ -1 }; int16_t currentSpatialLayer{ -1 };
int16_t currentTemporalLayer{ -1 }; int16_t currentTemporalLayer{ -1 };
int16_t tsReferenceSpatialLayer{ -1 }; // Used for RTP TS sync.
std::unique_ptr<RTC::Codecs::EncodingContext> encodingContext; std::unique_ptr<RTC::Codecs::EncodingContext> encodingContext;
bool externallyManagedBitrate{ false }; bool externallyManagedBitrate{ false };
uint32_t tsOffset{ 0 }; // RTP Timestamp offset.
uint32_t tsExtraOffset{ 0 };
uint32_t lastIncreasedOriginalTs{ 0 };
}; };
/* Inline methods. */ /* Inline methods. */
......
...@@ -44,6 +44,8 @@ namespace RTC ...@@ -44,6 +44,8 @@ namespace RTC
RTC::RtpStream* rtpStream, RTC::RtpStream* rtpStream,
uint8_t score, uint8_t score,
uint8_t previousScore) = 0; uint8_t previousScore) = 0;
virtual void OnTransportProducerRtcpSenderReport(
RTC::Transport* transport, RTC::Producer* producer, RTC::RtpStream* rtpStream, bool first) = 0;
virtual void OnTransportProducerRtpPacketReceived( virtual void OnTransportProducerRtpPacketReceived(
RTC::Transport* transport, RTC::Producer* producer, RTC::RtpPacket* packet) = 0; RTC::Transport* transport, RTC::Producer* producer, RTC::RtpPacket* packet) = 0;
virtual void OnTransportNeedWorstRemoteFractionLost( virtual void OnTransportNeedWorstRemoteFractionLost(
...@@ -112,6 +114,8 @@ namespace RTC ...@@ -112,6 +114,8 @@ namespace RTC
RTC::Producer* producer, RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override; RTC::Producer* producer, RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void OnProducerRtpStreamScore( void OnProducerRtpStreamScore(
RTC::Producer* producer, RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override; RTC::Producer* producer, RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override;
void OnProducerRtcpSenderReport(
RTC::Producer* producer, RTC::RtpStream* rtpStream, bool first) override;
void OnProducerRtpPacketReceived(RTC::Producer* producer, RTC::RtpPacket* packet) override; void OnProducerRtpPacketReceived(RTC::Producer* producer, RTC::RtpPacket* packet) override;
void OnProducerSendRtcpPacket(RTC::Producer* producer, RTC::RTCP::Packet* packet) override; void OnProducerSendRtcpPacket(RTC::Producer* producer, RTC::RTCP::Packet* packet) override;
void OnProducerNeedWorstRemoteFractionLost( void OnProducerNeedWorstRemoteFractionLost(
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#include "common.hpp" #include "common.hpp"
#include <openssl/hmac.h> #include <openssl/hmac.h>
#include <cmath>
#include <cstring> // std::memcmp(), std::memcpy() #include <cstring> // std::memcmp(), std::memcpy()
#include <string> #include <string>
...@@ -300,21 +301,32 @@ namespace Utils ...@@ -300,21 +301,32 @@ namespace Utils
}; };
static Time::Ntp TimeMs2Ntp(uint64_t ms); static Time::Ntp TimeMs2Ntp(uint64_t ms);
static uint64_t Ntp2TimeMs(Time::Ntp ntp);
static bool IsNewerTimestamp(uint32_t timestamp, uint32_t prevTimestamp); static bool IsNewerTimestamp(uint32_t timestamp, uint32_t prevTimestamp);
static uint32_t LatestTimestamp(uint32_t timestamp1, uint32_t timestamp2); static uint32_t LatestTimestamp(uint32_t timestamp1, uint32_t timestamp2);
}; };
inline Time::Ntp Time::TimeMs2Ntp(uint64_t ms) inline Time::Ntp Time::TimeMs2Ntp(uint64_t ms)
{ {
Ntp ntp; Time::Ntp ntp; // NOLINT(cppcoreguidelines-pro-type-member-init)
ntp.seconds = ms / 1000; ntp.seconds = ms / 1000;
ntp.fractions = ntp.fractions =
static_cast<uint32_t>(static_cast<double>(ms % 1000) / 1000 * Utils::Time::NtpFractionalUnit); static_cast<uint32_t>((static_cast<double>(ms % 1000) / 1000) * NtpFractionalUnit);
return ntp; return ntp;
} }
inline uint64_t Time::Ntp2TimeMs(Time::Ntp ntp)
{
// clang-format off
return (
static_cast<uint64_t>(ntp.seconds) * 1000 +
static_cast<uint64_t>(std::round((static_cast<double>(ntp.fractions) * 1000) / NtpFractionalUnit))
);
// clang-format on
}
inline bool Time::IsNewerTimestamp(uint32_t timestamp, uint32_t prevTimestamp) inline bool Time::IsNewerTimestamp(uint32_t timestamp, uint32_t prevTimestamp)
{ {
// Distinguish between elements that are exactly 0x80000000 apart. // Distinguish between elements that are exactly 0x80000000 apart.
......
...@@ -308,6 +308,7 @@ ...@@ -308,6 +308,7 @@
'test/src/Utils/TestBits.cpp', 'test/src/Utils/TestBits.cpp',
'test/src/Utils/TestIP.cpp', 'test/src/Utils/TestIP.cpp',
'test/src/Utils/TestString.cpp', 'test/src/Utils/TestString.cpp',
'test/src/Utils/TestTime.cpp',
# C++ include files. # C++ include files.
'test/include/catch.hpp', 'test/include/catch.hpp',
'test/include/helpers.hpp' 'test/include/helpers.hpp'
......
...@@ -180,8 +180,8 @@ namespace RTC ...@@ -180,8 +180,8 @@ namespace RTC
// Check whether pictureId and tl0PictureIndex sync is required. // Check whether pictureId and tl0PictureIndex sync is required.
if (context->syncRequired) if (context->syncRequired)
{ {
context->pictureIdManager.Sync(this->payloadDescriptor->pictureId); context->pictureIdManager.Sync(this->payloadDescriptor->pictureId - 1);
context->tl0PictureIndexManager.Sync(this->payloadDescriptor->tl0PictureIndex); context->tl0PictureIndexManager.Sync(this->payloadDescriptor->tl0PictureIndex - 1);
context->syncRequired = false; context->syncRequired = false;
} }
......
...@@ -126,6 +126,13 @@ namespace RTC ...@@ -126,6 +126,13 @@ namespace RTC
// Do nothing. // Do nothing.
} }
void PipeConsumer::ProducerRtcpSenderReport(RTC::RtpStream* /*rtpStream*/, bool /*first*/)
{
MS_TRACE();
// Do nothing.
}
void PipeConsumer::SendRtpPacket(RTC::RtpPacket* packet) void PipeConsumer::SendRtpPacket(RTC::RtpPacket* packet)
{ {
MS_TRACE(); MS_TRACE();
...@@ -162,7 +169,7 @@ namespace RTC ...@@ -162,7 +169,7 @@ namespace RTC
if (packet->IsKeyFrame()) if (packet->IsKeyFrame())
MS_DEBUG_TAG(rtp, "sync key frame received"); MS_DEBUG_TAG(rtp, "sync key frame received");
rtpSeqManager.Sync(packet->GetSequenceNumber()); rtpSeqManager.Sync(packet->GetSequenceNumber() - 1);
syncRequired = false; syncRequired = false;
} }
......
...@@ -533,8 +533,11 @@ namespace RTC ...@@ -533,8 +533,11 @@ namespace RTC
} }
auto* rtpStream = it->second; auto* rtpStream = it->second;
bool first = rtpStream->GetSenderReportNtpMs() == 0;
rtpStream->ReceiveRtcpSenderReport(report); rtpStream->ReceiveRtcpSenderReport(report);
this->listener->OnProducerRtcpSenderReport(this, rtpStream, first);
} }
void Producer::GetRtcp(RTC::RTCP::CompoundPacket* packet, uint64_t now) void Producer::GetRtcp(RTC::RTCP::CompoundPacket* packet, uint64_t now)
......
...@@ -578,6 +578,19 @@ namespace RTC ...@@ -578,6 +578,19 @@ namespace RTC
} }
} }
inline void Router::OnTransportProducerRtcpSenderReport(
RTC::Transport* /*transport*/, RTC::Producer* producer, RTC::RtpStream* rtpStream, bool first)
{
MS_TRACE();
auto& consumers = this->mapProducerConsumers.at(producer);
for (auto* consumer : consumers)
{
consumer->ProducerRtcpSenderReport(rtpStream, first);
}
}
inline void Router::OnTransportProducerRtpPacketReceived( inline void Router::OnTransportProducerRtpPacketReceived(
RTC::Transport* /*transport*/, RTC::Producer* producer, RTC::RtpPacket* packet) RTC::Transport* /*transport*/, RTC::Producer* producer, RTC::RtpPacket* packet)
{ {
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
#include "RTC/RtpStreamRecv.hpp" #include "RTC/RtpStreamRecv.hpp"
#include "DepLibUV.hpp" #include "DepLibUV.hpp"
#include "Logger.hpp" #include "Logger.hpp"
#include "Utils.hpp"
#include "RTC/Codecs/Codecs.hpp" #include "RTC/Codecs/Codecs.hpp"
namespace RTC namespace RTC
...@@ -426,6 +427,15 @@ namespace RTC ...@@ -426,6 +427,15 @@ namespace RTC
this->lastSrTimestamp = report->GetNtpSec() << 16; this->lastSrTimestamp = report->GetNtpSec() << 16;
this->lastSrTimestamp += report->GetNtpFrac() >> 16; this->lastSrTimestamp += report->GetNtpFrac() >> 16;
// Update info about last Sender Report.
Utils::Time::Ntp ntp; // NOLINT(cppcoreguidelines-pro-type-member-init)
ntp.seconds = report->GetNtpSec();
ntp.fractions = report->GetNtpFrac();
this->lastSenderReportNtpMs = Utils::Time::Ntp2TimeMs(ntp);
this->lastSenderReporTs = report->GetRtpTs();
// Update the score with the current RR. // Update the score with the current RR.
UpdateScore(); UpdateScore();
} }
......
...@@ -174,14 +174,18 @@ namespace RTC ...@@ -174,14 +174,18 @@ namespace RTC
// Calculate TS difference between now and maxPacketMs. // Calculate TS difference between now and maxPacketMs.
auto diffMs = now - this->maxPacketMs; auto diffMs = now - this->maxPacketMs;
auto diffTs = diffMs * this->GetClockRate() / 1000; auto diffTs = diffMs * GetClockRate() / 1000;
report->SetSsrc(GetSsrc()); report->SetSsrc(GetSsrc());
report->SetPacketCount(this->transmissionCounter.GetPacketCount()); report->SetPacketCount(this->transmissionCounter.GetPacketCount());
report->SetOctetCount(this->transmissionCounter.GetBytes()); report->SetOctetCount(this->transmissionCounter.GetBytes());
report->SetRtpTs(this->maxPacketTs + diffTs);
report->SetNtpSec(ntp.seconds); report->SetNtpSec(ntp.seconds);
report->SetNtpFrac(ntp.fractions); report->SetNtpFrac(ntp.fractions);
report->SetRtpTs(this->maxPacketTs + diffTs);
// Update info about last Sender Report.
this->lastSenderReportNtpMs = now;
this->lastSenderReporTs = this->maxPacketTs + diffTs;
return report; return report;
} }
......
...@@ -42,7 +42,7 @@ namespace RTC ...@@ -42,7 +42,7 @@ namespace RTC
void SeqManager<T>::Sync(T input) void SeqManager<T>::Sync(T input)
{ {
// Update base. // Update base.
this->base = this->maxOutput - input + 1; this->base = this->maxOutput - input;
// Update maxInput. // Update maxInput.
this->maxInput = input; this->maxInput = input;
......
...@@ -124,6 +124,13 @@ namespace RTC ...@@ -124,6 +124,13 @@ namespace RTC
EmitScore(); EmitScore();
} }
void SimpleConsumer::ProducerRtcpSenderReport(RTC::RtpStream* /*rtpStream*/, bool /*first*/)
{
MS_TRACE();
// Do nothing.
}
void SimpleConsumer::SendRtpPacket(RTC::RtpPacket* packet) void SimpleConsumer::SendRtpPacket(RTC::RtpPacket* packet)
{ {
MS_TRACE(); MS_TRACE();
...@@ -156,7 +163,7 @@ namespace RTC ...@@ -156,7 +163,7 @@ namespace RTC
if (packet->IsKeyFrame()) if (packet->IsKeyFrame())
MS_DEBUG_TAG(rtp, "sync key frame received"); MS_DEBUG_TAG(rtp, "sync key frame received");
this->rtpSeqManager.Sync(packet->GetSequenceNumber()); this->rtpSeqManager.Sync(packet->GetSequenceNumber() - 1);
this->syncRequired = false; this->syncRequired = false;
} }
......
...@@ -287,6 +287,27 @@ namespace RTC ...@@ -287,6 +287,27 @@ namespace RTC
} }
} }
void SimulcastConsumer::ProducerRtcpSenderReport(RTC::RtpStream* rtpStream, bool first)
{
MS_TRACE();
// Just interested if this is the first Sender Report for a RTP stream.
if (first)
MS_DEBUG_TAG(simulcast, "first SenderReport [ssrc:%" PRIu32 "]", rtpStream->GetSsrc());
else
return;
// If our current selected RTP stream does not yet have SR, do nothing since
// we know we won't be able to switch.
auto* producerCurrentRtpStream = GetProducerCurrentRtpStream();
if (!producerCurrentRtpStream || !producerCurrentRtpStream->GetSenderReportNtpMs())
return;
if (IsActive())
MayChangeLayers();
}
void SimulcastConsumer::SetExternallyManagedBitrate() void SimulcastConsumer::SetExternallyManagedBitrate()
{ {
MS_TRACE(); MS_TRACE();
...@@ -368,6 +389,10 @@ namespace RTC ...@@ -368,6 +389,10 @@ namespace RTC
if (producerScore == 0) if (producerScore == 0)
continue; continue;
// We may not yet switch to a different spatial layer.
if (!CanSwitchToSpatialLayer(spatialLayer))
continue;
if (producerScore >= maxProducerScore || producerScore >= 7) if (producerScore >= maxProducerScore || producerScore >= 7)
{ {
int16_t temporalLayer{ 0 }; int16_t temporalLayer{ 0 };
...@@ -485,6 +510,10 @@ namespace RTC ...@@ -485,6 +510,10 @@ namespace RTC
// Take it even if it's bad. // Take it even if it's bad.
if (producerRtpStream && producerRtpStream->GetScore() > 0) if (producerRtpStream && producerRtpStream->GetScore() > 0)
{ {
// We may not yet switch to a different spatial layer.
if (!CanSwitchToSpatialLayer(0))
return 0;
spatialLayer = 0; spatialLayer = 0;
temporalLayer = 0; temporalLayer = 0;
} }
...@@ -510,6 +539,10 @@ namespace RTC ...@@ -510,6 +539,10 @@ namespace RTC
if (!producerRtpStream || producerRtpStream->GetScore() < 7) if (!producerRtpStream || producerRtpStream->GetScore() < 7)
return 0; return 0;
// We may not yet switch to a different spatial layer.
if (!CanSwitchToSpatialLayer(spatialLayer))
return 0;
// Set temporal layer to 0. // Set temporal layer to 0.
temporalLayer = 0; temporalLayer = 0;
} }
...@@ -627,17 +660,71 @@ namespace RTC ...@@ -627,17 +660,71 @@ namespace RTC
if (packet->IsKeyFrame()) if (packet->IsKeyFrame())
MS_DEBUG_TAG(rtp, "sync key frame received"); MS_DEBUG_TAG(rtp, "sync key frame received");
this->rtpSeqManager.Sync(packet->GetSequenceNumber()); // Sync our RTP stream's sequence number and timestamp.
this->rtpTimestampManager.Sync(packet->GetTimestamp()); this->rtpSeqManager.Sync(packet->GetSequenceNumber() - 1);
// Calculate RTP timestamp diff between now and last sent RTP packet. // Sync our RTP stream's RTP timestamp.
if (this->rtpStream->GetMaxPacketMs() != 0u) if (spatialLayer == this->tsReferenceSpatialLayer)
{ {
auto now = DepLibUV::GetTime(); this->tsOffset = 0;
auto diffMs = now - this->rtpStream->GetMaxPacketMs(); }
auto diffTs = diffMs * this->rtpStream->GetClockRate() / 1000; // If this is not the RTP stream we use as TS reference, do NTP based RTP TS synchronization.
else
{
auto* producerTsReferenceRtpStream = GetProducerTsReferenceRtpStream();
auto* producerCurrentRtpStream = GetProducerCurrentRtpStream();
// NOTE: If we are here is because we have Sender Reports for both the
// TS reference stream and the target one.
MS_ASSERT(
producerTsReferenceRtpStream->GetSenderReportNtpMs(),
"no Sender Report for TS reference RTP stream");
MS_ASSERT(
producerCurrentRtpStream->GetSenderReportNtpMs(),
"no Sender Report for current RTP stream");
// Calculate NTP and TS stuff.
auto ntpMs1 = producerTsReferenceRtpStream->GetSenderReportNtpMs();
auto ts1 = producerTsReferenceRtpStream->GetSenderReportTs();
auto ntpMs2 = producerCurrentRtpStream->GetSenderReportNtpMs();
auto ts2 = producerCurrentRtpStream->GetSenderReportTs();
int64_t diffMs;
if (ntpMs2 >= ntpMs1)
diffMs = ntpMs2 - ntpMs1;
else
diffMs = -1 * (ntpMs1 - ntpMs2);
int64_t diffTs = diffMs * this->rtpStream->GetClockRate() / 1000;
uint32_t newTs2 = ts2 - diffTs;
this->rtpTimestampManager.Offset(diffTs); // Apply offset. This is the difference that later must be removed from the
// sending RTP packet.
this->tsOffset = newTs2 - ts1;
}
// Reset tsExtraOffset and lastIncreasedOriginalTs.
this->tsExtraOffset = 0;
this->lastIncreasedOriginalTs = 0;
// When switching to a new stream it may happen that the timestamp of this
// keyframe is lower than the last sent. If so, apply an extra offset to
// "fix" it gradually.
if (packet->GetTimestamp() - this->tsOffset <= this->rtpStream->GetMaxPacketTs())
{
this->tsExtraOffset =
this->rtpStream->GetMaxPacketTs() - packet->GetTimestamp() + this->tsOffset + 1;
this->lastIncreasedOriginalTs = packet->GetTimestamp();
MS_DEBUG_TAG(
simulcast,
"ts extra offset needed [ts in:%" PRIu32 ", ts out:%" PRIu32 ", ts max out:%" PRIu32
", ts offset:%" PRIu32 ", ts extra offset:%" PRIu32 "]",
packet->GetTimestamp(),
packet->GetTimestamp() - this->tsOffset,
this->rtpStream->GetMaxPacketTs(),
this->tsOffset,
this->tsExtraOffset);
} }
if (this->encodingContext) if (this->encodingContext)
...@@ -650,7 +737,6 @@ namespace RTC ...@@ -650,7 +737,6 @@ namespace RTC
if (this->encodingContext && !packet->EncodePayload(this->encodingContext.get())) if (this->encodingContext && !packet->EncodePayload(this->encodingContext.get()))
{ {
this->rtpSeqManager.Drop(packet->GetSequenceNumber()); this->rtpSeqManager.Drop(packet->GetSequenceNumber());
this->rtpTimestampManager.Drop(packet->GetTimestamp());
return; return;
} }
...@@ -665,12 +751,52 @@ namespace RTC ...@@ -665,12 +751,52 @@ namespace RTC
UpdateCurrentLayers(); UpdateCurrentLayers();
} }
// Update RTP seq number and timestamp. // Update RTP seq number and timestamp based on NTP offset.
uint16_t seq; uint16_t seq;
uint32_t timestamp; uint32_t timestamp = packet->GetTimestamp() - this->tsOffset;
if (this->tsExtraOffset)
{
if (timestamp > this->rtpStream->GetMaxPacketTs())
{
MS_DEBUG_TAG(
simulcast,
"ts extra offset done [ts in:%" PRIu32 ", ts out:%" PRIu32 ", ts offset:%" PRIu32
", ts extra offset:%" PRIu32 "]",
packet->GetTimestamp(),
timestamp,
this->tsOffset,
this->tsExtraOffset);
this->tsExtraOffset = 0;
this->lastIncreasedOriginalTs = 0;
}
else if (packet->GetTimestamp() > this->lastIncreasedOriginalTs)
{
this->tsExtraOffset = this->rtpStream->GetMaxPacketTs() - timestamp + 1;
this->lastIncreasedOriginalTs = packet->GetTimestamp();
}
if (this->tsExtraOffset)
{
timestamp += this->tsExtraOffset;
MS_DEBUG_TAG(
simulcast,
"ts extra offset applied [ts in:%" PRIu32 ", ts out:%" PRIu32 ", ts offset:%" PRIu32
", ts extra offset:%" PRIu32 "]",
packet->GetTimestamp(),
timestamp,
this->tsOffset,
this->tsExtraOffset);
}
else
{
this->lastIncreasedOriginalTs = 0;
}
}
this->rtpSeqManager.Input(packet->GetSequenceNumber(), seq); this->rtpSeqManager.Input(packet->GetSequenceNumber(), seq);
this->rtpTimestampManager.Input(packet->GetTimestamp(), timestamp);
// Save original packet fields. // Save original packet fields.
auto origSsrc = packet->GetSsrc(); auto origSsrc = packet->GetSsrc();
...@@ -1041,6 +1167,10 @@ namespace RTC ...@@ -1041,6 +1167,10 @@ namespace RTC
if (producerScore == 0) if (producerScore == 0)
continue; continue;
// We may not yet switch to a different spatial layer.
if (!CanSwitchToSpatialLayer(spatialLayer))
continue;
if (producerScore >= maxProducerScore || producerScore >= 7) if (producerScore >= maxProducerScore || producerScore >= 7)
{ {
newTargetSpatialLayer = spatialLayer; newTargetSpatialLayer = spatialLayer;
...@@ -1076,6 +1206,15 @@ namespace RTC ...@@ -1076,6 +1206,15 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
// If we don't have yet a RTP timestamp reference, set it now.
if (newTargetSpatialLayer != -1 && this->tsReferenceSpatialLayer == -1)
{
MS_DEBUG_TAG(
simulcast, "using spatialLayer:%" PRIi16 " as RTP timestamp reference", newTargetSpatialLayer);
this->tsReferenceSpatialLayer = newTargetSpatialLayer;
}
if (newTargetSpatialLayer == -1) if (newTargetSpatialLayer == -1)
{ {
// Unset current and target layers. // Unset current and target layers.
...@@ -1158,6 +1297,40 @@ namespace RTC ...@@ -1158,6 +1297,40 @@ namespace RTC
EmitScore(); EmitScore();
} }
inline bool SimulcastConsumer::CanSwitchToSpatialLayer(int16_t spatialLayer) const
{
MS_TRACE();
// This method assumes that the caller has verified that there is a valid
// Producer RtpStream for the given spatial layer.
MS_ASSERT(
this->producerRtpStreams.at(spatialLayer),
"no Producer RtpStream for the given spatialLayer:%" PRIi16,
spatialLayer);
// We can switch to the given spatial layer if:
// - we don't have any TS reference spatial layer yet, or
// - the given spatial layer matches the TS reference spatial layer, or
// - both , the RTP streams of our TS reference spatial layer and the given
// spatial layer, have Sender Report.
//
// clang-format off
bool canSwitch = (
this->tsReferenceSpatialLayer == -1 ||
spatialLayer == this->tsReferenceSpatialLayer ||
(
GetProducerTsReferenceRtpStream()->GetSenderReportNtpMs() &&
this->producerRtpStreams.at(spatialLayer)->GetSenderReportNtpMs()
)
);
// clang-format on
if (!canSwitch)
MS_DEBUG_TAG(simulcast, "cannot switch to spatialLayer:%" PRIi16, spatialLayer);
return canSwitch;
}
inline void SimulcastConsumer::EmitScore() const inline void SimulcastConsumer::EmitScore() const
{ {
MS_TRACE(); MS_TRACE();
...@@ -1210,6 +1383,17 @@ namespace RTC ...@@ -1210,6 +1383,17 @@ namespace RTC
return this->producerRtpStreams.at(this->targetSpatialLayer); return this->producerRtpStreams.at(this->targetSpatialLayer);
} }
inline RTC::RtpStream* SimulcastConsumer::GetProducerTsReferenceRtpStream() const
{
MS_TRACE();
if (this->tsReferenceSpatialLayer == -1)
return nullptr;
// This may return nullptr.
return this->producerRtpStreams.at(this->tsReferenceSpatialLayer);
}
inline void SimulcastConsumer::OnRtpStreamScore( inline void SimulcastConsumer::OnRtpStreamScore(
RTC::RtpStream* /*rtpStream*/, uint8_t /*score*/, uint8_t /*previousScore*/) RTC::RtpStream* /*rtpStream*/, uint8_t /*score*/, uint8_t /*previousScore*/)
{ {
......
...@@ -839,6 +839,14 @@ namespace RTC ...@@ -839,6 +839,14 @@ namespace RTC
this->listener->OnTransportProducerRtpStreamScore(this, producer, rtpStream, score, previousScore); this->listener->OnTransportProducerRtpStreamScore(this, producer, rtpStream, score, previousScore);
} }
inline void Transport::OnProducerRtcpSenderReport(
RTC::Producer* producer, RTC::RtpStream* rtpStream, bool first)
{
MS_TRACE();
this->listener->OnTransportProducerRtcpSenderReport(this, producer, rtpStream, first);
}
inline void Transport::OnProducerRtpPacketReceived(RTC::Producer* producer, RTC::RtpPacket* packet) inline void Transport::OnProducerRtpPacketReceived(RTC::Producer* producer, RTC::RtpPacket* packet)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -25,7 +25,7 @@ void validate(SeqManager<uint16_t>& seqManager, std::vector<TestSeqManagerInput> ...@@ -25,7 +25,7 @@ void validate(SeqManager<uint16_t>& seqManager, std::vector<TestSeqManagerInput>
for (auto& element : inputs) for (auto& element : inputs)
{ {
if (element.sync) if (element.sync)
seqManager.Sync(element.input); seqManager.Sync(element.input - 1);
if (element.offset) if (element.offset)
seqManager.Offset(element.offset); seqManager.Offset(element.offset);
......
#include "common.hpp"
#include "DepLibUV.hpp"
#include "Utils.hpp"
#include "catch.hpp"
using namespace Utils;
SCENARIO("Utils::Time::TimeMs2Ntp() and Utils::Time::Ntp2TimeMs()")
{
auto now = DepLibUV::GetTime();
auto ntp = Time::TimeMs2Ntp(now);
auto now2 = Time::Ntp2TimeMs(ntp);
auto ntp2 = Time::TimeMs2Ntp(now2);
REQUIRE(now2 == now);
REQUIRE(ntp2.seconds == ntp.seconds);
REQUIRE(ntp2.fractions == ntp.fractions);
}
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论