提交 1a155323 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo 提交者: GitHub

Remote bitrate estimator (#80)

Habemus REMB

* rbe: initial commit

* rbe: new 'LatesTimestamp' time utility

* rbe: new log tag 'rbe' (Remote Bitrate Estimator)

* rbe: logging and assertion normalization

* rbe: use Mediasoup RtpPacket and ExtensionHeader implementations

* rbe: don't consider RTCP Feedback packets for now. TODO

* rbe: use internal RtpDataCounters

* rbe: set a fixed minimum bit rate

* rbe: remove adaptive threshold experiment

...until we understand the adaptive threshold parameters

http://c3lab.poliba.it/images/6/65/Gcc-analysis.pdf (section 5)

* rbe: add files into .gyp file

* add 'goog-remb' to the supported RTP capabilties

* rbe: rename 'RemoteBitrateObserver' to 'RemoteBitrateEstimator::Listener'

* rbe: make use of the remote bitrate estimator

* rtcp: REMB packet

* remb: send RTCP REMB messages when remote bitrate calculator triggers a change

* remb: cosmetic

* remb: update doc

* rbe: cosmetic

* rtcp: make REMB packet a specialization of AFB

* rbe: remove unused RemoteBitrateEstimator::IncomingPacketFeedbackVector()

Note: also removed in original implementation

* RateCalculator: new Reset() interface

* rbe: Mediasoup-ization first commit

get rid of BweDefines.hpp

* prepend 'this->' to instance members'

* rbe: prepend data members with 'this->' and camelCase them

* rbe: camelCase local variables and method arguments

* rbe: use tabs and inline small and simple member methods

* rbe: remote ctags file

* rbe: mayor style changes

* rbe: add MS_TRACE macro

* rbe: use 'default' keyword for empty desructor on base class

* rbe: more cleanup

* rbe: declare static data before any other

* rbe: start comments with lowercase

* rbe: always use adaptive thresholds

* include missing header file

* remb: make getters const

* Update REMB stuff to new RTP extension API

* remb: use specific API to get abs exten.

* Clean up how REMB, NACK and RTP header extensions are checked.
上级 7adc2a94
......@@ -147,6 +147,7 @@ Application information will be relayed from the remote RTP receiver to the corr
### REMB (for now a subtype of AFB)
In future, this information is to be consumed by the local RTP Senders in order to adapt their transmission rate to the availability of the remote RTP receivers.
REMB RTCP is generated locally based on the remote bitrate estimation.
## Mediasoup internal behaviour for each type of RTCP
......@@ -172,6 +173,7 @@ In future, this information is to be consumed by the local RTP Senders in order
-------------|-----|-----|------|-----|------|------|------|------|-----|------|
RtpSender | B | B | B | B | I | | I | | | C |
RtpReceiver | | | | | | I | | I | | |
RtpTransport| | | | | | | | | | G |
( ): Does not apply.
......
......@@ -133,7 +133,8 @@ let supportedRtpCapabilities =
{ type: 'nack', parameter: 'app' }, // Bypassed.
{ type: 'ccm', parameter: 'fir' }, // Bypassed.
{ type: 'ack', parameter: 'rpsi' }, // Bypassed.
{ type: 'ack', parameter: 'app' } // Bypassed.
{ type: 'ack', parameter: 'app' }, // Bypassed.
{ type: 'goog-remb' } // Locally generated.
]
},
{
......@@ -149,7 +150,8 @@ let supportedRtpCapabilities =
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
]
},
{
......@@ -169,7 +171,8 @@ let supportedRtpCapabilities =
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
]
},
{
......@@ -189,7 +192,8 @@ let supportedRtpCapabilities =
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
]
},
{
......@@ -205,7 +209,8 @@ let supportedRtpCapabilities =
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
]
}
],
......
......@@ -9,16 +9,23 @@ namespace RTC { namespace RTCP
class FeedbackPsAfbPacket
: public FeedbackPsPacket
{
public:
typedef enum Application : uint8_t
{
UNKNOWN = 0,
REMB = 1
} Application;
public:
static FeedbackPsAfbPacket* Parse(const uint8_t* data, size_t len);
public:
// Parsed Report. Points to an external data.
explicit FeedbackPsAfbPacket(CommonHeader* commonHeader);
FeedbackPsAfbPacket(uint32_t sender_ssrc, uint32_t media_ssrc);
explicit FeedbackPsAfbPacket(CommonHeader* commonHeader, Application application = UNKNOWN);
FeedbackPsAfbPacket(uint32_t sender_ssrc, uint32_t media_ssrc, Application application = UNKNOWN);
virtual ~FeedbackPsAfbPacket() {};
uint8_t* GetData() const;
Application GetApplication() const;
/* Pure virtual methods inherited from Packet. */
public:
......@@ -27,6 +34,7 @@ namespace RTC { namespace RTCP
virtual size_t GetSize() const override;
private:
Application application = UNKNOWN;
uint8_t* data = nullptr;
size_t size = 0;
};
......@@ -34,22 +42,25 @@ namespace RTC { namespace RTCP
/* Inline instance methods. */
inline
FeedbackPsAfbPacket::FeedbackPsAfbPacket(CommonHeader* commonHeader):
FeedbackPsAfbPacket::FeedbackPsAfbPacket(CommonHeader* commonHeader, Application application):
FeedbackPsPacket(commonHeader)
{
this->size = ((ntohs(commonHeader->length) + 1) * 4) - (sizeof(CommonHeader) + sizeof(FeedbackPacket::Header));
this->data = (uint8_t*)commonHeader + sizeof(CommonHeader) + sizeof(FeedbackPacket::Header);
this->application = application;
}
inline
FeedbackPsAfbPacket::FeedbackPsAfbPacket(uint32_t sender_ssrc, uint32_t media_ssrc):
FeedbackPsAfbPacket::FeedbackPsAfbPacket(uint32_t sender_ssrc, uint32_t media_ssrc, Application application):
FeedbackPsPacket(FeedbackPs::MessageType::AFB, sender_ssrc, media_ssrc)
{}
{
this->application = application;
}
inline
uint8_t* FeedbackPsAfbPacket::GetData() const
FeedbackPsAfbPacket::Application FeedbackPsAfbPacket::GetApplication() const
{
return this->data;
return this->application;
}
inline
......
#ifndef MS_RTC_RTCP_FEEDBACK_REMB_HPP
#define MS_RTC_RTCP_FEEDBACK_REMB_HPP
#include "common.hpp"
#include "RTC/RTCP/FeedbackPsAfb.hpp"
#include <vector>
/* draft-alvestrand-rmcat-remb-03
* RTCP message for Receiver Estimated Maximum Bitrate (REMB)
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|V=2|P| FMT=15 | PT=206 | length |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
0 | SSRC of packet sender |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
4 | SSRC of media source |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
8 | Unique identifier 'R' 'E' 'M' 'B' |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12 | Num SSRC | BR Exp | BR Mantissa |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
16 | SSRC feedback |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ... |
*/
namespace RTC { namespace RTCP
{
class FeedbackPsRembPacket
: public FeedbackPsAfbPacket
{
public:
// 'R' 'E' 'M' 'B'.
static uint32_t UniqueIdentifier;
public:
static FeedbackPsRembPacket* Parse(const uint8_t* data, size_t len);
public:
// Parsed Report. Points to an external data.
explicit FeedbackPsRembPacket(CommonHeader* commonHeader);
FeedbackPsRembPacket(uint32_t sender_ssrc, uint32_t media_ssrc);
virtual ~FeedbackPsRembPacket() {};
bool IsCorrect();
void SetBitrate(uint64_t bitrate);
void SetSsrcs(const std::vector<uint32_t>& ssrcs);
uint64_t GetBitrate();
const std::vector<uint32_t>& GetSsrcs();
/* Pure virtual methods inherited from Packet. */
public:
virtual void Dump() const override;
virtual size_t Serialize(uint8_t* buffer) override;
virtual size_t GetSize() const override;
private:
std::vector<uint32_t> ssrcs;
// Bitrate represented in bps
uint64_t bitrate;
bool isCorrect = true;
};
/* Inline instance methods. */
inline
FeedbackPsRembPacket::FeedbackPsRembPacket(uint32_t sender_ssrc, uint32_t media_ssrc):
FeedbackPsAfbPacket(sender_ssrc, media_ssrc, FeedbackPsAfbPacket::Application::REMB)
{}
inline
bool FeedbackPsRembPacket::IsCorrect()
{
return this->isCorrect;
}
inline
void FeedbackPsRembPacket::SetBitrate(uint64_t bitrate)
{
this->bitrate = bitrate;
}
inline
void FeedbackPsRembPacket::SetSsrcs(const std::vector<uint32_t>& ssrcs)
{
this->ssrcs = ssrcs;
}
inline
uint64_t FeedbackPsRembPacket::GetBitrate()
{
return this->bitrate;
}
inline
const std::vector<uint32_t>& FeedbackPsRembPacket::GetSsrcs()
{
return this->ssrcs;
}
inline
size_t FeedbackPsRembPacket::GetSize() const
{
return FeedbackPsPacket::GetSize() + 8 + (sizeof(uint32_t) * this->ssrcs.size());
}
}}
#endif
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_AIMD_RATE_CONTROL_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_AIMD_RATE_CONTROL_HPP
#include "common.hpp"
#include "RTC/RemoteBitrateEstimator/RateControlRegion.hpp"
#include "RTC/RemoteBitrateEstimator/RateControlInput.hpp"
#include "RTC/RemoteBitrateEstimator/OveruseDetector.hpp"
// A rate control implementation based on additive increases of
// bitrate when no over-use is detected and multiplicative decreases when
// over-uses are detected. When we think the available bandwidth has changes or
// is unknown, we will switch to a "slow-start mode" where we increase
// multiplicatively.
namespace RTC
{
class AimdRateControl
{
private:
static constexpr int64_t kDefaultRttMs = 200;
// (jmillan) replacement from 'congestion_controller::GetMinBitrateBps()'.
static constexpr int kMinBitrateBps = 10000;
private:
enum RateControlState
{
kRcHold,
kRcIncrease,
kRcDecrease
};
public:
AimdRateControl();
virtual ~AimdRateControl() = default;
// Returns true if there is a valid estimate of the incoming bitrate, false
// otherwise.
bool ValidEstimate() const;
void SetStartBitrate(int startBitrateBps);
void SetMinBitrate(int minBitrateBps);
int64_t GetFeedbackInterval() const;
// Returns true if the bitrate estimate hasn't been changed for more than
// an RTT, or if the incomingBitrate is less than half of the current
// estimate. Should be used to decide if we should reduce the rate further
// when over-using.
bool TimeToReduceFurther(int64_t timeNow, uint32_t incomingBitrateBps) const;
uint32_t LatestEstimate() const;
uint32_t UpdateBandwidthEstimate(int64_t nowMs);
void SetRtt(int64_t rtt);
void Update(const RateControlInput* input, int64_t nowMs);
void SetEstimate(int bitrateBps, int64_t nowMs);
public:
// Returns the increase rate which is used when used bandwidth is near the
// maximal available bandwidth.
virtual int GetNearMaxIncreaseRateBps() const;
virtual int GetLastBitrateDecreaseBps() const;
private:
// Update the target bitrate according based on, among other things,
// the current rate control state, the current target bitrate and the incoming
// bitrate. When in the "increase" state the bitrate will be increased either
// additively or multiplicatively depending on the rate control region. When
// in the "decrease" state the bitrate will be decreased to slightly below the
// incoming bitrate. When in the "hold" state the bitrate will be kept
// constant to allow built up queues to drain.
uint32_t ChangeBitrate(uint32_t currentBitrate, uint32_t incomingBitrate, int64_t nowMs);
// Clamps newBitrateBps to within the configured min bitrate and a linear
// function of the incoming bitrate, so that the new bitrate can't grow too
// large compared to the bitrate actually being received by the other end.
uint32_t ClampBitrate(uint32_t newBitrateBps, uint32_t incomingBitrateBps) const;
uint32_t MultiplicativeRateIncrease(int64_t nowMs, int64_t lastMs, uint32_t currentBitrateBps) const;
uint32_t AdditiveRateIncrease(int64_t nowMs, int64_t lastMs) const;
void UpdateChangePeriod(int64_t nowMs);
void UpdateMaxBitRateEstimate(float incomingBitRateKbps);
void ChangeState(const RateControlInput& input, int64_t nowMs);
void ChangeState(RateControlState newState);
void ChangeRegion(RateControlRegion region);
private:
uint32_t minConfiguredBitrateBps = kMinBitrateBps;
uint32_t maxConfiguredBitrateBps = 30000000;
uint32_t currentBitrateBps = this->maxConfiguredBitrateBps;
float avgMaxBitrateKbps = -1.0f;
float varMaxBitrateKbps = 0.4f;
RateControlState rateControlState = kRcHold;
RateControlRegion rateControlRegion = kRcMaxUnknown;
int64_t timeLastBitrateChange = -1;
RateControlInput currentInput;
bool updated = false;
int64_t timeFirstIncomingEstimate = -1;
bool bitrateIsInitialized = false;
float beta = 0.85f;
int64_t rtt = kDefaultRttMs;
int lastDecrease;
};
/* Inline methods. */
inline
AimdRateControl::AimdRateControl() :
currentInput(kBwNormal, 0, 1.0)
{}
inline
void AimdRateControl::SetStartBitrate(int startBitrateBps)
{
this->currentBitrateBps = startBitrateBps;
this->bitrateIsInitialized = true;
}
inline
void AimdRateControl::SetMinBitrate(int minBitrateBps)
{
this->minConfiguredBitrateBps = minBitrateBps;
this->currentBitrateBps = std::max<int>(minBitrateBps, this->currentBitrateBps);
}
inline
bool AimdRateControl::ValidEstimate() const
{
return this->bitrateIsInitialized;
}
inline
uint32_t AimdRateControl::LatestEstimate() const
{
return this->currentBitrateBps;
}
inline
uint32_t AimdRateControl::UpdateBandwidthEstimate(int64_t nowMs)
{
this->currentBitrateBps = ChangeBitrate(this->currentBitrateBps, this->currentInput.incomingBitrate, nowMs);
return this->currentBitrateBps;
}
inline
void AimdRateControl::SetRtt(int64_t rtt)
{
this->rtt = rtt;
}
inline
void AimdRateControl::SetEstimate(int bitrateBps, int64_t nowMs)
{
this->updated = true;
this->bitrateIsInitialized = true;
this->currentBitrateBps = ClampBitrate(bitrateBps, bitrateBps);
this->timeLastBitrateChange = nowMs;
}
inline
int AimdRateControl::GetLastBitrateDecreaseBps() const
{
return this->lastDecrease;
}
inline
uint32_t AimdRateControl::AdditiveRateIncrease(int64_t nowMs, int64_t lastMs) const
{
return static_cast<uint32_t>((nowMs - lastMs) * GetNearMaxIncreaseRateBps() / 1000);
}
inline
void AimdRateControl::ChangeRegion(RateControlRegion region)
{
this->rateControlRegion = region;
}
inline
void AimdRateControl::ChangeState(RateControlState newState)
{
this->rateControlState = newState;
}
}
#endif
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_BANDWIDTH_USAGE_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_BANDWIDTH_USAGE_HPP
// webrtc/modules/remote_bitrate_estimator/include/bwe_defines.h
namespace RTC
{
enum BandwidthUsage
{
kBwNormal,
kBwUnderusing,
kBwOverusing
};
}
#endif
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_INTER_ARRIVAL_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_INTER_ARRIVAL_HPP
#include "common.hpp"
namespace RTC
{
// Helper class to compute the inter-arrival time delta and the size delta
// between two timestamp groups. A timestamp is a 32 bit unsigned number with
// a client defined rate.
class InterArrival
{
public:
// After this many packet groups received out of order InterArrival will
// reset, assuming that clocks have made a jump.
static constexpr int kReorderedResetThreshold = 3;
static constexpr int64_t kArrivalTimeOffsetThresholdMs = 3000;
// A timestamp group is defined as all packets with a timestamp which are at
// most timestamp_group_length_ticks older than the first timestamp in that
// group.
InterArrival(uint32_t timestamp_group_length_ticks, double timestamp_to_ms_coeff, bool enable_burst_grouping);
// This function returns true if a delta was computed, or false if the current
// group is still incomplete or if only one group has been completed.
// |timestamp| is the timestamp.
// |arrival_time_ms| is the local time at which the packet arrived.
// |packet_size| is the size of the packet.
// |timestamp_delta| (output) is the computed timestamp delta.
// |arrival_time_delta_ms| (output) is the computed arrival-time delta.
// |packet_size_delta| (output) is the computed size delta.
bool ComputeDeltas(uint32_t timestamp, int64_t arrival_time_ms, int64_t system_time_ms, size_t packet_size, uint32_t* timestamp_delta, int64_t* arrival_time_delta_ms, int* packet_size_delta);
private:
struct TimestampGroup
{
TimestampGroup();
bool IsFirstPacket() const;
size_t size;
uint32_t first_timestamp;
uint32_t timestamp;
int64_t complete_time_ms;
int64_t last_system_time_ms;
};
// Returns true if the packet with timestamp |timestamp| arrived in order.
bool PacketInOrder(uint32_t timestamp);
// Returns true if the last packet was the end of the current batch and the
// packet with |timestamp| is the first of a new batch.
bool NewTimestampGroup(int64_t arrival_time_ms, uint32_t timestamp) const;
bool BelongsToBurst(int64_t arrival_time_ms, uint32_t timestamp) const;
void Reset();
const uint32_t kTimestampGroupLengthTicks;
TimestampGroup currentTimestampGroup;
TimestampGroup prevTimestampGroup;
double timestampToMsCoeff;
bool burstGrouping;
int numConsecutiveReorderedPackets;
};
/* Inline methods. */
inline
InterArrival::TimestampGroup::TimestampGroup() :
size(0),
first_timestamp(0),
timestamp(0),
complete_time_ms(-1)
{}
inline
bool InterArrival::TimestampGroup::IsFirstPacket() const
{
return complete_time_ms == -1;
}
inline
InterArrival::InterArrival(uint32_t timestamp_group_length_ticks, double timestamp_to_ms_coeff, bool enable_burst_grouping) :
kTimestampGroupLengthTicks(timestamp_group_length_ticks),
currentTimestampGroup(),
prevTimestampGroup(),
timestampToMsCoeff(timestamp_to_ms_coeff),
burstGrouping(enable_burst_grouping),
numConsecutiveReorderedPackets(0)
{}
}
#endif
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_OVERUSE_DETECTOR_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_OVERUSE_DETECTOR_HPP
#include "common.hpp"
#include "RTC/RemoteBitrateEstimator/RateControlRegion.hpp"
#include "RTC/RemoteBitrateEstimator/BandwidthUsage.hpp"
#include <list>
namespace RTC
{
class OveruseDetector
{
private:
static constexpr double kOverUsingTimeThreshold = 10;
public:
OveruseDetector() = default;
// Update the detection state based on the estimated inter-arrival time delta
// offset. |timestampDelta| is the delta between the last timestamp which the
// estimated offset is based on and the last timestamp on which the last
// offset was based on, representing the time between detector updates.
// |numOfDeltas| is the number of deltas the offset estimate is based on.
// Returns the state after the detection update.
BandwidthUsage Detect(double offset, double timestampDelta, int numOfDeltas, int64_t nowMs);
// Returns the current detector state.
BandwidthUsage State() const;
private:
void UpdateThreshold(double modifiedOffset, int64_t nowMs);
private:
double kUp = 0.0087;
double kDown = 0.039;
double overusingTimeThreshold = kOverUsingTimeThreshold;
double threshold = 12.5;
int64_t lastUpdateMs = -1;
double prevOffset = 0.0;
double timeOverUsing = -1;
int overuseCounter = 0;
BandwidthUsage hypothesis = kBwNormal;
};
inline
BandwidthUsage OveruseDetector::State() const
{
return this->hypothesis;
}
}
#endif
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_OVERUSE_ESTIMATOR_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_OVERUSE_ESTIMATOR_HPP
#include "common.hpp"
#include "RTC/RemoteBitrateEstimator/BandwidthUsage.hpp"
#include <deque>
#include <cstring> // std::memcpy()
namespace RTC
{
// (jmillan) borrowed from webrtc/common_types.h
//
// Bandwidth over-use detector options.
// These are used to drive experimentation with bandwidth estimation parameters.
// See modules/remote_bitrate_estimator/overuse_detector.h
struct OverUseDetectorOptions
{
OverUseDetectorOptions();
double initialSlope;
double initialOffset;
double initialE[2][2];
double initialProcessNoise[2];
double initialAvgNoise;
double initialVarNoise;
};
class OveruseEstimator
{
public:
explicit OveruseEstimator(const OverUseDetectorOptions& options);
~OveruseEstimator();
// Update the estimator with a new sample. The deltas should represent deltas
// between timestamp groups as defined by the InterArrival class.
// |current_hypothesis| should be the hypothesis of the over-use detector at
// this time.
void Update(int64_t tDelta, double tsDelta, int sizeDelta, BandwidthUsage currentHypothesis, int64_t nowMs);
// Returns the estimated noise/jitter variance in ms^2.
double GetVarNoise() const;
// Returns the estimated inter-arrival time delta offset in ms.
double GetOffset() const;
// Returns the number of deltas which the current over-use estimator state is
// based on.
unsigned int GetNumOfDeltas() const;
private:
double UpdateMinFramePeriod(double tsDelta);
void UpdateNoiseEstimate(double residual, double tsDelta, bool stableState);
private:
// Must be first member variable. Cannot be const because we need to be copyable.
OverUseDetectorOptions options;
uint16_t numOfDeltas;
double slope;
double offset;
double prevOffset;
double E[2][2];
double processNoise[2];
double avgNoise;
double varNoise;
std::deque<double> tsDeltaHist;
};
/* Inline methods. */
inline
OverUseDetectorOptions::OverUseDetectorOptions() :
initialSlope(8.0 / 512.0),
initialOffset(0),
initialE(),
initialProcessNoise(),
initialAvgNoise(0.0),
initialVarNoise(50)
{
initialE[0][0] = 100;
initialE[1][1] = 1e-1;
initialE[0][1] = initialE[1][0] = 0;
initialProcessNoise[0] = 1e-13;
initialProcessNoise[1] = 1e-3;
}
inline
OveruseEstimator::OveruseEstimator(const OverUseDetectorOptions& options) :
options(options),
numOfDeltas(0),
slope(this->options.initialSlope),
offset(this->options.initialOffset),
prevOffset(this->options.initialOffset),
E(),
processNoise(),
avgNoise(this->options.initialAvgNoise),
varNoise(this->options.initialVarNoise),
tsDeltaHist()
{
std::memcpy(this->E, this->options.initialE, sizeof(this->E));
std::memcpy(this->processNoise, this->options.initialProcessNoise, sizeof(this->processNoise));
}
inline
OveruseEstimator::~OveruseEstimator()
{
this->tsDeltaHist.clear();
}
inline
double OveruseEstimator::GetVarNoise() const
{
return this->varNoise;
}
inline
double OveruseEstimator::GetOffset() const
{
return this->offset;
}
inline
unsigned int OveruseEstimator::GetNumOfDeltas() const
{
return this->numOfDeltas;
}
}
#endif
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_RATE_CONTROL_INPUT_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_RATE_CONTROL_INPUT_HPP
#include "common.hpp"
#include "RTC/RemoteBitrateEstimator/BandwidthUsage.hpp"
// webrtc/modules/remote_bitrate_estimator/include/bweDefines.h
namespace RTC
{
struct RateControlInput
{
RateControlInput(BandwidthUsage bwState, const uint32_t incomingBitrate, double noiseVar);
BandwidthUsage bwState;
uint32_t incomingBitrate;
double noiseVar;
};
/* Inline methods. */
inline
RateControlInput::RateControlInput(BandwidthUsage bwState, const uint32_t incomingBitrate, double noiseVar) :
bwState(bwState),
incomingBitrate(incomingBitrate),
noiseVar(noiseVar)
{}
}
#endif
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_RATE_CONTROL_REGION_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_RATE_CONTROL_REGION_HPP
// webrtc/modules/remote_bitrate_estimator/include/bwe_defines.h
namespace RTC
{
enum RateControlRegion
{
kRcNearMax,
kRcAboveMax,
kRcMaxUnknown
};
}
#endif
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This class estimates the incoming available bandwidth.
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_HPP
#include "common.hpp"
#include "RTC/RtpPacket.hpp"
#include <cassert>
#include <map>
#include <vector>
namespace RTC
{
// (jmillan) borrowed from webrtc/modules/include/module_common_types.h
//
// Interface used by the CallStats class to distribute call statistics.
// Callbacks will be triggered as soon as the class has been registered to a
// CallStats object using RegisterStatsObserver.
class CallStatsObserver
{
public:
virtual ~CallStatsObserver() = default;
virtual void OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) = 0;
};
class RemoteBitrateEstimator : public CallStatsObserver
{
public:
// Used to signal changes in bitrate estimates for the incoming streams.
class Listener
{
public:
// Called when a receive channel group has a new bitrate estimate for the incoming streams.
virtual void onReceiveBitrateChanged(const std::vector<uint32_t>& ssrcs, uint32_t bitrate) = 0;
};
protected:
static const int64_t kProcessIntervalMs = 500;
static const int64_t kStreamTimeOutMs = 2000;
public:
virtual ~RemoteBitrateEstimator() = default;
// Called for each incoming packet. Updates the incoming payload bitrate
// estimate and the over-use detector. If an over-use is detected the
// remote bitrate estimate will be updated. Note that |payload_size| is the
// packet size excluding headers.
// Note that |arrival_time_ms| can be of an arbitrary time base.
virtual void IncomingPacket(int64_t arrival_time_ms, size_t payload_size, const RtpPacket& packet, const uint32_t absSendTime) = 0;
// Removes all data for |ssrc|.
virtual void RemoveStream(uint32_t ssrc) = 0;
// Returns true if a valid estimate exists and sets |bitrate_bps| to the
// estimated payload bitrate in bits per second. |ssrcs| is the list of ssrcs
// currently being received and of which the bitrate estimate is based upon.
virtual bool LatestEstimate(std::vector<uint32_t>* ssrcs, uint32_t* bitrate_bps) const = 0;
virtual void SetMinBitrate(int min_bitrate_bps) = 0;
// (jmillan) borrowed from webrtc/modules/include/module.h.
//
// Returns the number of milliseconds until the module wants a worker
// thread to call Process.
// This method is called on the same worker thread as Process will
// be called on.
// TODO(tommi): Almost all implementations of this function, need to know
// the current tick count. Consider passing it as an argument. It could
// also improve the accuracy of when the next callback occurs since the
// thread that calls Process() will also have it's tick count reference
// which might not match with what the implementations use.
virtual int64_t TimeUntilNextProcess() = 0;
// Process any pending tasks such as timeouts.
// Called on a worker thread.
virtual void Process() = 0;
};
}
#endif
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_ABS_SEND_TIME_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_ABS_SEND_TIME_HPP
#include "common.hpp"
#include "RTC/RemoteBitrateEstimator/AimdRateControl.hpp"
#include "RTC/RemoteBitrateEstimator/RemoteBitrateEstimator.hpp"
#include "RTC/RemoteBitrateEstimator/InterArrival.hpp"
#include "RTC/RemoteBitrateEstimator/OveruseDetector.hpp"
#include "RTC/RemoteBitrateEstimator/OveruseEstimator.hpp"
#include "RTC/RtpDataCounter.hpp"
#include "Logger.hpp"
#include <list>
#include <map>
#include <memory>
#include <vector>
#include <cassert>
namespace RTC
{
struct Probe
{
Probe(int64_t sendTimeMs, int64_t recvTimeMs, size_t payloadSize);
int64_t sendTimeMs;
int64_t recvTimeMs;
size_t payloadSize;
};
struct Cluster
{
int GetSendBitrateBps() const;
int GetRecvBitrateBps() const;
float sendMeanMs = 0.0f;
float recvMeanMs = 0.0f;
// TODO(holmer): Add some variance metric as well?
size_t meanSize = 0;
int count = 0;
int numAboveMinDelta = 0;
};
class RemoteBitrateEstimatorAbsSendTime : public RemoteBitrateEstimator
{
private:
static bool IsWithinClusterBounds(int sendDeltaMs, const Cluster& clusterAggregate);
static void AddCluster(std::list<Cluster>* clusters, Cluster* cluster);
public:
RemoteBitrateEstimatorAbsSendTime(Listener* observer);
virtual ~RemoteBitrateEstimatorAbsSendTime() = default;
void IncomingPacket(int64_t arrivalTimeMs, size_t payloadSize, const RtpPacket& packet, const uint32_t absSendTime) override;
// This class relies on Process() being called periodically (at least once
// every other second) for streams to be timed out properly.
void Process() override;
int64_t TimeUntilNextProcess() override;
void OnRttUpdate(int64_t avgRttMs, int64_t maxRttMs) override;
void RemoveStream(uint32_t ssrc) override;
bool LatestEstimate(std::vector<uint32_t>* ssrcs, uint32_t* bitrateBps) const override;
void SetMinBitrate(int minBitrateBps) override;
private:
typedef std::map<uint32_t, int64_t> Ssrcs;
enum class ProbeResult
{
kBitrateUpdated,
kNoUpdate
};
private:
void IncomingPacketInfo(int64_t arrivalTimeMs, uint32_t sendTime_24bits, size_t payloadSize, uint32_t ssrc);
void ComputeClusters(std::list<Cluster>* clusters) const;
std::list<Cluster>::const_iterator FindBestProbe(const std::list<Cluster>& clusters) const;
// Returns true if a probe which changed the estimate was detected.
ProbeResult ProcessClusters(int64_t nowMs);
bool IsBitrateImproving(int probeBitrateBps) const;
void TimeoutStreams(int64_t nowMs);
private:
Listener* const observer;
std::unique_ptr<InterArrival> interArrival;
std::unique_ptr<OveruseEstimator> estimator;
OveruseDetector detector;
RateCalculator incomingBitrate;
bool incomingBitrateInitialized = false;
std::vector<int> recentPropagationDeltaMs;
std::vector<int64_t> recentUpdateTimeMs;
std::list<Probe> probes;
size_t totalProbesReceived = 0;
int64_t firstPacketTimeMs = -1;
int64_t lastUpdateMs = -1;
bool umaRecorded = false;
Ssrcs ssrcs;
AimdRateControl remoteRate;
};
/* Inline Methods. */
inline
Probe::Probe(int64_t sendTimeMs, int64_t recvTimeMs, size_t payloadSize) :
sendTimeMs(sendTimeMs),
recvTimeMs(recvTimeMs),
payloadSize(payloadSize)
{}
inline
int Cluster::GetSendBitrateBps() const
{
assert(sendMeanMs > 0.0f);
return meanSize * 8 * 1000 / sendMeanMs;
}
inline
int Cluster::GetRecvBitrateBps() const
{
assert(recvMeanMs > 0.0f);
return meanSize * 8 * 1000 / recvMeanMs;
}
inline
RemoteBitrateEstimatorAbsSendTime::RemoteBitrateEstimatorAbsSendTime(Listener* observer) :
observer(observer),
interArrival(),
estimator(),
detector(),
incomingBitrate()
{}
inline
void RemoteBitrateEstimatorAbsSendTime::Process()
{}
inline
int64_t RemoteBitrateEstimatorAbsSendTime::TimeUntilNextProcess()
{
const int64_t kDisabledModuleTime = 1000;
return kDisabledModuleTime;
}
inline
void RemoteBitrateEstimatorAbsSendTime::OnRttUpdate(int64_t avgRttMs, int64_t maxRttMs)
{
(void) maxRttMs;
this->remoteRate.SetRtt(avgRttMs);
}
inline
void RemoteBitrateEstimatorAbsSendTime::RemoveStream(uint32_t ssrc)
{
this->ssrcs.erase(ssrc);
}
inline
void RemoteBitrateEstimatorAbsSendTime::SetMinBitrate(int minBitrateBps)
{
this->remoteRate.SetMinBitrate(minBitrateBps);
}
}
#endif
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_SINGLE_STREAM_HPP
#define MS_RTC_REMOTE_BITRATE_ESTIMATOR_SINGLE_STREAM_HPP
#include "common.hpp"
#include "RTC/RemoteBitrateEstimator/AimdRateControl.hpp"
#include "RTC/RemoteBitrateEstimator/RemoteBitrateEstimator.hpp"
#include "RTC/RemoteBitrateEstimator/OveruseEstimator.hpp"
#include "RTC/RemoteBitrateEstimator/InterArrival.hpp"
#include "RTC/RtpDataCounter.hpp"
#include <map>
#include <memory>
#include <vector>
namespace RTC
{
class RemoteBitrateEstimatorSingleStream :
public RemoteBitrateEstimator
{
private:
static constexpr double kTimestampToMs = 1.0 / 90.0;
public:
RemoteBitrateEstimatorSingleStream(Listener* observer);
virtual ~RemoteBitrateEstimatorSingleStream();
void IncomingPacket(int64_t arrivalTimeMs, size_t payloadSize, const RtpPacket& packet, const uint32_t transmissionTimeOffset) override;
void Process() override;
int64_t TimeUntilNextProcess() override;
void OnRttUpdate(int64_t avgRttMs, int64_t maxRttMs) override;
void RemoveStream(uint32_t ssrc) override;
bool LatestEstimate(std::vector<uint32_t>* ssrcs, uint32_t* bitrateBps) const override;
void SetMinBitrate(int minBitrateBps) override;
private:
struct Detector
{
enum
{
kTimestampGroupLengthMs = 5
};
explicit Detector(int64_t lastPacketTimeMs, const OverUseDetectorOptions& options, bool enableBurstGrouping);
int64_t lastPacketTimeMs;
InterArrival interArrival;
OveruseEstimator estimator;
OveruseDetector detector;
};
private:
typedef std::map<uint32_t, Detector*> SsrcOveruseEstimatorMap;
private:
// Triggers a new estimate calculation.
void UpdateEstimate(int64_t timeNow);
void GetSsrcs(std::vector<uint32_t>* ssrcs) const;
// Returns |remoteRate| if the pointed to object exists,
// otherwise creates it.
AimdRateControl* GetRemoteRate();
private:
SsrcOveruseEstimatorMap overuseDetectors;
RateCalculator incomingBitrate;
uint32_t lastValidIncomingBitrate = 0;
std::unique_ptr<AimdRateControl> remoteRate;
Listener* observer;
int64_t lastProcessTime = -1;
int64_t processIntervalMs;
bool umaRecorded = false;
};
/* Inline Methods. */
inline
RemoteBitrateEstimatorSingleStream::Detector::Detector(int64_t lastPacketTimeMs, const OverUseDetectorOptions& options, bool enableBurstGrouping) :
lastPacketTimeMs(lastPacketTimeMs),
interArrival(90 * kTimestampGroupLengthMs, kTimestampToMs, enableBurstGrouping),
estimator(options),
detector()
{}
inline
RemoteBitrateEstimatorSingleStream::RemoteBitrateEstimatorSingleStream(Listener* observer) :
incomingBitrate(),
remoteRate(new AimdRateControl()), observer(observer), processIntervalMs(kProcessIntervalMs)
{
//MS_ASSERT(this->observer, "'this->observer' missing");
}
inline
RemoteBitrateEstimatorSingleStream::~RemoteBitrateEstimatorSingleStream()
{
while (!this->overuseDetectors.empty())
{
SsrcOveruseEstimatorMap::iterator it = this->overuseDetectors.begin();
delete it->second;
this->overuseDetectors.erase(it);
}
}
inline
void RemoteBitrateEstimatorSingleStream::Process()
{
UpdateEstimate(DepLibUV::GetTime());
this->lastProcessTime = DepLibUV::GetTime();
}
inline
void RemoteBitrateEstimatorSingleStream::OnRttUpdate(int64_t avgRttMs, int64_t maxRttMs)
{
(void) maxRttMs;
GetRemoteRate()->SetRtt(avgRttMs);
}
inline
void RemoteBitrateEstimatorSingleStream::RemoveStream(unsigned int ssrc)
{
SsrcOveruseEstimatorMap::iterator it = this->overuseDetectors.find(ssrc);
if (it != this->overuseDetectors.end())
{
delete it->second;
this->overuseDetectors.erase(it);
}
}
inline
AimdRateControl* RemoteBitrateEstimatorSingleStream::GetRemoteRate()
{
if (!this->remoteRate)
this->remoteRate.reset(new AimdRateControl());
return this->remoteRate.get();
}
inline
void RemoteBitrateEstimatorSingleStream::SetMinBitrate(int minBitrateBps)
{
this->remoteRate->SetMinBitrate(minBitrateBps);
}
}
#endif
......@@ -20,10 +20,11 @@ namespace RTC
explicit RateCalculator(size_t windowSize = defaultWindowSize, float scale = kBpsScale);
void Update(size_t count, uint64_t now);
uint32_t GetRate(uint64_t now);
void Reset();
private:
void RemoveOldData(uint64_t now);
void Reset(uint64_t oldestTime);
void Reset(uint64_t now);
private:
struct BufferItem
......@@ -69,16 +70,22 @@ namespace RTC
{
uint64_t now = DepLibUV::GetTime();
this->Reset(now - windowSize);
this->Reset(now);
}
inline
void RateCalculator::Reset(uint64_t oldestTime)
void RateCalculator::Reset()
{
this->Reset(this->oldestTime);
}
inline
void RateCalculator::Reset(uint64_t now)
{
this->buffer.reset(new BufferItem[windowSize]);
this->totalCount = 0;
this->oldestIndex = 0;
this->oldestTime = oldestTime;
this->oldestTime = now - this->windowSize;
}
inline
......
......@@ -194,7 +194,7 @@ namespace RTC
Media::Kind kind = Media::Kind::ALL;
std::string uri;
RtpHeaderExtensionUri::Type type;
uint16_t preferredId = 0;
uint8_t preferredId = 0;
bool preferredEncrypt = false;
};
......@@ -276,7 +276,7 @@ namespace RTC
public:
std::string uri;
RtpHeaderExtensionUri::Type type;
uint16_t id = 0;
uint8_t id = 0;
bool encrypt = false;
RTC::Parameters parameters;
};
......
......@@ -22,6 +22,7 @@ namespace RTC
RTC::RtpCodecMime mime;
uint32_t clockRate = 0;
bool useNack = false;
uint8_t absSendTimeId = 0; // 0 means no abs-send-time id.
};
public:
......
......@@ -16,6 +16,7 @@
#include "RTC/RtpPacket.hpp"
#include "RTC/RTCP/Packet.hpp"
#include "RTC/RTCP/CompoundPacket.hpp"
#include "RTC/RemoteBitrateEstimator/RemoteBitrateEstimatorAbsSendTime.hpp"
#include "Channel/Request.hpp"
#include "Channel/Notifier.hpp"
#include <string>
......@@ -29,7 +30,8 @@ namespace RTC
public RTC::TcpServer::Listener,
public RTC::TcpConnection::Listener,
public RTC::IceServer::Listener,
public RTC::DtlsTransport::Listener
public RTC::DtlsTransport::Listener,
public RTC::RemoteBitrateEstimator::Listener
{
public:
class Listener
......@@ -39,6 +41,9 @@ namespace RTC
virtual void onTransportRtcpPacket(RTC::Transport* transport, RTC::RTCP::Packet* packet) = 0;
};
private:
static uint8_t rtcpBuffer[];
public:
Transport(Listener* listener, Channel::Notifier* notifier, uint32_t transportId, Json::Value& data);
virtual ~Transport();
......@@ -52,6 +57,7 @@ namespace RTC
void SendRtcpPacket(RTC::RTCP::Packet* packet);
void SendRtcpCompoundPacket(RTC::RTCP::CompoundPacket* packet);
RTC::RtpReceiver* GetRtpReceiver(uint32_t ssrc);
void EnableRemb();
private:
void MayRunDtlsTransport();
......@@ -93,6 +99,10 @@ namespace RTC
virtual void onOutgoingDtlsData(RTC::DtlsTransport* dtlsTransport, const uint8_t* data, size_t len) override;
virtual void onDtlsApplicationData(RTC::DtlsTransport* dtlsTransport, const uint8_t* data, size_t len) override;
/* Pure virtual methods inherited from RTC::RemoteBitrateEstimator::Listener. */
public:
virtual void onReceiveBitrateChanged(const std::vector<uint32_t>& ssrcs, uint32_t bitrate) override;
public:
// Passed by argument.
uint32_t transportId;
......@@ -118,6 +128,8 @@ namespace RTC
RTC::DtlsTransport::Role dtlsLocalRole = RTC::DtlsTransport::Role::AUTO;
// Others (RtpListener).
RtpListener rtpListener;
// REMB.
std::unique_ptr<RemoteBitrateEstimatorAbsSendTime> remoteBitrateEstimator;
};
/* Inline instance methods. */
......@@ -139,6 +151,16 @@ namespace RTC
{
return this->rtpListener.GetRtpReceiver(ssrc);
}
inline
void Transport::EnableRemb()
{
if (!this->remoteBitrateEstimator)
{
this->remoteBitrateEstimator.reset(
new RTC::RemoteBitrateEstimatorAbsSendTime(this));
}
}
}
#endif
......@@ -19,6 +19,7 @@ public:
bool rtp { false };
bool srtp { false };
bool rtcp { false };
bool rbe { false };
// TODO: Add more tags (here and in Settings.cpp).
};
......
......@@ -287,6 +287,8 @@ namespace Utils
};
static void CurrentTimeNtp(Ntp& ntp);
static bool IsNewerTimestamp(uint32_t timestamp, uint32_t prev_timestamp);
static uint32_t LatestTimestamp(uint32_t timestamp1, uint32_t timestamp2);
};
inline
......@@ -298,6 +300,26 @@ namespace Utils
ntp.seconds = tv.tv_sec + UnixNtpOffset;
ntp.fractions = (uint32_t)((double)(tv.tv_usec) * NtpFractionalUnit * 1.0e-6);
}
inline
bool Time::IsNewerTimestamp(uint32_t timestamp, uint32_t prev_timestamp)
{
// Distinguish between elements that are exactly 0x80000000 apart.
// If t1>t2 and |t1-t2| = 0x80000000: IsNewer(t1,t2)=true,
// IsNewer(t2,t1)=false
// rather than having IsNewer(t1,t2) = IsNewer(t2,t1) = false.
if (static_cast<uint32_t>(timestamp - prev_timestamp) == 0x80000000) {
return timestamp > prev_timestamp;
}
return timestamp != prev_timestamp &&
static_cast<uint32_t>(timestamp - prev_timestamp) < 0x80000000;
}
inline
uint32_t Time::LatestTimestamp(uint32_t timestamp1, uint32_t timestamp2)
{
return IsNewerTimestamp(timestamp1, timestamp2) ? timestamp1 : timestamp2;
}
}
#endif
......@@ -77,6 +77,13 @@
'src/RTC/RTCP/FeedbackPsVbcm.cpp',
'src/RTC/RTCP/FeedbackPsLei.cpp',
'src/RTC/RTCP/FeedbackPsAfb.cpp',
'src/RTC/RTCP/FeedbackPsRemb.cpp',
'src/RTC/RemoteBitrateEstimator/AimdRateControl.cpp',
'src/RTC/RemoteBitrateEstimator/InterArrival.cpp',
'src/RTC/RemoteBitrateEstimator/OveruseDetector.cpp',
'src/RTC/RemoteBitrateEstimator/OveruseEstimator.cpp',
'src/RTC/RemoteBitrateEstimator/RemoteBitrateEstimatorAbsSendTime.cpp',
'src/RTC/RemoteBitrateEstimator/RemoteBitrateEstimatorSingleStream.cpp',
'src/Utils/Crypto.cpp',
'src/Utils/File.cpp',
'src/Utils/IP.cpp',
......@@ -145,6 +152,14 @@
'include/RTC/RTCP/FeedbackPsVbcm.hpp',
'include/RTC/RTCP/FeedbackPsLei.hpp',
'include/RTC/RTCP/FeedbackPsAfb.hpp',
'include/RTC/RTCP/FeedbackPsRemb.hpp',
'include/RTC/RemoteBitrateEstimator/AimdRateControl.hpp',
'include/RTC/RemoteBitrateEstimator/InterArrival.hpp',
'include/RTC/RemoteBitrateEstimator/OveruseDetector.hpp',
'include/RTC/RemoteBitrateEstimator/OveruseEstimator.hpp',
'include/RTC/RemoteBitrateEstimator/RemoteBitrateEstimator.hpp',
'include/RTC/RemoteBitrateEstimator/RemoteBitrateEstimatorAbsSendTime.hpp',
'include/RTC/RemoteBitrateEstimator/RemoteBitrateEstimatorSingleStream.hpp',
'include/handles/SignalsHandler.hpp',
'include/handles/TcpConnection.hpp',
'include/handles/TcpServer.hpp',
......
......@@ -5,6 +5,7 @@
#include "RTC/RtpDictionaries.hpp"
#include "RTC/RTCP/CompoundPacket.hpp"
#include "RTC/RTCP/FeedbackRtpNack.hpp"
#include "RTC/RTCP/FeedbackPsRemb.hpp"
#include "RTC/RTCP/Sdes.hpp"
#include "MediaSoupError.hpp"
#include "Logger.hpp"
......@@ -790,11 +791,21 @@ namespace RTC
switch (feedback->GetMessageType())
{
case RTCP::FeedbackPs::MessageType::AFB:
{
RTCP::FeedbackPsAfbPacket* afb = static_cast<RTCP::FeedbackPsAfbPacket*>(feedback);
if (afb->GetApplication() == RTCP::FeedbackPsAfbPacket::REMB)
{
// afb->Dump();
break;
}
}
// [[fallthrough]]; (C++17)
case RTCP::FeedbackPs::MessageType::PLI:
case RTCP::FeedbackPs::MessageType::SLI:
case RTCP::FeedbackPs::MessageType::RPSI:
case RTCP::FeedbackPs::MessageType::FIR:
case RTCP::FeedbackPs::MessageType::AFB:
{
RTC::RtpSender* rtpSender = this->GetRtpSender(feedback->GetMediaSsrc());
......
......@@ -17,6 +17,7 @@
#include "RTC/RTCP/FeedbackPsVbcm.hpp"
#include "RTC/RTCP/FeedbackPsLei.hpp"
#include "RTC/RTCP/FeedbackPsAfb.hpp"
#include "Utils.hpp"
#include "Logger.hpp"
#include <cstring>
......@@ -162,8 +163,10 @@ namespace RTC { namespace RTCP
break;
case FeedbackPs::MessageType::AFB:
{
packet = FeedbackPsAfbPacket::Parse(data, len);
break;
}
case FeedbackPs::MessageType::EXT:
break;
......
......@@ -2,6 +2,8 @@
// #define MS_LOG_DEV
#include "RTC/RTCP/FeedbackPsAfb.hpp"
#include "RTC/RTCP/FeedbackPsRemb.hpp"
#include "Utils.hpp"
#include "Logger.hpp"
#include <cstring>
......@@ -21,7 +23,18 @@ namespace RTC { namespace RTCP
}
CommonHeader* commonHeader = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data));
std::unique_ptr<FeedbackPsAfbPacket> packet(new FeedbackPsAfbPacket(commonHeader));
std::unique_ptr<FeedbackPsAfbPacket> packet;
constexpr size_t offset = sizeof(CommonHeader) + sizeof(FeedbackPacket::Header);
if (Utils::Byte::Get4Bytes(data, offset) == FeedbackPsRembPacket::UniqueIdentifier)
{
packet.reset(FeedbackPsRembPacket::Parse(data, len));
}
else {
packet.reset(new FeedbackPsAfbPacket(commonHeader));
}
return packet.release();
}
......
#define MS_CLASS "RTC::RTCP::FeedbackPsRembPacket"
// #define MS_LOG_DEV
#include "RTC/RTCP/FeedbackPsRemb.hpp"
#include "Utils.hpp"
#include "Logger.hpp"
#include <cstring>
namespace RTC { namespace RTCP
{
/* Class variables. */
uint32_t FeedbackPsRembPacket::UniqueIdentifier = 0x52454D42;
/* Class methods. */
FeedbackPsRembPacket* FeedbackPsRembPacket::Parse(const uint8_t* data, size_t len)
{
MS_TRACE();
if (sizeof(CommonHeader) + sizeof(FeedbackPacket::Header) > len)
{
MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded");
return nullptr;
}
CommonHeader* commonHeader = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data));
std::unique_ptr<FeedbackPsRembPacket> packet(new FeedbackPsRembPacket(commonHeader));
if (!packet->IsCorrect())
return nullptr;
return packet.release();
}
FeedbackPsRembPacket::FeedbackPsRembPacket(CommonHeader* commonHeader):
FeedbackPsAfbPacket(commonHeader, FeedbackPsAfbPacket::REMB)
{
uint8_t* data = reinterpret_cast<uint8_t*>(commonHeader+1);
if (Utils::Byte::Get4Bytes(data, 8) != UniqueIdentifier)
{
MS_WARN_TAG(rtcp, "invalid unique indentifier in REMB packet");
this->isCorrect = false;
return;
}
size_t numSsrcs = data[12];
uint8_t exponent = data[13] >> 2;
uint64_t mantissa = (static_cast<uint32_t>(data[13] & 0x03) << 16) | Utils::Byte::Get2Bytes(data, 14);
this->bitrate = (mantissa << exponent);
if ((this->bitrate >> exponent) != mantissa)
{
MS_WARN_TAG(rtcp, "invalid REMB bitrate value : %" PRIu64" *2^%u", mantissa, exponent);
this->isCorrect = false;
return;
}
// Check length.
size_t len = (size_t)(ntohs(commonHeader->length) + 1) * 4;
if (len != sizeof(CommonHeader) + sizeof(FeedbackPacket::Header) + sizeof(Header) + (numSsrcs * sizeof(uint32_t)))
{
MS_WARN_TAG(rtcp, "invalid payload size: %zu for the given number of ssrcs: %zu", len, numSsrcs);
this->isCorrect = false;
return;
}
size_t index = 16;
this->ssrcs.reserve(numSsrcs);
for (size_t n=0; n<numSsrcs; ++n)
{
this->ssrcs.push_back(Utils::Byte::Get4Bytes(data, index));
index += sizeof(uint32_t);
}
}
size_t FeedbackPsRembPacket::Serialize(uint8_t* buffer)
{
MS_TRACE();
size_t offset = FeedbackPsPacket::Serialize(buffer);
uint64_t mantissa = this->bitrate;
uint8_t exponent = 0;
while (mantissa > 0x3FFFF /* max mantissa (18 bits) */) {
mantissa >>= 1;
++exponent;
}
Utils::Byte::Set4Bytes(buffer, offset, UniqueIdentifier);
offset += sizeof(UniqueIdentifier);
buffer[offset] = this->ssrcs.size();
offset+=1;
buffer[offset] = (exponent << 2) | (mantissa >> 16);
offset+=1;
Utils::Byte::Set2Bytes(buffer, offset, mantissa & 0xFFFF);
offset+=2;
for (auto ssrc : this->ssrcs)
{
Utils::Byte::Set4Bytes(buffer, offset, ssrc);
offset += sizeof(ssrc);
}
return offset;
}
void FeedbackPsRembPacket::Dump() const
{
MS_TRACE();
MS_DUMP("<FeedbackPsRembPacket>");
FeedbackPsPacket::Dump();
MS_DUMP("\t bitrate (bps): %" PRIu64, this->bitrate);
for (auto ssrc : this->ssrcs)
MS_DUMP("\t ssrc: %" PRIu32, ssrc);
MS_DUMP("</FeedbackPsRembPacket>");
}
}}
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#define MS_CLASS "AimdRateControl"
// #define MS_LOG_DEV
#include "RTC/RemoteBitrateEstimator/AimdRateControl.hpp"
#include "RTC/RemoteBitrateEstimator/RemoteBitrateEstimator.hpp"
#include "Logger.hpp"
#include <algorithm>
#include <cmath>
static constexpr int64_t kMaxFeedbackIntervalMs = 1000;
namespace RTC
{
int64_t AimdRateControl::GetFeedbackInterval() const
{
MS_TRACE();
// Estimate how often we can send RTCP if we allocate up to 5% of bandwidth
// to feedback.
static const int kRtcpSize = 80;
int64_t interval = static_cast<int64_t>(kRtcpSize * 8.0 * 1000.0 / (0.05 * this->currentBitrateBps) + 0.5);
const int64_t kMinFeedbackIntervalMs = 200;
return std::min(std::max(interval, kMinFeedbackIntervalMs), kMaxFeedbackIntervalMs);
}
bool AimdRateControl::TimeToReduceFurther(int64_t timeNow, uint32_t incomingBitrateBps) const
{
MS_TRACE();
const int64_t bitrateReductionInterval = std::max<int64_t>(std::min<int64_t>(this->rtt, 200), 10);
if (timeNow - this->timeLastBitrateChange >= bitrateReductionInterval)
{
return true;
}
if (ValidEstimate())
{
// TODO(terelius/holmer): Investigate consequences of increasing
// the threshold to 0.95 * LatestEstimate().
const uint32_t threshold = static_cast<uint32_t>(0.5 * LatestEstimate());
return incomingBitrateBps < threshold;
}
return false;
}
void AimdRateControl::Update(const RateControlInput* input, int64_t nowMs)
{
MS_TRACE();
MS_ASSERT(input, "input missing");
// Set the initial bit rate value to what we're receiving the first half
// second.
if (!this->bitrateIsInitialized)
{
const int64_t kInitializationTimeMs = 5000;
//MSDASSERT(kBitrateWindowMs <= kInitializationTimeMs);
if (this->timeFirstIncomingEstimate < 0)
{
if (input->incomingBitrate)
this->timeFirstIncomingEstimate = nowMs;
}
else if (nowMs - this->timeFirstIncomingEstimate > kInitializationTimeMs && input->incomingBitrate)
{
this->currentBitrateBps = input->incomingBitrate;
this->bitrateIsInitialized = true;
}
}
if (this->updated && this->currentInput.bwState == kBwOverusing)
{
// Only update delay factor and incoming bit rate. We always want to react
// on an over-use.
this->currentInput.noiseVar = input->noiseVar;
this->currentInput.incomingBitrate = input->incomingBitrate;
}
else
{
this->updated = true;
this->currentInput = *input;
}
}
int AimdRateControl::GetNearMaxIncreaseRateBps() const
{
MS_TRACE();
// MS_ASSERT(this->currentBitrateBps > 0);
double bitsPerFrame = static_cast<double>(this->currentBitrateBps) / 30.0;
double packetsPerFrame = std::ceil(bitsPerFrame / (8.0 * 1200.0));
double avgPacketSizeBits = bitsPerFrame / packetsPerFrame;
// Approximate the over-use estimator delay to 100 ms.
const int64_t responseTime = (this->rtt + 100) * 2;
constexpr double kMinIncreaseRateBps = 4000;
return static_cast<int>(std::max(kMinIncreaseRateBps, (avgPacketSizeBits * 1000) / responseTime));
}
uint32_t AimdRateControl::ChangeBitrate(uint32_t newBitrateBps, uint32_t incomingBitrateBps, int64_t nowMs)
{
MS_TRACE();
if (!this->updated)
{
return this->currentBitrateBps;
}
// An over-use should always trigger us to reduce the bitrate, even though
// we have not yet established our first estimate. By acting on the over-use,
// we will end up with a valid estimate.
if (!this->bitrateIsInitialized && this->currentInput.bwState != kBwOverusing)
return this->currentBitrateBps;
this->updated = false;
ChangeState(this->currentInput, nowMs);
// Calculated here because it's used in multiple places.
const float incomingBitrateKbps = incomingBitrateBps / 1000.0f;
// Calculate the max bit rate std dev given the normalized
// variance and the current incoming bit rate.
const float stdMaxBitRate = sqrt(this->varMaxBitrateKbps * this->avgMaxBitrateKbps);
switch (this->rateControlState)
{
case kRcHold:
break;
case kRcIncrease:
if (this->avgMaxBitrateKbps >= 0 && incomingBitrateKbps > this->avgMaxBitrateKbps + 3 * stdMaxBitRate)
{
ChangeRegion(kRcMaxUnknown);
this->avgMaxBitrateKbps = -1.0;
}
if (this->rateControlRegion == kRcNearMax)
{
uint32_t additiveIncreaseBps = AdditiveRateIncrease(nowMs, this->timeLastBitrateChange);
newBitrateBps += additiveIncreaseBps;
}
else
{
uint32_t multiplicativeIncreaseBps = MultiplicativeRateIncrease(nowMs, this->timeLastBitrateChange, newBitrateBps);
newBitrateBps += multiplicativeIncreaseBps;
}
this->timeLastBitrateChange = nowMs;
break;
case kRcDecrease:
this->bitrateIsInitialized = true;
// Set bit rate to something slightly lower than max
// to get rid of any self-induced delay.
newBitrateBps = static_cast<uint32_t>(this->beta * incomingBitrateBps + 0.5);
if (newBitrateBps > this->currentBitrateBps)
{
// Avoid increasing the rate when over-using.
if (this->rateControlRegion != kRcMaxUnknown)
{
newBitrateBps = static_cast<uint32_t>(this->beta * this->avgMaxBitrateKbps * 1000 + 0.5f);
}
newBitrateBps = std::min(newBitrateBps, this->currentBitrateBps);
}
ChangeRegion(kRcNearMax);
if (incomingBitrateBps < this->currentBitrateBps)
{
this->lastDecrease = int(this->currentBitrateBps - newBitrateBps);
}
if (incomingBitrateKbps < this->avgMaxBitrateKbps - 3 * stdMaxBitRate)
{
this->avgMaxBitrateKbps = -1.0f;
}
UpdateMaxBitRateEstimate(incomingBitrateKbps);
// Stay on hold until the pipes are cleared.
ChangeState(kRcHold);
this->timeLastBitrateChange = nowMs;
break;
default:
MS_ASSERT(false, "invalid this->rateControlState value");
}
return ClampBitrate(newBitrateBps, incomingBitrateBps);
}
uint32_t AimdRateControl::ClampBitrate(uint32_t newBitrateBps, uint32_t incomingBitrateBps) const
{
MS_TRACE();
// Don't change the bit rate if the send side is too far off.
// We allow a bit more lag at very low rates to not too easily get stuck if
// the encoder produces uneven outputs.
const uint32_t maxBitrateBps = static_cast<uint32_t>(1.5f * incomingBitrateBps) + 10000;
if (newBitrateBps > this->currentBitrateBps && newBitrateBps > maxBitrateBps)
{
newBitrateBps = std::max(this->currentBitrateBps, maxBitrateBps);
}
newBitrateBps = std::max(newBitrateBps, this->minConfiguredBitrateBps);
return newBitrateBps;
}
uint32_t AimdRateControl::MultiplicativeRateIncrease(int64_t nowMs, int64_t lastMs, uint32_t currentBitrateBps) const
{
MS_TRACE();
double alpha = 1.08;
if (lastMs > -1)
{
int timeSinceLastUpdateMs = std::min(static_cast<int>(nowMs - lastMs), 1000);
alpha = pow(alpha, timeSinceLastUpdateMs / 1000.0);
}
uint32_t multiplicativeIncreaseBps = std::max(currentBitrateBps * (alpha - 1.0), 1000.0);
return multiplicativeIncreaseBps;
}
void AimdRateControl::UpdateMaxBitRateEstimate(float incomingBitrateKbps)
{
MS_TRACE();
const float alpha = 0.05f;
if (this->avgMaxBitrateKbps == -1.0f)
{
this->avgMaxBitrateKbps = incomingBitrateKbps;
}
else
{
this->avgMaxBitrateKbps = (1 - alpha) * this->avgMaxBitrateKbps + alpha * incomingBitrateKbps;
}
// Estimate the max bit rate variance and normalize the variance
// with the average max bit rate.
const float norm = std::max(this->avgMaxBitrateKbps, 1.0f);
this->varMaxBitrateKbps = (1 - alpha) * this->varMaxBitrateKbps +
alpha * (this->avgMaxBitrateKbps - incomingBitrateKbps) * (this->avgMaxBitrateKbps - incomingBitrateKbps) / norm;
// 0.4 ~= 14 kbit/s at 500 kbit/s
if (this->varMaxBitrateKbps < 0.4f)
{
this->varMaxBitrateKbps = 0.4f;
}
// 2.5f ~= 35 kbit/s at 500 kbit/s
if (this->varMaxBitrateKbps > 2.5f)
{
this->varMaxBitrateKbps = 2.5f;
}
}
void AimdRateControl::ChangeState(const RateControlInput& input, int64_t nowMs)
{
MS_TRACE();
(void) input;
switch (this->currentInput.bwState)
{
case kBwNormal:
if (this->rateControlState == kRcHold)
{
this->timeLastBitrateChange = nowMs;
ChangeState(kRcIncrease);
}
break;
case kBwOverusing:
if (this->rateControlState != kRcDecrease)
{
ChangeState(kRcDecrease);
}
break;
case kBwUnderusing:
ChangeState(kRcHold);
break;
default:
MS_ASSERT(false, "invalid RateControlInput::bwState value");
}
}
}
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#define MS_CLASS "InterArrival"
// #define MS_LOG_DEV
#include "RTC/RemoteBitrateEstimator/InterArrival.hpp"
#include "Logger.hpp"
#include "Utils.hpp" // LatestTimestamp
#include <algorithm>
namespace RTC
{
static const int kBurstDeltaThresholdMs = 5;
bool InterArrival::ComputeDeltas(uint32_t timestamp, int64_t arrival_time_ms, int64_t system_time_ms, size_t packet_size, uint32_t* timestamp_delta,
int64_t* arrival_time_delta_ms, int* packet_size_delta)
{
MS_TRACE();
MS_ASSERT(timestamp_delta, "'timestamp_delta' missing");
MS_ASSERT(arrival_time_delta_ms, "'arrival_time_delta_ms' missing");
MS_ASSERT(packet_size_delta, "'packet_size_delta' missing");
bool calculated_deltas = false;
if (this->currentTimestampGroup.IsFirstPacket())
{
// We don't have enough data to update the filter, so we store it until we
// have two frames of data to process.
this->currentTimestampGroup.timestamp = timestamp;
this->currentTimestampGroup.first_timestamp = timestamp;
}
else if (!PacketInOrder(timestamp))
{
return false;
}
else if (NewTimestampGroup(arrival_time_ms, timestamp))
{
// First packet of a later frame, the previous frame sample is ready.
if (this->prevTimestampGroup.complete_time_ms >= 0)
{
*timestamp_delta = this->currentTimestampGroup.timestamp - this->prevTimestampGroup.timestamp;
*arrival_time_delta_ms = this->currentTimestampGroup.complete_time_ms - this->prevTimestampGroup.complete_time_ms;
// Check system time differences to see if we have an unproportional jump
// in arrival time. In that case reset the inter-arrival computations.
int64_t system_time_delta_ms = this->currentTimestampGroup.last_system_time_ms - this->prevTimestampGroup.last_system_time_ms;
if (*arrival_time_delta_ms - system_time_delta_ms >= kArrivalTimeOffsetThresholdMs)
{
MS_WARN_TAG(rbe, "the arrival time clock offset has changed, resetting [diff:%" PRId64 "ms]",
*arrival_time_delta_ms - system_time_delta_ms);
Reset();
return false;
}
if (*arrival_time_delta_ms < 0)
{
// The group of packets has been reordered since receiving its local
// arrival timestamp.
++this->numConsecutiveReorderedPackets;
if (this->numConsecutiveReorderedPackets >= kReorderedResetThreshold)
{
MS_WARN_TAG(rbe, "packets are being reordered on the path from the "
"socket to the bandwidth estimator, ignoring this "
"packet for bandwidth estimation, resetting");
Reset();
}
return false;
}
else
{
this->numConsecutiveReorderedPackets = 0;
}
MS_ASSERT(*arrival_time_delta_ms >= 0, "invalid arrival_time_delta_ms value");
*packet_size_delta = static_cast<int>(this->currentTimestampGroup.size) - static_cast<int>(this->prevTimestampGroup.size);
calculated_deltas = true;
}
this->prevTimestampGroup = this->currentTimestampGroup;
// The new timestamp is now the current frame.
this->currentTimestampGroup.first_timestamp = timestamp;
this->currentTimestampGroup.timestamp = timestamp;
this->currentTimestampGroup.size = 0;
}
else
{
this->currentTimestampGroup.timestamp = Utils::Time::LatestTimestamp(this->currentTimestampGroup.timestamp, timestamp);
}
// Accumulate the frame size.
this->currentTimestampGroup.size += packet_size;
this->currentTimestampGroup.complete_time_ms = arrival_time_ms;
this->currentTimestampGroup.last_system_time_ms = system_time_ms;
return calculated_deltas;
}
bool InterArrival::PacketInOrder(uint32_t timestamp)
{
MS_TRACE();
if (this->currentTimestampGroup.IsFirstPacket())
{
return true;
}
else
{
// Assume that a diff which is bigger than half the timestamp interval
// (32 bits) must be due to reordering. This code is almost identical to
// that in IsNewerTimestamp() in module_common_types.h.
uint32_t timestamp_diff = timestamp - this->currentTimestampGroup.first_timestamp;
return timestamp_diff < 0x80000000;
}
}
// Assumes that |timestamp| is not reordered compared to
// |this->currentTimestampGroup|.
bool InterArrival::NewTimestampGroup(int64_t arrival_time_ms, uint32_t timestamp) const
{
MS_TRACE();
if (this->currentTimestampGroup.IsFirstPacket())
{
return false;
}
else if (BelongsToBurst(arrival_time_ms, timestamp))
{
return false;
}
else
{
uint32_t timestamp_diff = timestamp - this->currentTimestampGroup.first_timestamp;
return timestamp_diff > kTimestampGroupLengthTicks;
}
}
bool InterArrival::BelongsToBurst(int64_t arrival_time_ms, uint32_t timestamp) const
{
MS_TRACE();
if (!this->burstGrouping)
{
return false;
}
MS_ASSERT(this->currentTimestampGroup.complete_time_ms >= 0, "invalid complete_time_ms value");
int64_t arrival_time_delta_ms = arrival_time_ms - this->currentTimestampGroup.complete_time_ms;
uint32_t timestamp_diff = timestamp - this->currentTimestampGroup.timestamp;
int64_t ts_delta_ms = this->timestampToMsCoeff * timestamp_diff + 0.5;
if (ts_delta_ms == 0)
return true;
int propagation_delta_ms = arrival_time_delta_ms - ts_delta_ms;
return propagation_delta_ms < 0 && arrival_time_delta_ms <= kBurstDeltaThresholdMs;
}
void InterArrival::Reset()
{
MS_TRACE();
this->numConsecutiveReorderedPackets = 0;
this->currentTimestampGroup = TimestampGroup();
this->prevTimestampGroup = TimestampGroup();
}
}
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#define MS_CLASS "OveruseDetector"
// #define MS_LOG_DEV
#include "RTC/RemoteBitrateEstimator/OveruseDetector.hpp"
#include "Logger.hpp"
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <sstream>
#include <string>
namespace RTC
{
constexpr double kMaxAdaptOffsetMs = 15.0;
constexpr int kMinNumDeltas = 60;
BandwidthUsage OveruseDetector::Detect(double offset, double tsDelta, int numOfDeltas, int64_t nowMs)
{
MS_TRACE();
if (numOfDeltas < 2)
{
return kBwNormal;
}
const double T = std::min(numOfDeltas, kMinNumDeltas) * offset;
if (T > this->threshold)
{
if (this->timeOverUsing == -1)
{
// Initialize the timer. Assume that we've been
// over-using half of the time since the previous
// sample.
this->timeOverUsing = tsDelta / 2;
}
else
{
// Increment timer
this->timeOverUsing += tsDelta;
}
this->overuseCounter++;
if (this->timeOverUsing > this->overusingTimeThreshold && this->overuseCounter > 1)
{
if (offset >= this->prevOffset)
{
this->timeOverUsing = 0;
this->overuseCounter = 0;
this->hypothesis = kBwOverusing;
}
}
}
else if (T < -this->threshold)
{
this->timeOverUsing = -1;
this->overuseCounter = 0;
this->hypothesis = kBwUnderusing;
}
else
{
this->timeOverUsing = -1;
this->overuseCounter = 0;
this->hypothesis = kBwNormal;
}
this->prevOffset = offset;
UpdateThreshold(T, nowMs);
return this->hypothesis;
}
void OveruseDetector::UpdateThreshold(double modifiedOffset, int64_t nowMs)
{
MS_TRACE();
if (this->lastUpdateMs == -1)
this->lastUpdateMs = nowMs;
if (fabs(modifiedOffset) > this->threshold + kMaxAdaptOffsetMs)
{
// Avoid adapting the threshold to big latency spikes, caused e.g.,
// by a sudden capacity drop.
this->lastUpdateMs = nowMs;
return;
}
const double k = fabs(modifiedOffset) < this->threshold ? this->kDown : this->kUp;
const int64_t kMaxTimeDeltaMs = 100;
int64_t timeDeltaMs = std::min(nowMs - this->lastUpdateMs, kMaxTimeDeltaMs);
this->threshold += k * (fabs(modifiedOffset) - this->threshold) * timeDeltaMs;
const double kMinThreshold = 6;
const double kMaxThreshold = 600;
this->threshold = std::min(std::max(this->threshold, kMinThreshold), kMaxThreshold);
this->lastUpdateMs = nowMs;
}
}
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#define MS_CLASS "OveruseEstimator"
// #define MS_LOG_DEV
#include "RTC/RemoteBitrateEstimator/OveruseEstimator.hpp"
#include "Logger.hpp"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
namespace RTC
{
constexpr size_t kMinFramePeriodHistoryLength = 60;
constexpr uint16_t kDeltaCounterMax = 1000;
void OveruseEstimator::Update(int64_t tDelta, double tsDelta, int sizeDelta, BandwidthUsage currentHypothesis, int64_t nowMs)
{
MS_TRACE();
(void) nowMs;
const double minFramePeriod = UpdateMinFramePeriod(tsDelta);
const double tTsDelta = tDelta - tsDelta;
double fsDelta = sizeDelta;
++this->numOfDeltas;
if (this->numOfDeltas > kDeltaCounterMax)
{
this->numOfDeltas = kDeltaCounterMax;
}
// Update the Kalman filter.
this->E[0][0] += this->processNoise[0];
this->E[1][1] += this->processNoise[1];
if ((currentHypothesis == kBwOverusing && this->offset < this->prevOffset) ||
(currentHypothesis == kBwUnderusing && this->offset > this->prevOffset))
{
this->E[1][1] += 10 * this->processNoise[1];
}
const double h[2] = {fsDelta, 1.0};
const double Eh[2] = {this->E[0][0] * h[0] + this->E[0][1] * h[1], this->E[1][0] * h[0] + this->E[1][1] * h[1]};
const double residual = tTsDelta - this->slope * h[0] - this->offset;
const bool inStableState = (currentHypothesis == kBwNormal);
const double maxResidual = 3.0 * sqrt(this->varNoise);
// We try to filter out very late frames. For instance periodic key
// frames doesn't fit the Gaussian model well.
if (fabs(residual) < maxResidual)
{
UpdateNoiseEstimate(residual, minFramePeriod, inStableState);
}
else
{
UpdateNoiseEstimate(residual < 0 ? -maxResidual : maxResidual, minFramePeriod, inStableState);
}
const double denom = this->varNoise + h[0] * Eh[0] + h[1] * Eh[1];
const double K[2] = {Eh[0] / denom, Eh[1] / denom};
const double IKh[2][2] = {{1.0 - K[0] * h[0], -K[0] * h[1]}, {-K[1] * h[0], 1.0 - K[1] * h[1]}};
const double e00 = this->E[0][0];
const double e01 = this->E[0][1];
// Update state.
this->E[0][0] = e00 * IKh[0][0] + this->E[1][0] * IKh[0][1];
this->E[0][1] = e01 * IKh[0][0] + this->E[1][1] * IKh[0][1];
this->E[1][0] = e00 * IKh[1][0] + this->E[1][0] * IKh[1][1];
this->E[1][1] = e01 * IKh[1][0] + this->E[1][1] * IKh[1][1];
// The covariance matrix must be positive semi-definite.
bool positiveSemiDefinite =
this->E[0][0] + this->E[1][1] >= 0 && this->E[0][0] * this->E[1][1] - this->E[0][1] * this->E[1][0] >= 0 && this->E[0][0] >= 0;
MS_ASSERT(positiveSemiDefinite, "positiveSemiDefinite missing");
if (!positiveSemiDefinite)
{
MS_ERROR("the over-use estimator's covariance matrix is no longer semi-definite");
}
this->slope = this->slope + K[0] * residual;
this->prevOffset = this->offset;
this->offset = this->offset + K[1] * residual;
}
double OveruseEstimator::UpdateMinFramePeriod(double tsDelta)
{
MS_TRACE();
double minFramePeriod = tsDelta;
if (this->tsDeltaHist.size() >= kMinFramePeriodHistoryLength)
{
this->tsDeltaHist.pop_front();
}
for (const double oldTsDelta : this->tsDeltaHist)
{
minFramePeriod = std::min(oldTsDelta, minFramePeriod);
}
this->tsDeltaHist.push_back(tsDelta);
return minFramePeriod;
}
void OveruseEstimator::UpdateNoiseEstimate(double residual, double tsDelta, bool stableState)
{
MS_TRACE();
if (!stableState)
{
return;
}
// Faster filter during startup to faster adapt to the jitter level
// of the network. |alpha| is tuned for 30 frames per second, but is scaled
// according to |tsDelta|.
double alpha = 0.01;
if (this->numOfDeltas > 10 * 30)
{
alpha = 0.002;
}
// Only update the noise estimate if we're not over-using. |beta| is a
// function of alpha and the time delta since the previous update.
const double beta = pow(1 - alpha, tsDelta * 30.0 / 1000.0);
this->avgNoise = beta * this->avgNoise + (1 - beta) * residual;
this->varNoise = beta * this->varNoise + (1 - beta) * (this->avgNoise - residual) * (this->avgNoise - residual);
if (this->varNoise < 1)
{
this->varNoise = 1;
}
}
}
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#define MS_CLASS "RemoteBitrateEstimatorSingleStream"
// #define MS_LOG_DEV
#include "RTC/RemoteBitrateEstimator/RemoteBitrateEstimatorSingleStream.hpp"
#include "RTC/RemoteBitrateEstimator/AimdRateControl.hpp"
#include "RTC/RemoteBitrateEstimator/InterArrival.hpp"
#include "RTC/RemoteBitrateEstimator/OveruseDetector.hpp"
#include "RTC/RemoteBitrateEstimator/OveruseEstimator.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include <utility> // std::make_pair
namespace RTC
{
void RemoteBitrateEstimatorSingleStream::IncomingPacket(int64_t arrivalTimeMs, size_t payloadSize, const RtpPacket& packet, const uint32_t transmissionTimeOffset)
{
MS_TRACE();
if (!this->umaRecorded)
{
this->umaRecorded = true;
}
uint32_t ssrc = packet.GetSsrc();
uint32_t rtpTimestamp = packet.GetTimestamp() + transmissionTimeOffset;
int64_t nowMs = DepLibUV::GetTime();
SsrcOveruseEstimatorMap::iterator it = this->overuseDetectors.find(ssrc);
if (it == this->overuseDetectors.end())
{
// This is a new SSRC. Adding to map.
// TODO(holmer): If the channel changes SSRC the old SSRC will still be
// around in this map until the channel is deleted. This is OK since the
// callback will no longer be called for the old SSRC. This will be
// automatically cleaned up when we have one RemoteBitrateEstimator per REMB
// group.
std::pair<SsrcOveruseEstimatorMap::iterator, bool> insertResult =
this->overuseDetectors.insert(std::make_pair(ssrc, new Detector(nowMs, OverUseDetectorOptions(), true)));
it = insertResult.first;
}
Detector* estimator = it->second;
estimator->lastPacketTimeMs = nowMs;
// Check if incoming bitrate estimate is valid, and if it needs to be reset.
uint32_t incomingBitrate = this->incomingBitrate.GetRate(nowMs);
if (incomingBitrate)
{
this->lastValidIncomingBitrate = incomingBitrate;
}
else if (this->lastValidIncomingBitrate > 0)
{
// Incoming bitrate had a previous valid value, but now not enough data
// point are left within the current window. Reset incoming bitrate
// estimator so that the window size will only contain new data points.
this->incomingBitrate.Reset();
this->lastValidIncomingBitrate = 0;
}
this->incomingBitrate.Update(payloadSize, nowMs);
const BandwidthUsage priorState = estimator->detector.State();
uint32_t timestampDelta = 0;
int64_t timeDelta = 0;
int sizeDelta = 0;
if (estimator->interArrival.ComputeDeltas(rtpTimestamp, arrivalTimeMs, nowMs, payloadSize, &timestampDelta, &timeDelta, &sizeDelta))
{
double timestampDeltaMs = timestampDelta * kTimestampToMs;
estimator->estimator.Update(timeDelta, timestampDeltaMs, sizeDelta, estimator->detector.State(), nowMs);
estimator->detector.Detect(estimator->estimator.GetOffset(), timestampDeltaMs, estimator->estimator.GetNumOfDeltas(), nowMs);
}
if (estimator->detector.State() == kBwOverusing)
{
uint32_t incomingBitrateBps = this->incomingBitrate.GetRate(nowMs);
if (incomingBitrateBps && (priorState != kBwOverusing || GetRemoteRate()->TimeToReduceFurther(nowMs, incomingBitrateBps)))
{
// The first overuse should immediately trigger a new estimate.
// We also have to update the estimate immediately if we are overusing
// and the target bitrate is too high compared to what we are receiving.
UpdateEstimate(nowMs);
}
}
}
int64_t RemoteBitrateEstimatorSingleStream::TimeUntilNextProcess()
{
MS_TRACE();
if (this->lastProcessTime < 0)
{
return 0;
}
// MS_DASSERT(this->processIntervalMs > 0);
return this->lastProcessTime + this->processIntervalMs - DepLibUV::GetTime();
}
void RemoteBitrateEstimatorSingleStream::UpdateEstimate(int64_t nowMs)
{
MS_TRACE();
BandwidthUsage bwState = kBwNormal;
double sumVarNoise = 0.0;
SsrcOveruseEstimatorMap::iterator it = this->overuseDetectors.begin();
while (it != this->overuseDetectors.end())
{
const int64_t timeOfLastReceivedPacket = it->second->lastPacketTimeMs;
if (timeOfLastReceivedPacket >= 0 && nowMs - timeOfLastReceivedPacket > kStreamTimeOutMs)
{
// This over-use detector hasn't received packets for |kStreamTimeOutMs|
// milliseconds and is considered stale.
delete it->second;
this->overuseDetectors.erase(it++);
}
else
{
sumVarNoise += it->second->estimator.GetVarNoise();
// Make sure that we trigger an over-use if any of the over-use detectors
// is detecting over-use.
if (it->second->detector.State() > bwState)
{
bwState = it->second->detector.State();
}
++it;
}
}
// We can't update the estimate if we don't have any active streams.
if (this->overuseDetectors.empty())
{
return;
}
AimdRateControl* remoteRate = GetRemoteRate();
double meanNoiseVar = sumVarNoise / static_cast<double>(this->overuseDetectors.size());
const RateControlInput input(bwState, this->incomingBitrate.GetRate(nowMs), meanNoiseVar);
remoteRate->Update(&input, nowMs);
uint32_t targetBitrate = remoteRate->UpdateBandwidthEstimate(nowMs);
if (remoteRate->ValidEstimate())
{
this->processIntervalMs = remoteRate->GetFeedbackInterval();
// MS_DASSERT(this->processIntervalMs > 0);
std::vector<uint32_t> ssrcs;
GetSsrcs(&ssrcs);
this->observer->onReceiveBitrateChanged(ssrcs, targetBitrate);
}
}
bool RemoteBitrateEstimatorSingleStream::LatestEstimate(std::vector<uint32_t>* ssrcs, uint32_t* bitrateBps) const
{
MS_TRACE();
MS_ASSERT(bitrateBps, "'bitrateBps' missing");
if (!this->remoteRate->ValidEstimate())
{
return false;
}
GetSsrcs(ssrcs);
if (ssrcs->empty())
*bitrateBps = 0;
else
*bitrateBps = this->remoteRate->LatestEstimate();
return true;
}
void RemoteBitrateEstimatorSingleStream::GetSsrcs(std::vector<uint32_t>* ssrcs) const
{
MS_TRACE();
MS_ASSERT(ssrcs, "'ssrcs' missing");
ssrcs->resize(this->overuseDetectors.size());
int i = 0;
for (SsrcOveruseEstimatorMap::const_iterator it = this->overuseDetectors.begin(); it != this->overuseDetectors.end(); ++it, ++i)
{
(*ssrcs)[i] = it->first;
}
}
}
......@@ -31,7 +31,7 @@ namespace RTC
Json::CharReader* jsonReader = builder.newCharReader();
// NOTE: These lines are auto-generated from data/supportedCapabilities.js.
const std::string supportedRtpCapabilities = R"({"codecs":[{"kind":"audio","name":"audio/opus","clockRate":48000,"numChannels":2,"rtcpFeedback":[]},{"kind":"audio","name":"audio/PCMU","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/PCMA","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/ISAC","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/ISAC","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/G722","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/iLBC","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":24000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":12000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":48000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":8000,"rtcpFeedback":[]},{"kind":"video","name":"video/VP8","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"}]},{"kind":"video","name":"video/VP9","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"}]},{"kind":"video","name":"video/H264","clockRate":90000,"parameters":{"packetizationMode":0},"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"}]},{"kind":"video","name":"video/H264","clockRate":90000,"parameters":{"packetizationMode":1},"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"}]},{"kind":"video","name":"video/H265","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"}]}],"headerExtensions":[{"kind":"audio","uri":"urn:ietf:params:rtp-hdrext:ssrc-audio-level","preferredId":1,"preferredEncrypt":false},{"kind":"video","uri":"urn:ietf:params:rtp-hdrext:toffset","preferredId":2,"preferredEncrypt":false},{"kind":"","uri":"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time","preferredId":3,"preferredEncrypt":false},{"kind":"video","uri":"urn:3gpp:video-orientation","preferredId":4,"preferredEncrypt":false},{"kind":"","uri":"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","preferredId":5,"preferredEncrypt":false}],"fecMechanisms":[]})";
const std::string supportedRtpCapabilities = R"({"codecs":[{"kind":"audio","name":"audio/opus","clockRate":48000,"numChannels":2,"rtcpFeedback":[]},{"kind":"audio","name":"audio/PCMU","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/PCMA","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/ISAC","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/ISAC","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/G722","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/iLBC","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":24000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":12000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":48000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":8000,"rtcpFeedback":[]},{"kind":"video","name":"video/VP8","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/VP9","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H264","clockRate":90000,"parameters":{"packetizationMode":0},"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H264","clockRate":90000,"parameters":{"packetizationMode":1},"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H265","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]}],"headerExtensions":[{"kind":"audio","uri":"urn:ietf:params:rtp-hdrext:ssrc-audio-level","preferredId":1,"preferredEncrypt":false},{"kind":"video","uri":"urn:ietf:params:rtp-hdrext:toffset","preferredId":2,"preferredEncrypt":false},{"kind":"","uri":"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time","preferredId":3,"preferredEncrypt":false},{"kind":"video","uri":"urn:3gpp:video-orientation","preferredId":4,"preferredEncrypt":false},{"kind":"","uri":"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","preferredId":5,"preferredEncrypt":false}],"fecMechanisms":[]})";
Json::Value json;
std::string json_parse_error;
......
......@@ -45,7 +45,7 @@ namespace RTC
if (!data[k_preferredId].isUInt())
MS_THROW_ERROR("missing RtpHeaderExtension.preferredId");
this->preferredId = (uint16_t)data[k_preferredId].asUInt();
this->preferredId = (uint8_t)data[k_preferredId].asUInt();
// `preferredEncrypt` is optional.
if (data[k_preferredEncrypt].isBool())
......
......@@ -36,7 +36,7 @@ namespace RTC
if (!data[k_id].isUInt())
MS_THROW_ERROR("missing RtpHeaderExtensionParameters.id");
this->id = (uint16_t)data[k_id].asUInt();
this->id = (uint8_t)data[k_id].asUInt();
// `encrypt` is optional.
if (data[k_encrypt].isBool())
......
......@@ -371,6 +371,31 @@ namespace RTC
// Get the codec of the stream/encoding.
auto& codec = this->rtpParameters->GetCodecForEncoding(encoding);
bool useNack = false;
bool useRemb = false;
uint8_t absSendTimeId = 0;
for (auto& fb : codec.rtcpFeedback)
{
if (!useNack && fb.type == "nack")
{
MS_DEBUG_TAG(rtcp, "enabling NACK generation");
useNack = true;
}
else if (!useRemb && fb.type == "goog-remb")
{
MS_DEBUG_TAG(rbe, "enabling REMB");
useRemb = true;
}
}
for (auto& exten : this->rtpParameters->headerExtensions)
{
if (!absSendTimeId && exten.type == RTC::RtpHeaderExtensionUri::Type::ABS_SEND_TIME)
{
absSendTimeId = exten.id;
}
}
// Create stream params.
RTC::RtpStream::Params params;
......@@ -379,10 +404,15 @@ namespace RTC
params.payloadType = codec.payloadType;
params.mime = codec.mime;
params.clockRate = codec.clockRate;
params.useNack = (this->kind != RTC::Media::Kind::AUDIO);
params.useNack = useNack;
params.absSendTimeId = absSendTimeId;
// Create a RtpStreamRecv for receiving a media stream.
this->rtpStreams[ssrc] = new RTC::RtpStreamRecv(this, params);
// Enable REMB in the transport if requested.
if (useRemb)
this->transport->EnableRemb();
}
void RtpReceiver::ClearRtpStreams()
......
......@@ -406,6 +406,25 @@ namespace RTC
uint32_t ssrc = encoding.ssrc;
// Get the codec of the stream/encoding.
auto& codec = this->rtpParameters->GetCodecForEncoding(encoding);
bool useNack = false;
uint8_t absSendTimeId = 0; // 0 means no abs-send-time id.
for (auto& fb : codec.rtcpFeedback)
{
if (!useNack && fb.type == "nack")
{
MS_DEBUG_TAG(rtcp, "enabling NACK processing");
useNack = true;
}
}
for (auto& exten : this->rtpParameters->headerExtensions)
{
if (!absSendTimeId && exten.type == RTC::RtpHeaderExtensionUri::Type::ABS_SEND_TIME)
{
absSendTimeId = exten.id;
}
}
// Create stream params.
RTC::RtpStream::Params params;
......@@ -414,29 +433,14 @@ namespace RTC
params.payloadType = codec.payloadType;
params.mime = codec.mime;
params.clockRate = codec.clockRate;
params.useNack = (this->kind != RTC::Media::Kind::AUDIO);
params.useNack = useNack;
params.absSendTimeId = absSendTimeId;
// Create a RtpStreamSend for sending a single media stream.
switch (this->kind)
{
case RTC::Media::Kind::VIDEO:
case RTC::Media::Kind::DEPTH:
{
// Buffer up to N packets.
this->rtpStream = new RTC::RtpStreamSend(params, 200);
break;
}
case RTC::Media::Kind::AUDIO:
{
// No buffer for audio streams.
this->rtpStream = new RTC::RtpStreamSend(params, 0);
break;
}
default:
;
}
if (useNack)
this->rtpStream = new RTC::RtpStreamSend(params, 200);
else
this->rtpStream = new RTC::RtpStreamSend(params, 0);
}
void RtpSender::RetransmitRtpPacket(RTC::RtpPacket* packet)
......
......@@ -163,6 +163,7 @@ namespace RTC
static const Json::StaticString k_mime("mime");
static const Json::StaticString k_clockRate("clockRate");
static const Json::StaticString k_useNack("useNack");
static const Json::StaticString k_absSendTimeId("absSendTimeId");
Json::Value json(Json::objectValue);
......@@ -171,6 +172,7 @@ namespace RTC
json[k_mime] = this->mime.name;
json[k_clockRate] = (Json::UInt)this->clockRate;
json[k_useNack] = this->useNack;
json[k_absSendTimeId] = (Json::UInt)this->absSendTimeId;
return json;
}
......
......@@ -54,6 +54,13 @@ namespace RTC
// Calculate Jitter.
CalculateJitter(packet->GetTimestamp());
// Set RTP header extension ids.
if (this->params.absSendTimeId)
{
packet->AddExtensionMapping(
RtpHeaderExtensionUri::Type::ABS_SEND_TIME, this->params.absSendTimeId);
}
// May trigger a NACK to the sender.
if (this->params.useNack)
MayTriggerNack(packet);
......
......@@ -107,6 +107,14 @@ namespace RTC
// Ensure the container's first element is 0.
container[0] = nullptr;
// If NACK is not supported, exit.
if (!this->params.useNack)
{
MS_WARN_TAG(rtcp, "NACK not negotiated");
return;
}
// If the buffer is empty just return.
if (this->buffer.size() == 0)
return;
......
......@@ -2,7 +2,9 @@
// #define MS_LOG_DEV
#include "RTC/Transport.hpp"
#include "RTC/RTCP/FeedbackPsRemb.hpp"
#include "Settings.hpp"
#include "DepLibUV.hpp"
#include "Utils.hpp"
#include "MediaSoupError.hpp"
#include "Logger.hpp"
......@@ -32,6 +34,10 @@ uint32_t generateIceCandidatePriority(uint16_t local_preference)
namespace RTC
{
/* Class variables. */
uint8_t Transport::rtcpBuffer[MS_RTCP_BUFFER_SIZE];
/* Instance methods. */
Transport::Transport(Listener* listener, Channel::Notifier* notifier, uint32_t transportId, Json::Value& data) :
......@@ -274,6 +280,7 @@ namespace RTC
static const Json::StaticString v_connecting("connecting");
static const Json::StaticString v_closed("closed");
static const Json::StaticString v_failed("failed");
static const Json::StaticString k_useRemb("useRemb");
static const Json::StaticString k_rtpListener("rtpListener");
Json::Value json(Json::objectValue);
......@@ -354,6 +361,9 @@ namespace RTC
break;
}
// Add `useRemb`.
json[k_useRemb] = (this->remoteBitrateEstimator ? true : false);
// Add `rtpListener`.
json[k_rtpListener] = this->rtpListener.toJson();
......@@ -763,6 +773,18 @@ namespace RTC
// Pass the RTP packet to the corresponding RtpReceiver.
rtpReceiver->ReceiveRtpPacket(packet);
// Feed the remote bitrate estimator (REMB).
if (this->remoteBitrateEstimator)
{
uint32_t absSendTime;
if (packet->ReadAbsSendTime(&absSendTime))
{
this->remoteBitrateEstimator->IncomingPacket(
DepLibUV::GetTime(), packet->GetPayloadLength(), *packet, absSendTime);
}
}
delete packet;
}
......@@ -1084,4 +1106,21 @@ namespace RTC
MS_DEBUG_TAG(dtls, "DTLS application data received [size:%zu]", len);
}
void Transport::onReceiveBitrateChanged(const std::vector<uint32_t>& ssrcs, uint32_t bitrate)
{
MS_TRACE();
MS_DEBUG_TAG(rbe, "sending RTCP REMB packet [bitrate:%" PRIu32 "]", bitrate);
for (auto ssrc: ssrcs)
{
MS_DEBUG_TAG(rbe, " ssrc : %" PRIu32, ssrc);
}
RTC::RTCP::FeedbackPsRembPacket packet(0, 0);
packet.SetBitrate(bitrate);
packet.SetSsrcs(ssrcs);
packet.Serialize(Transport::rtcpBuffer);
this->SendRtcpPacket(&packet);
}
}
......@@ -194,6 +194,8 @@ void Settings::PrintConfiguration()
log_tags.push_back("srtp");
if (Settings::configuration.logTags.rtcp)
log_tags.push_back("rtcp");
if (Settings::configuration.logTags.rbe)
log_tags.push_back("rbe");
MS_DEBUG_TAG(info, "<configuration>");
......@@ -521,6 +523,8 @@ void Settings::SetLogTags(std::vector<std::string>& tags)
Settings::configuration.logTags.srtp = true;
else if (tag == "rtcp")
Settings::configuration.logTags.rtcp = true;
else if (tag == "rbe")
Settings::configuration.logTags.rbe = true;
}
}
......
......@@ -17,6 +17,7 @@
#include "RTC/RTCP/FeedbackPsVbcm.hpp"
#include "RTC/RTCP/FeedbackPsLei.hpp"
#include "RTC/RTCP/FeedbackPsAfb.hpp"
#include "RTC/RTCP/FeedbackPsRemb.hpp"
#include <string>
using namespace RTC::RTCP;
......@@ -612,8 +613,38 @@ SCENARIO("parse RTCP packets", "[parser][rtcp]")
FeedbackPsAfbPacket* packet = FeedbackPsAfbPacket::Parse(buffer, sizeof(buffer));
REQUIRE(packet);
REQUIRE((packet->GetData()[dataSize -1] & 1) == dataBitmask);
REQUIRE(packet->GetApplication() == FeedbackPsAfbPacket::UNKNOWN);
delete packet;
}
SECTION("FeedbackPsRembPacket")
{
uint32_t sender_ssrc = 0;
uint32_t media_ssrc = 0;
uint64_t bitrate = 654321;
// Precission lost.
uint64_t bitrateParsed = 654320;
std::vector<uint32_t> ssrcs { 11111, 22222, 33333, 44444 };
// Create a packet.
FeedbackPsRembPacket packet(sender_ssrc, media_ssrc);
packet.SetBitrate(bitrate);
packet.SetSsrcs(ssrcs);
// Serialize.
uint8_t rtcpBuffer[MS_RTCP_BUFFER_SIZE];
packet.Serialize(rtcpBuffer);
RTC::RTCP::Packet::CommonHeader* header = reinterpret_cast<RTC::RTCP::Packet::CommonHeader*>(rtcpBuffer);
size_t len = (size_t)(ntohs(header->length) + 1) * 4;
// Recover the packet out of the serialized buffer.
FeedbackPsRembPacket* parsed = FeedbackPsRembPacket::Parse(rtcpBuffer, len);
REQUIRE(parsed);
REQUIRE(parsed->GetMediaSsrc() == media_ssrc);
REQUIRE(parsed->GetSenderSsrc() == sender_ssrc);
REQUIRE(parsed->GetBitrate() == bitrateParsed);
REQUIRE(parsed->GetSsrcs() == ssrcs);
}
}
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论