提交 593f861e authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

Merge branch 'simulcast' into v2

......@@ -7,6 +7,10 @@
/worker/out/
/worker/**/*.xcodeproj/
# vim temporal files
*.swp
*.swo
# Others
/npm-debug.log
/NO_GIT/
# TODO in mediasoup v2 (server-side)
* Must avoid passing JSON data to Transport/Producer/Consumer instance methods. Instead, create API methods that receive "nice" C++ params and do all the JSON decode work in `Router::HandleRequest()`.
* Properly set extended seq32 for nacked packets.
* Must mangle RTP sequence numbers in Consumers:
- After paused.
- After the Producer gets `updateRtpParameters()` called (so a `OnProducerRtpParametersUpdated` listener is required in Producer for the Router to call `SourceRtpParametersUpdated()` on all its Concumers).
- NOTE: We may also need to mangle RTP timestamps!
* Check NackGenerator intervals.
* After `updateProducer` (which changes receiving SSRCs), should we do something in Transport between `producer->ReceiveRtpPacket(packet)` and `this->remoteBitrateEstimator->IncomingPacket`?
* Remove `producer.on('rtprawpacket')` and, instead, create a special `RtpConsumer` or something like that.
* Set a proper value for Producer::FullFrameRequestBlockTimeout (currently 1 second).
......
......@@ -4,6 +4,8 @@ const Logger = require('./Logger');
const EnhancedEventEmitter = require('./EnhancedEventEmitter');
const errors = require('./errors');
const PROFILES = new Set([ 'low', 'medium', 'high' ]);
const logger = new Logger('Consumer');
class Consumer extends EnhancedEventEmitter
......@@ -50,6 +52,14 @@ class Consumer extends EnhancedEventEmitter
// @type {Boolean}
this._sourcePaused = false;
// Preferred profile.
// @type {String}
this._preferredProfile = null;
// Effective profile.
// @type {String}
this._effectiveProfile = null;
this._handleWorkerNotifications();
}
......@@ -143,6 +153,26 @@ class Consumer extends EnhancedEventEmitter
return this._locallyPaused || this._remotelyPaused || this._sourcePaused;
}
/**
* The preferred profile.
*
* @type {String}
*/
get preferredProfile()
{
return this._preferredProfile;
}
/**
* The effective profile.
*
* @type {String}
*/
get effectiveProfile()
{
return this._effectiveProfile;
}
/**
* Close the Consumer.
*
......@@ -219,12 +249,14 @@ class Consumer extends EnhancedEventEmitter
toJson()
{
return {
id : this.id,
kind : this.kind,
peerName : this.peer.name,
rtpParameters : this.rtpParameters,
paused : this.paused,
appData : this.appData
id : this.id,
kind : this.kind,
peerName : this.peer.name,
rtpParameters : this.rtpParameters,
paused : this.paused,
preferredProfile : this.preferredProfile,
effectiveProfile : this.effectiveProfile,
appData : this.appData
};
}
......@@ -233,8 +265,9 @@ class Consumer extends EnhancedEventEmitter
*
* @param {Transport} transport
* @param {Boolean} remotelyPaused
* @param {String} preferredProfile
*/
enable(transport, remotelyPaused)
enable(transport, remotelyPaused, preferredProfile)
{
logger.debug('enable()');
......@@ -246,6 +279,9 @@ class Consumer extends EnhancedEventEmitter
if (remotelyPaused)
this.remotePause();
if (preferredProfile)
this.remoteSetPreferredProfile(preferredProfile);
const internal = Object.assign({}, this._internal,
{
transportId : transport.id
......@@ -450,10 +486,91 @@ class Consumer extends EnhancedEventEmitter
this.safeEmit('resume', 'remote', appData);
}
/**
* Sets the preferred RTP profile.
*
* @param {String} profile
*/
setPreferredProfile(profile)
{
logger.debug('setPreferredProfile() [profile:%s]', profile);
if (this._closed)
{
logger.error('setPreferredProfile() | Consumer closed');
return;
}
else if (profile === this._preferredProfile)
{
return;
}
else if (!PROFILES.has(profile))
{
logger.error('setPreferredProfile() | invalid profile "%s"', profile);
return;
}
this._channel.request('consumer.setPreferredProfile', this._internal,
{
profile
})
.then(() =>
{
logger.debug('"consumer.setPreferredProfile" request succeeded');
this._preferredProfile = profile;
const data =
{
id : this.id,
peerName : this.peer.name,
profile : profile
};
this.emit('@notify', 'consumerPreferredProfileSet', data);
})
.catch((error) =>
{
logger.error(
'"consumer.setPreferredProfile" request failed: %s', String(error));
});
}
/**
* Preferred receiving profile was set on my remote Consumer.
*
* @param {String} profile
*/
remoteSetPreferredProfile(profile)
{
logger.debug('remoteSetPreferredProfile() [profile:%s]', profile);
if (this._closed || profile === this._preferredProfile)
return;
this._channel.request('consumer.setPreferredProfile', this._internal,
{
profile
})
.then(() =>
{
logger.debug('"consumer.setPreferredProfile" request succeeded');
this._preferredProfile = profile;
})
.catch((error) =>
{
logger.error(
'"consumer.setPreferredProfile" request failed: %s', String(error));
});
}
_handleWorkerNotifications()
{
// Subscribe to notifications.
this._channel.on(this._internal.consumerId, (event) =>
this._channel.on(this._internal.consumerId, (event, data) =>
{
switch (event)
{
......@@ -473,13 +590,13 @@ class Consumer extends EnhancedEventEmitter
if (this.enabled && !this._locallyPaused)
{
const data =
const data2 =
{
id : this.id,
peerName : this.peer.name
};
this.emit('@notify', 'consumerPaused', data);
this.emit('@notify', 'consumerPaused', data2);
}
this.safeEmit('pause', 'source');
......@@ -496,13 +613,13 @@ class Consumer extends EnhancedEventEmitter
if (this.enabled && !this._locallyPaused)
{
const data =
const data2 =
{
id : this.id,
peerName : this.peer.name
};
this.emit('@notify', 'consumerResumed', data);
this.emit('@notify', 'consumerResumed', data2);
}
this.safeEmit('resume', 'source');
......@@ -510,6 +627,32 @@ class Consumer extends EnhancedEventEmitter
break;
}
case 'effectiveprofilechange':
{
const { profile } = data;
if (this._effectiveProfile === profile)
return;
this._effectiveProfile = profile;
if (this.enabled)
{
const data2 =
{
id : this.id,
peerName : this.peer.name,
profile : this._effectiveProfile
};
this.emit('@notify', 'consumerEffectiveProfileChanged', data2);
}
this.safeEmit('effectiveprofilechange', this._effectiveProfile);
break;
}
default:
logger.error('ignoring unknown event "%s"', event);
}
......
......@@ -400,7 +400,7 @@ class Peer extends EnhancedEventEmitter
case 'enableConsumer':
{
const { id, transportId, paused } = request;
const { id, transportId, paused, preferredProfile } = request;
const consumer = this._consumers.get(id);
const transport = this._transports.get(transportId);
......@@ -409,11 +409,13 @@ class Peer extends EnhancedEventEmitter
else if (!transport)
return Promise.reject(new TypeError('Transport not found'));
return consumer.enable(transport, paused)
return consumer.enable(transport, paused, preferredProfile)
.then(() =>
{
return {
paused : consumer.sourcePaused || consumer.locallyPaused
paused : consumer.sourcePaused || consumer.locallyPaused,
preferredProfile : consumer.preferredProfile,
effectiveProfile : consumer.effectiveProfile
};
});
}
......@@ -568,6 +570,19 @@ class Peer extends EnhancedEventEmitter
break;
}
case 'setConsumerPreferredProfile':
{
const { id, profile } = notification;
const consumer = this._consumers.get(id);
if (!consumer)
throw new Error('Consumer not found');
consumer.remoteSetPreferredProfile(profile);
break;
}
default:
throw new Error(`unknown notification method "${method}"`);
}
......@@ -623,7 +638,7 @@ class Peer extends EnhancedEventEmitter
source : producer
};
// Create a Producer instance.
// Create a Consumer instance.
const consumer = new Consumer(internal, data, this._channel);
consumer.appData = producer.appData;
......
......@@ -262,10 +262,6 @@ exports.getProducerRtpParametersMapping = function(params, caps)
* and the RTP capabilities of the Room.
* It may throw if invalid or non supported RTP parameters are given.
*
* TODO: This method should also reduce encodings in case of simulcast/SVC
* so the resulting consumable RTP parameters are suitable for a Consumer.
* For now we assume a single encoding in the Producer RTP parameters.
*
* @param {RTCRtpParameters} params
* @param {RTCRtpCapabilities} caps
* @param {Object} rtpMapping - As generated by getProducerRtpParametersMapping().
......@@ -379,7 +375,7 @@ exports.getConsumableRtpParameters = function(params, caps, rtpMapping)
/**
* Generate RTP parameters for a specific Consumer.
*
* NOTE: It's up to theremote Consumer to check the codecs and decide whether it
* NOTE: It's up to the remote Consumer to check the codecs and decide whether it
* can enable this Consumer or not.
*
* @param {RTCRtpParameters} consumableRtpParameters - Consumable RTP parameters.
......@@ -427,7 +423,7 @@ exports.getConsumerRtpParameters = function(consumableRtpParameters, rtpCapabili
const consumerEncoding =
{
ssrc : consumableRtpParameters.encodings[0].ssrc
ssrc : utils.randomNumber()
};
if (rtxSupported)
......
......@@ -262,7 +262,7 @@ const supportedRtpCapabilities =
preferredEncrypt : false
},
{
kind : '',
kind : 'video',
uri : 'urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id',
preferredId : 5,
preferredEncrypt : false
......
......@@ -42,7 +42,8 @@ namespace Channel
CONSUMER_DUMP,
CONSUMER_ENABLE,
CONSUMER_PAUSE,
CONSUMER_RESUME
CONSUMER_RESUME,
CONSUMER_SET_PREFERRED_PROFILE
};
private:
......
......@@ -15,11 +15,12 @@
#include "RTC/RtpStreamSend.hpp"
#include "RTC/Transport.hpp"
#include <json/json.h>
#include <set>
#include <unordered_set>
namespace RTC
{
class Consumer
class Consumer : public RtpStream::Listener
{
public:
Consumer(
......@@ -42,12 +43,15 @@ namespace RTC
void Resume();
void SourcePause();
void SourceResume();
void AddProfile(const RTC::RtpEncodingParameters::Profile profile);
void RemoveProfile(const RTC::RtpEncodingParameters::Profile profile);
void SourceRtpParametersUpdated();
void SetPreferredProfile(const RTC::RtpEncodingParameters::Profile profile);
void Disable();
bool IsEnabled() const;
const RTC::RtpParameters& GetParameters() const;
bool IsPaused() const;
void SendRtpPacket(RTC::RtpPacket* packet);
void SendRtpPacket(RTC::RtpPacket* packet, RTC::RtpEncodingParameters::Profile profile);
void GetRtcp(RTC::RTCP::CompoundPacket* packet, uint64_t now);
void ReceiveNack(RTC::RTCP::FeedbackRtpNackPacket* nackPacket);
void ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report);
......@@ -58,6 +62,11 @@ namespace RTC
void FillSupportedCodecPayloadTypes();
void CreateRtpStream(RTC::RtpEncodingParameters& encoding);
void RetransmitRtpPacket(RTC::RtpPacket* packet);
void RecalculateEffectiveProfile();
/* Pure virtual methods inherited from RTC::RtpStream::Listener. */
public:
void OnRtpStreamHealthReport(RTC::RtpStream* rtpStream, bool healthy) override;
public:
// Passed by argument.
......@@ -85,10 +94,17 @@ namespace RTC
RTC::RtpDataCounter retransmittedCounter;
// RTP sequence number and timestamp.
uint16_t seqNum{ 0 };
uint16_t maxSeqNum{ 0 };
uint32_t rtpTimestamp{ 0 };
uint16_t lastRecvSeqNum{ 0 };
uint32_t lastRecvRtpTimestamp{ 0 };
uint32_t maxRecvExtendedSeqNum{ 0 };
uint16_t maxRecvSeqNum{ 0 };
bool syncRequired{ true };
// RTP profiles.
std::set<RTC::RtpEncodingParameters::Profile> profiles;
RTC::RtpEncodingParameters::Profile preferredProfile{ RTC::RtpEncodingParameters::Profile::DEFAULT };
RTC::RtpEncodingParameters::Profile effectiveProfile{ RTC::RtpEncodingParameters::Profile::DEFAULT };
};
/* Inline methods. */
......
......@@ -15,6 +15,7 @@
#include "handles/Timer.hpp"
#include <json/json.h>
#include <map>
#include <set>
#include <string>
#include <unordered_set>
#include <vector>
......@@ -30,11 +31,24 @@ namespace RTC
std::map<uint8_t, uint8_t> headerExtensionIds;
};
public:
// TODO: YES?
// RTP header extension ids that must be shared by all the Producers using
// the same Transport.
// NOTE: These ids are the original ids in the RTP packet (before the Producer
// maps them to the corresponding ids in the room).
struct HeaderExtensionIdsForTransport
{
uint8_t absSendTime{ 0 }; // 0 means no abs-send-time id.
uint8_t rid{ 0 }; // 0 means no RID id.
};
private:
struct KnownHeaderExtensions
struct HeaderExtensionIds
{
uint8_t ssrcAudioLevelId{ 0 }; // 0 means no ssrc-audio-level id.
uint8_t absSendTimeId{ 0 }; // 0 means no abs-send-time id.
uint8_t ssrcAudioLevel{ 0 }; // 0 means no ssrc-audio-level id.
uint8_t absSendTime{ 0 }; // 0 means no abs-send-time id.
uint8_t rid{ 0 }; // 0 means no RID id.
};
public:
......@@ -64,26 +78,28 @@ namespace RTC
void SetRtpObjectEvent(bool enabled);
const RTC::RtpParameters& GetParameters() const;
bool IsPaused() const;
void ApplyExtensionIdMapping(RTC::RtpPacket* packet) const;
void ReceiveRtpPacket(RTC::RtpPacket* packet);
void ReceiveRtcpSenderReport(RTC::RTCP::SenderReport* report);
void GetRtcp(RTC::RTCP::CompoundPacket* packet, uint64_t now);
void ReceiveRtcpFeedback(RTC::RTCP::FeedbackPsPacket* packet) const;
void ReceiveRtcpFeedback(RTC::RTCP::FeedbackRtpPacket* packet) const;
void RequestFullFrame(bool force = false);
const std::set<RTC::RtpEncodingParameters::Profile> GetProfiles() const;
private:
void FillKnownHeaderExtensions();
void FillHeaderExtensionIds();
void CreateRtpStream(RTC::RtpEncodingParameters& encoding);
void ClearRtpStream(RTC::RtpStreamRecv* rtpStream);
void ClearRtpStreams();
void ApplyPayloadTypeMapping(RTC::RtpPacket* packet) const;
void ApplySsrcMapping(RTC::RtpPacket* packet) const;
void ApplyRtpMapping(RTC::RtpPacket* packet) const;
RTC::RtpEncodingParameters::Profile GetProfile(RTC::RtpStreamRecv* rtpStream, RTC::RtpPacket* packet);
/* Pure virtual methods inherited from RTC::RtpStreamRecv::Listener. */
public:
void OnRtpStreamRecvNackRequired(
RTC::RtpStreamRecv* rtpStream, const std::vector<uint16_t>& seqNumbers) override;
void OnRtpStreamRecvPliRequired(RTC::RtpStreamRecv* rtpStream) override;
void OnRtpStreamHealthReport(RTC::RtpStream* rtpStream, bool healthy) override;
/* Pure virtual methods inherited from Timer::Listener. */
public:
......@@ -104,11 +120,11 @@ namespace RTC
// Allocated by this.
std::map<uint32_t, RTC::RtpStreamRecv*> rtpStreams;
std::map<uint32_t, RTC::RtpStreamRecv*> mapRtxStreams;
std::map<RTC::RtpStreamRecv*, std::set<RTC::RtpEncodingParameters::Profile>> profiles;
Timer* fullFrameRequestBlockTimer{ nullptr };
// Others.
std::vector<RtpEncodingParameters> outputEncodings;
struct KnownHeaderExtensions knownHeaderExtensions;
std::map<uint32_t, uint32_t> ssrcMapping;
struct HeaderExtensionIds headerExtensionIds;
bool paused{ false };
bool rtpRawEventEnabled{ false };
bool rtpObjectEventEnabled{ false };
......@@ -151,6 +167,26 @@ namespace RTC
rtpStream->ReceiveRtcpSenderReport(report);
}
}
inline const std::set<RTC::RtpEncodingParameters::Profile> Producer::GetProfiles() const
{
std::set<RTC::RtpEncodingParameters::Profile> profiles;
for (const auto& it : this->profiles)
{
for (const auto& it2 : it.second)
{
auto profile = it2;
if (profile == RTC::RtpEncodingParameters::Profile::DEFAULT)
break;
profiles.insert(profile);
}
}
return profiles;
}
} // namespace RTC
#endif
......@@ -12,11 +12,16 @@ namespace RTC
class ProducerListener
{
public:
virtual void OnProducerClosed(RTC::Producer* producer) = 0;
virtual void OnProducerRtpParametersUpdated(RTC::Producer* producer) = 0;
virtual void OnProducerPaused(RTC::Producer* producer) = 0;
virtual void OnProducerResumed(RTC::Producer* producer) = 0;
virtual void OnProducerRtpPacket(RTC::Producer* producer, RTC::RtpPacket* packet) = 0;
virtual void OnProducerClosed(RTC::Producer* producer) = 0;
virtual void OnProducerRtpParametersUpdated(RTC::Producer* producer) = 0;
virtual void OnProducerPaused(RTC::Producer* producer) = 0;
virtual void OnProducerResumed(RTC::Producer* producer) = 0;
virtual void OnProducerRtpPacket(
RTC::Producer* producer, RTC::RtpPacket* packet, RTC::RtpEncodingParameters::Profile profile) = 0;
virtual void OnProducerProfileEnabled(
RTC::Producer* producer, RTC::RtpEncodingParameters::Profile profile) = 0;
virtual void OnProducerProfileDisabled(
RTC::Producer* producer, RTC::RtpEncodingParameters::Profile profile) = 0;
};
} // namespace RTC
......
......@@ -67,7 +67,14 @@ namespace RTC
void OnProducerRtpParametersUpdated(RTC::Producer* producer) override;
void OnProducerPaused(RTC::Producer* producer) override;
void OnProducerResumed(RTC::Producer* producer) override;
void OnProducerRtpPacket(RTC::Producer* producer, RTC::RtpPacket* packet) override;
void OnProducerRtpPacket(
RTC::Producer* producer,
RTC::RtpPacket* packet,
RTC::RtpEncodingParameters::Profile profile) override;
void OnProducerProfileEnabled(
RTC::Producer* producer, RTC::RtpEncodingParameters::Profile profile) override;
void OnProducerProfileDisabled(
RTC::Producer* producer, RTC::RtpEncodingParameters::Profile profile) override;
/* Pure virtual methods inherited from RTC::ConsumerListener. */
public:
......
......@@ -206,6 +206,20 @@ namespace RTC
class RtpEncodingParameters
{
public:
enum class Profile : uint8_t
{
NONE = 0,
DEFAULT,
LOW,
MEDIUM,
HIGH
};
public:
static std::map<std::string, Profile> string2Profile;
static std::map<Profile, std::string> profile2String;
public:
RtpEncodingParameters(){};
explicit RtpEncodingParameters(Json::Value& data);
......@@ -226,6 +240,7 @@ namespace RTC
bool active{ true };
std::string encodingId;
std::vector<std::string> dependencyEncodingIds;
Profile profile{ Profile::DEFAULT };
};
class RtpHeaderExtensionParameters
......
......@@ -19,7 +19,6 @@ namespace RTC
Json::Value ToJson() const;
bool HasSsrc(uint32_t ssrc, const RTC::Producer* producer) const;
bool HasMuxId(const std::string& muxId, const RTC::Producer* producer) const;
bool HasPayloadType(uint8_t payloadType, const RTC::Producer* producer) const;
void AddProducer(RTC::Producer* producer);
void RemoveProducer(const RTC::Producer* producer);
RTC::Producer* GetProducer(RTC::RtpPacket* packet);
......@@ -27,18 +26,13 @@ namespace RTC
private:
void RollbackProducer(
RTC::Producer* producer,
std::vector<uint32_t>& previousSsrcs,
std::string& previousMuxId,
std::vector<uint8_t>& previousPayloadTypes);
RTC::Producer* producer, std::vector<uint32_t>& previousSsrcs, std::string& previousMuxId);
public:
// Table of SSRC / Producer pairs.
std::unordered_map<uint32_t, RTC::Producer*> ssrcTable;
// Table of MID RTP header extension / Producer pairs.
std::unordered_map<std::string, const RTC::Producer*> muxIdTable;
// Table of RTP payload type / Producer pairs.
std::unordered_map<uint8_t, RTC::Producer*> ptTable;
};
/* Inline instance methods. */
......@@ -48,13 +42,9 @@ namespace RTC
auto it = this->ssrcTable.find(ssrc);
if (it == this->ssrcTable.end())
{
return false;
}
else
{
return (it->second != producer);
}
}
inline bool RtpListener::HasMuxId(const std::string& muxId, const RTC::Producer* producer) const
......@@ -62,27 +52,9 @@ namespace RTC
auto it = this->muxIdTable.find(muxId);
if (it == this->muxIdTable.end())
{
return false;
}
else
{
return (it->second != producer);
}
}
inline bool RtpListener::HasPayloadType(uint8_t payloadType, const RTC::Producer* producer) const
{
auto it = this->ptTable.find(payloadType);
if (it == this->ptTable.end())
{
return false;
}
else
{
return (it->second != producer);
}
}
} // namespace RTC
......
......@@ -110,8 +110,8 @@ namespace RTC
void MangleExtensionHeaderIds(const std::map<uint8_t, uint8_t>& idMapping);
bool HasOneByteExtensions() const;
bool HasTwoBytesExtensions() const;
void AddExtensionMapping(RtpHeaderExtensionUri::Type uri, uint8_t id);
uint8_t* GetExtension(RtpHeaderExtensionUri::Type uri, uint8_t* len) const;
void AddExtensionMapping(RTC::RtpHeaderExtensionUri::Type uri, uint8_t id);
uint8_t* GetExtension(RTC::RtpHeaderExtensionUri::Type uri, uint8_t* len) const;
bool ReadAudioLevel(uint8_t* volume, bool* voice) const;
bool ReadAbsSendTime(uint32_t* time) const;
uint8_t* GetPayload() const;
......@@ -131,7 +131,7 @@ namespace RTC
ExtensionHeader* extensionHeader{ nullptr };
std::map<uint8_t, OneByteExtension*> oneByteExtensions;
std::map<uint8_t, TwoBytesExtension*> twoBytesExtensions;
std::map<RtpHeaderExtensionUri::Type, uint8_t> extensionMap;
std::map<RTC::RtpHeaderExtensionUri::Type, uint8_t> extensionMap;
uint8_t* payload{ nullptr };
size_t payloadLength{ 0 };
uint8_t payloadPadding{ 0 };
......@@ -266,12 +266,12 @@ namespace RTC
return (GetExtensionHeaderId() & 0b1111111111110000) == 0b0001000000000000;
}
inline void RtpPacket::AddExtensionMapping(RtpHeaderExtensionUri::Type uri, uint8_t id)
inline void RtpPacket::AddExtensionMapping(RTC::RtpHeaderExtensionUri::Type uri, uint8_t id)
{
this->extensionMap[uri] = id;
}
inline uint8_t* RtpPacket::GetExtension(RtpHeaderExtensionUri::Type uri, uint8_t* len) const
inline uint8_t* RtpPacket::GetExtension(RTC::RtpHeaderExtensionUri::Type uri, uint8_t* len) const
{
*len = 0;
......@@ -309,7 +309,7 @@ namespace RTC
uint8_t extenLen;
uint8_t* extenValue;
extenValue = GetExtension(RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL, &extenLen);
extenValue = GetExtension(RTC::RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL, &extenLen);
if (!extenValue || extenLen != 1)
return false;
......@@ -326,7 +326,7 @@ namespace RTC
uint8_t extenLen;
uint8_t* extenValue;
extenValue = GetExtension(RtpHeaderExtensionUri::Type::ABS_SEND_TIME, &extenLen);
extenValue = GetExtension(RTC::RtpHeaderExtensionUri::Type::ABS_SEND_TIME, &extenLen);
if (!extenValue || extenLen != 3)
return false;
......
......@@ -4,12 +4,20 @@
#include "common.hpp"
#include "RTC/RtpDictionaries.hpp"
#include "RTC/RtpPacket.hpp"
#include "handles/Timer.hpp"
#include <json/json.h>
namespace RTC
{
class RtpStream
class RtpStream : public Timer::Listener
{
public:
class Listener
{
public:
virtual void OnRtpStreamHealthReport(RTC::RtpStream* rtpStream, bool healthy) = 0;
};
public:
struct Params
{
......@@ -27,9 +35,10 @@ namespace RTC
explicit RtpStream(RTC::RtpStream::Params& params);
virtual ~RtpStream();
virtual Json::Value ToJson() const = 0;
uint32_t GetSsrc();
virtual Json::Value ToJson() = 0;
virtual bool ReceivePacket(RTC::RtpPacket* packet);
uint32_t GetSsrc();
bool IsHealthy();
protected:
void InitSeq(uint16_t seq);
......@@ -39,7 +48,12 @@ namespace RTC
/* Pure virtual methods that must be implemented by the subclass. */
protected:
virtual void OnInitSeq() = 0;
virtual void OnInitSeq() = 0;
virtual void CheckHealth() = 0;
/* Pure virtual methods inherited from Timer::Listener. */
public:
void OnTimer(Timer* timer) override;
protected:
// Given as argument.
......@@ -52,12 +66,13 @@ namespace RTC
uint32_t cycles{ 0 }; // Shifted count of seq. number cycles.
uint32_t baseSeq{ 0 }; // Base seq number.
uint32_t badSeq{ 0 }; // Last 'bad' seq number + 1.
uint32_t probation{ 0 }; // Seq. packets till source is valid.
uint32_t received{ 0 }; // Packets received.
uint32_t expectedPrior{ 0 }; // Packet expected at last interval.
uint32_t receivedPrior{ 0 }; // Packet received at last interval.
// Others.
uint32_t maxTimestamp{ 0 }; // Highest timestamp seen.
Timer* healthCheckTimer{ nullptr };
bool healthy{ true };
};
/* Inline instance methods. */
......@@ -66,6 +81,11 @@ namespace RTC
{
return this->params.ssrc;
}
inline bool RtpStream::IsHealthy()
{
return this->healthy;
}
} // namespace RTC
#endif
......@@ -4,6 +4,7 @@
#include "RTC/NackGenerator.hpp"
#include "RTC/RTCP/ReceiverReport.hpp"
#include "RTC/RTCP/SenderReport.hpp"
#include "RTC/RtpDataCounter.hpp"
#include "RTC/RtpStream.hpp"
namespace RTC
......@@ -11,7 +12,7 @@ namespace RTC
class RtpStreamRecv : public RtpStream, public RTC::NackGenerator::Listener
{
public:
class Listener
class Listener : public RtpStream::Listener
{
public:
virtual void OnRtpStreamRecvNackRequired(
......@@ -23,13 +24,14 @@ namespace RTC
RtpStreamRecv(Listener* listener, RTC::RtpStream::Params& params);
~RtpStreamRecv() override;
Json::Value ToJson() const override;
Json::Value ToJson() override;
bool ReceivePacket(RTC::RtpPacket* packet) override;
bool ReceiveRtxPacket(RTC::RtpPacket* packet);
RTC::RTCP::ReceiverReport* GetRtcpReceiverReport();
void ReceiveRtcpSenderReport(RTC::RTCP::SenderReport* report);
void SetRtx(uint8_t payloadType, uint32_t ssrc);
void RequestFullFrame();
uint32_t GetBitRate();
private:
void CalculateJitter(uint32_t rtpTimestamp);
......@@ -37,6 +39,7 @@ namespace RTC
/* Pure virtual methods inherited from RtpStream. */
protected:
void OnInitSeq() override;
virtual void CheckHealth() override;
/* Pure virtual methods inherited from RTC::NackGenerator. */
protected:
......@@ -54,11 +57,12 @@ namespace RTC
uint32_t transit{ 0 }; // Relative trans time for prev pkt.
uint32_t jitter{ 0 }; // Estimated jitter.
std::unique_ptr<RTC::NackGenerator> nackGenerator;
// RTX related.
bool hasRtx{ false };
uint8_t rtxPayloadType{ 0 };
uint32_t rtxSsrc{ 0 };
// RTP counters.
RTC::RtpDataCounter receivedCounter;
};
} // namespace RTC
......
......@@ -29,7 +29,7 @@ namespace RTC
RtpStreamSend(RTC::RtpStream::Params& params, size_t bufferSize);
~RtpStreamSend() override;
Json::Value ToJson() const override;
Json::Value ToJson() override;
bool ReceivePacket(RTC::RtpPacket* packet) override;
void ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report);
void RequestRtpRetransmission(
......@@ -39,15 +39,15 @@ namespace RTC
void SetRtx(uint8_t payloadType, uint32_t ssrc);
bool HasRtx() const;
void RtxEncode(RtpPacket* packet);
void Reset();
void ClearRetransmissionBuffer();
private:
void ClearBuffer();
void StorePacket(RTC::RtpPacket* packet);
/* Pure virtual methods inherited from RtpStream. */
protected:
void OnInitSeq() override;
void CheckHealth() override;
private:
std::vector<StorageItem> storage;
......
......@@ -153,7 +153,14 @@ namespace RTC
void OnProducerRtpParametersUpdated(RTC::Producer* producer) override;
void OnProducerPaused(RTC::Producer* producer) override;
void OnProducerResumed(RTC::Producer* producer) override;
void OnProducerRtpPacket(RTC::Producer* producer, RTC::RtpPacket* packet) override;
void OnProducerRtpPacket(
RTC::Producer* producer,
RTC::RtpPacket* packet,
RTC::RtpEncodingParameters::Profile profile) override;
void OnProducerProfileEnabled(
RTC::Producer* producer, RTC::RtpEncodingParameters::Profile profile) override;
void OnProducerProfileDisabled(
RTC::Producer* producer, RTC::RtpEncodingParameters::Profile profile) override;
/* Pure virtual methods inherited from RTC::ConsumerListener. */
public:
......
......@@ -37,7 +37,8 @@ namespace Channel
{ "consumer.dump", Request::MethodId::CONSUMER_DUMP },
{ "consumer.enable", Request::MethodId::CONSUMER_ENABLE },
{ "consumer.pause", Request::MethodId::CONSUMER_PAUSE },
{ "consumer.resume", Request::MethodId::CONSUMER_RESUME }
{ "consumer.resume", Request::MethodId::CONSUMER_RESUME },
{ "consumer.setPreferredProfile", Request::MethodId::CONSUMER_SET_PREFERRED_PROFILE }
};
// clang-format on
......
......@@ -24,7 +24,7 @@ namespace RTC
MS_TRACE();
// Initialize sequence number.
this->seqNum = static_cast<uint16_t>(Utils::Crypto::GetRandomUInt(0x00FF, 0xFFFF));
this->maxSeqNum = static_cast<uint16_t>(Utils::Crypto::GetRandomUInt(0x00FF, 0xFFFF));
// Set the RTCP report generation interval.
if (this->kind == RTC::Media::Kind::AUDIO)
......@@ -66,6 +66,8 @@ namespace RTC
static const Json::StaticString JsonStringEnabled{ "enabled" };
static const Json::StaticString JsonStringPaused{ "paused" };
static const Json::StaticString JsonStringSourcePaused{ "sourcePaused" };
static const Json::StaticString JsonStringPreferredProfile{ "preferredProfile" };
static const Json::StaticString JsonStringEffectiveProfile{ "effectiveProfile" };
Json::Value json(Json::objectValue);
......@@ -85,6 +87,12 @@ namespace RTC
json[JsonStringSourcePaused] = this->sourcePaused;
json[JsonStringPreferredProfile] =
RTC::RtpEncodingParameters::profile2String[this->preferredProfile];
json[JsonStringEffectiveProfile] =
RTC::RtpEncodingParameters::profile2String[this->effectiveProfile];
return json;
}
......@@ -119,6 +127,12 @@ namespace RTC
{
MS_TRACE();
// Must have a single encoding.
if (rtpParameters.encodings.empty())
MS_THROW_ERROR("invalid empty rtpParameters.encodings");
else if (rtpParameters.encodings[0].ssrc == 0)
MS_THROW_ERROR("missing rtpParameters.encodings[0].ssrc");
if (IsEnabled())
Disable();
......@@ -145,9 +159,7 @@ namespace RTC
MS_DEBUG_DEV("Consumer paused [consumerId:%" PRIu32 "]", this->consumerId);
if (IsEnabled() && !this->sourcePaused)
{
this->rtpStream->Reset();
}
this->rtpStream->ClearRetransmissionBuffer();
}
void Consumer::Resume()
......@@ -181,9 +193,7 @@ namespace RTC
this->notifier->Emit(this->consumerId, "sourcepaused");
if (IsEnabled() && !this->paused)
{
this->rtpStream->Reset();
}
this->rtpStream->ClearRetransmissionBuffer();
}
void Consumer::SourceResume()
......@@ -200,9 +210,7 @@ namespace RTC
this->notifier->Emit(this->consumerId, "sourceresumed");
if (IsEnabled() && !this->paused)
{
RequestFullFrame();
}
}
void Consumer::SourceRtpParametersUpdated()
......@@ -213,6 +221,59 @@ namespace RTC
return;
this->syncRequired = true;
this->rtpStream->ClearRetransmissionBuffer();
}
void Consumer::AddProfile(const RTC::RtpEncodingParameters::Profile profile)
{
MS_ASSERT(
profile != RTC::RtpEncodingParameters::Profile::NONE &&
profile != RTC::RtpEncodingParameters::Profile::DEFAULT,
"invalid profile");
MS_ASSERT(this->profiles.find(profile) == this->profiles.end(), "profile already exists");
// Insert profile.
this->profiles.insert(profile);
MS_DEBUG_TAG(
rtp, "profile added: %s", RTC::RtpEncodingParameters::profile2String[profile].c_str());
;
RecalculateEffectiveProfile();
}
void Consumer::RemoveProfile(const RTC::RtpEncodingParameters::Profile profile)
{
MS_ASSERT(
profile != RTC::RtpEncodingParameters::Profile::NONE &&
profile != RTC::RtpEncodingParameters::Profile::DEFAULT,
"invalid profile");
MS_ASSERT(this->profiles.find(profile) != this->profiles.end(), "profile not found");
// Remove profile.
this->profiles.erase(profile);
MS_DEBUG_TAG(
rtp,
"profile removed: %s",
RTC::RtpEncodingParameters::profile2String[this->effectiveProfile].c_str());
;
RecalculateEffectiveProfile();
}
void Consumer::SetPreferredProfile(const RTC::RtpEncodingParameters::Profile profile)
{
MS_TRACE();
if (this->preferredProfile == profile)
return;
this->preferredProfile = profile;
RecalculateEffectiveProfile();
}
/**
......@@ -239,7 +300,7 @@ namespace RTC
this->retransmittedCounter.Reset();
}
void Consumer::SendRtpPacket(RTC::RtpPacket* packet)
void Consumer::SendRtpPacket(RTC::RtpPacket* packet, RTC::RtpEncodingParameters::Profile profile)
{
MS_TRACE();
......@@ -250,15 +311,6 @@ namespace RTC
if (IsPaused())
return;
// Ignore the packet if the SSRC is not the single one in the sender
// RTP parameters.
if (packet->GetSsrc() != this->rtpParameters.encodings[0].ssrc)
{
MS_WARN_TAG(rtp, "ignoring packet with unknown SSRC [ssrc:%" PRIu32 "]", packet->GetSsrc());
return;
}
// Map the payload type.
auto payloadType = packet->GetPayloadType();
......@@ -271,22 +323,46 @@ namespace RTC
return;
}
// If the packet belongs to different profile than the one being sent, drop it.
// NOTE: This is specific to simulcast with no temporal layers.
if (profile != this->effectiveProfile)
return;
// Check whether sequence number and timestamp sync is required.
if (this->syncRequired)
{
this->seqNum += 1;
this->seqNum = ++this->maxSeqNum;
auto now = static_cast<uint32_t>(DepLibUV::GetTime());
if (now > this->rtpTimestamp)
this->rtpTimestamp = now;
this->maxRecvExtendedSeqNum = packet->GetExtendedSequenceNumber();
this->maxRecvSeqNum = packet->GetSequenceNumber();
this->syncRequired = false;
MS_DEBUG_TAG(
rtp,
"re-syncing Consumer stream [seqNum:%" PRIu16 ", maxRecvSeqNum:%" PRIu16
", maxRecvExtendedSeqNum:%" PRIu32 "]",
this->seqNum,
this->maxRecvSeqNum,
this->maxRecvExtendedSeqNum);
}
else
{
this->seqNum += packet->GetSequenceNumber() - this->lastRecvSeqNum;
this->rtpTimestamp += packet->GetTimestamp() - this->lastRecvRtpTimestamp;
// Update the max received sequence number if required.
if (packet->GetExtendedSequenceNumber() > this->maxRecvExtendedSeqNum)
{
this->maxRecvExtendedSeqNum = packet->GetExtendedSequenceNumber();
this->maxRecvSeqNum = packet->GetSequenceNumber();
this->maxSeqNum = this->seqNum;
}
}
// Save the received sequence number.
......@@ -295,10 +371,16 @@ namespace RTC
// Save the received timestamp.
this->lastRecvRtpTimestamp = packet->GetTimestamp();
// Update packet sequence number.
// Save real SSRC.
auto ssrc = packet->GetSsrc();
// Rewrite packet SSRC.
packet->SetSsrc(this->rtpParameters.encodings[0].ssrc);
// Rewrite packet sequence number.
packet->SetSequenceNumber(this->seqNum);
// Update packet timestamp.
// Rewrite packet timestamp.
packet->SetTimestamp(this->rtpTimestamp);
// Process the packet.
......@@ -311,6 +393,9 @@ namespace RTC
this->transmittedCounter.Update(packet);
}
// Restore packet SSRC.
packet->SetSsrc(ssrc);
// Restore the original sequence number.
packet->SetSequenceNumber(this->lastRecvSeqNum);
......@@ -400,6 +485,14 @@ namespace RTC
}
}
void Consumer::OnRtpStreamHealthReport(RtpStream* stream, bool healthy)
{
MS_TRACE();
if (!IsEnabled())
return;
}
void Consumer::FillSupportedCodecPayloadTypes()
{
MS_TRACE();
......@@ -475,8 +568,8 @@ namespace RTC
MS_DEBUG_TAG(
rtx,
"sending rtx packet [ssrc: %" PRIu32 " seqnr: %" PRIu16
"] recovering original [ssrc: %" PRIu32 " seqnr: %" PRIu16 "]",
"sending RTX packet [ssrc: %" PRIu32 ", seq: %" PRIu16
"] recovering original [ssrc: %" PRIu32 ", seq: %" PRIu16 "]",
rtxPacket->GetSsrc(),
rtxPacket->GetSequenceNumber(),
packet->GetSsrc(),
......@@ -487,7 +580,7 @@ namespace RTC
rtxPacket = packet;
MS_DEBUG_TAG(
rtx,
"retransmitting packet [ssrc: %" PRIu32 " seqnr: %" PRIu16 "]",
"retransmitting packet [ssrc: %" PRIu32 ", seq: %" PRIu16 "]",
rtxPacket->GetSsrc(),
rtxPacket->GetSequenceNumber());
}
......@@ -502,4 +595,71 @@ namespace RTC
if (rtxPacket != packet)
delete rtxPacket;
}
void Consumer::RecalculateEffectiveProfile()
{
static const Json::StaticString JsonStringProfile{ "profile" };
Json::Value eventData(Json::objectValue);
RTC::RtpEncodingParameters::Profile newProfile;
// If there are no profiles, select none or default, depending on whether this
// is single stream or simulcast/SVC.
if (this->profiles.empty())
{
if (this->effectiveProfile != RtpEncodingParameters::Profile::DEFAULT)
newProfile = RtpEncodingParameters::Profile::NONE;
else
newProfile = RtpEncodingParameters::Profile::DEFAULT;
}
// If there is no preferred profile, take the best one available.
else if (this->preferredProfile == RTC::RtpEncodingParameters::Profile::DEFAULT)
{
auto it = this->profiles.crbegin();
newProfile = *it;
}
// Otherwise take the highest available profile equal or lower than the preferred.
else
{
std::set<RtpEncodingParameters::Profile>::reverse_iterator it;
newProfile = RtpEncodingParameters::Profile::NONE;
for (it = this->profiles.rbegin(); it != this->profiles.rend(); ++it)
{
auto profile = *it;
if (profile <= this->preferredProfile)
{
newProfile = *it;
break;
}
}
}
if (newProfile == this->effectiveProfile)
return;
this->effectiveProfile = newProfile;
MS_DEBUG_TAG(
rtp,
"new effective profile: %s",
RTC::RtpEncodingParameters::profile2String[this->effectiveProfile].c_str());
;
// Notify.
eventData[JsonStringProfile] = RTC::RtpEncodingParameters::profile2String[this->effectiveProfile];
this->notifier->Emit(this->consumerId, "effectiveprofilechange", eventData);
if (IsEnabled() && !IsPaused())
{
this->rtpStream->ClearRetransmissionBuffer();
RequestFullFrame();
}
this->syncRequired = true;
}
} // namespace RTC
......@@ -9,11 +9,11 @@ namespace RTC
{
/* Static. */
constexpr uint32_t MaxPacketAge{ 10000 };
constexpr size_t MaxNackPackets{ 500 };
constexpr uint32_t MaxPacketAge{ 2500 };
constexpr size_t MaxNackPackets{ 300 };
constexpr uint32_t DefaultRtt{ 100 };
constexpr uint8_t MaxNackRetries{ 8 };
constexpr uint64_t TimerInterval{ 25 };
constexpr uint8_t MaxNackRetries{ 3 };
constexpr uint64_t TimerInterval{ 50 };
/* Instance methods. */
......@@ -59,7 +59,8 @@ namespace RTC
return;
}
// May be an out of order packet or a retransmitted packet (without RTX).
// May be an out of order packet, or already handled retransmitted packet,
// or a retransmitted packet.
if (seq32 < this->lastSeq32)
{
auto it = this->nackList.find(seq32);
......@@ -75,12 +76,13 @@ namespace RTC
this->nackList.erase(it);
}
// Out of order packet.
// Out of order packet or already handled NACKed packet.
else
{
MS_DEBUG_TAG(
rtx,
"out of order RTX packet received [ssrc:%" PRIu32 ", seq:%" PRIu16 "]",
"ignoring out of order packet or already handled NACKed packet [ssrc:%" PRIu32
", seq:%" PRIu16 "]",
packet->GetSsrc(),
packet->GetSequenceNumber());
}
......
......@@ -34,13 +34,7 @@ namespace RTC
this->rtpMapping = rtpMapping;
// Fill ids of well known RTP header extensions with the mapped ids (if any).
FillKnownHeaderExtensions();
// Create RtpStreamRecv instances.
for (auto& encoding : this->rtpParameters.encodings)
{
CreateRtpStream(encoding);
}
FillHeaderExtensionIds();
// Set the RTCP report generation interval.
if (this->kind == RTC::Media::Kind::AUDIO)
......@@ -56,6 +50,8 @@ namespace RTC
{
MS_TRACE();
this->profiles.clear();
ClearRtpStreams();
}
......@@ -82,13 +78,16 @@ namespace RTC
static const Json::StaticString JsonStringKind{ "kind" };
static const Json::StaticString JsonStringRtpParameters{ "rtpParameters" };
static const Json::StaticString JsonStringRtpStreams{ "rtpStreams" };
static const Json::StaticString JsonStringSsrcAudioLevelId{ "ssrcAudioLevelId" };
static const Json::StaticString JsonStringAbsSendTimeId{ "absSendTimeId" };
static const Json::StaticString JsonStringHeaderExtensionIds{ "headerExtensionIds" };
static const Json::StaticString JsonStringSsrcAudioLevel{ "ssrcAudioLevel" };
static const Json::StaticString JsonStringAbsSendTime{ "absSendTime" };
static const Json::StaticString JsonStringRid{ "rid" };
static const Json::StaticString JsonStringPaused{ "paused" };
static const Json::StaticString JsonStringRtpRawEventEnabled{ "rtpRawEventEnabled" };
static const Json::StaticString JsonStringRtpObjectEventEnabled{ "rtpObjectEventEnabled" };
Json::Value json(Json::objectValue);
Json::Value jsonHeaderExtensionIds(Json::objectValue);
Json::Value jsonRtpStreams(Json::arrayValue);
json[JsonStringProducerId] = Json::UInt{ this->producerId };
......@@ -105,11 +104,16 @@ namespace RTC
}
json[JsonStringRtpStreams] = jsonRtpStreams;
if (this->knownHeaderExtensions.ssrcAudioLevelId != 0u)
json[JsonStringSsrcAudioLevelId] = this->knownHeaderExtensions.ssrcAudioLevelId;
if (this->headerExtensionIds.ssrcAudioLevel != 0u)
jsonHeaderExtensionIds[JsonStringSsrcAudioLevel] = this->headerExtensionIds.ssrcAudioLevel;
if (this->headerExtensionIds.absSendTime != 0u)
jsonHeaderExtensionIds[JsonStringAbsSendTime] = this->headerExtensionIds.absSendTime;
if (this->knownHeaderExtensions.absSendTimeId != 0u)
json[JsonStringAbsSendTimeId] = this->knownHeaderExtensions.absSendTimeId;
if (this->headerExtensionIds.rid != 0u)
jsonHeaderExtensionIds[JsonStringRid] = this->headerExtensionIds.rid;
json[JsonStringHeaderExtensionIds] = jsonHeaderExtensionIds;
json[JsonStringPaused] = this->paused;
......@@ -153,51 +157,13 @@ namespace RTC
// Clear previous RtpStreamRecv instances.
ClearRtpStreams();
// Create new RtpStreamRecv instances.
for (auto& encoding : this->rtpParameters.encodings)
{
CreateRtpStream(encoding);
}
for (auto& listener : this->listeners)
{
// NOTE: This may throw.
listener->OnProducerRtpParametersUpdated(this);
}
// Fill the SSRC mapping table.
this->ssrcMapping.clear();
auto& newEncodings = this->rtpParameters.encodings;
for (size_t i = 0; i != this->outputEncodings.size(); ++i)
{
if (i == newEncodings.size())
break;
auto& newEncoding = newEncodings[i];
auto& outputEncoding = this->outputEncodings[i];
if (outputEncoding.ssrc != newEncoding.ssrc)
{
this->ssrcMapping[newEncoding.ssrc] = outputEncoding.ssrc;
}
if (outputEncoding.hasRtx && newEncoding.hasRtx && outputEncoding.rtx.ssrc != newEncoding.rtx.ssrc)
{
this->ssrcMapping[newEncoding.rtx.ssrc] = outputEncoding.rtx.ssrc;
}
if (outputEncoding.hasFec && newEncoding.hasFec && outputEncoding.fec.ssrc != newEncoding.fec.ssrc)
{
this->ssrcMapping[newEncoding.fec.ssrc] = outputEncoding.fec.ssrc;
}
}
MS_DEBUG_DEV("Producer RTP parameters updated [producerId:%" PRIu32 "]", this->producerId);
RequestFullFrame(true);
}
void Producer::Pause()
......@@ -296,6 +262,26 @@ namespace RTC
// Find the corresponding RtpStreamRecv.
uint32_t ssrc = packet->GetSsrc();
if (
this->rtpStreams.find(ssrc) == this->rtpStreams.end() &&
this->mapRtxStreams.find(ssrc) == this->mapRtxStreams.end())
{
for (auto& encoding : this->rtpParameters.encodings)
{
// TODO: This is not ready for RID usage (without SSRC in encodings).
if (encoding.ssrc == ssrc)
{
CreateRtpStream(encoding);
// If this is the first media packet for this stream request a full frame.
if (encoding.ssrc == ssrc)
RequestFullFrame(true);
break;
}
}
}
RTC::RtpStreamRecv* rtpStream{ nullptr };
if (this->rtpStreams.find(ssrc) != this->rtpStreams.end())
......@@ -321,18 +307,28 @@ namespace RTC
return;
}
RTC::RtpEncodingParameters::Profile profile;
try
{
profile = GetProfile(rtpStream, packet);
}
catch (const MediaSoupError& error)
{
return;
}
// If paused stop here.
if (this->paused)
return;
// Apply the Producer codec payload type and SSRC mapping before dispatching
// the packet.
ApplyPayloadTypeMapping(packet);
ApplySsrcMapping(packet);
// Apply the Producer codec payload type and extension header mapping before
// dispatching the packet.
ApplyRtpMapping(packet);
for (auto& listener : this->listeners)
{
listener->OnProducerRtpPacket(this, packet);
listener->OnProducerRtpPacket(this, packet, profile);
}
// Emit "rtpraw" if enabled.
......@@ -377,27 +373,6 @@ namespace RTC
this->lastRtcpSentTime = now;
}
void Producer::ApplyExtensionIdMapping(RTC::RtpPacket* packet) const
{
MS_TRACE();
auto& headerExtensionIdMap = this->rtpMapping.headerExtensionIds;
packet->MangleExtensionHeaderIds(headerExtensionIdMap);
if (this->knownHeaderExtensions.ssrcAudioLevelId != 0u)
{
packet->AddExtensionMapping(
RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL, this->knownHeaderExtensions.ssrcAudioLevelId);
}
if (this->knownHeaderExtensions.absSendTimeId != 0u)
{
packet->AddExtensionMapping(
RtpHeaderExtensionUri::Type::ABS_SEND_TIME, this->knownHeaderExtensions.absSendTimeId);
}
}
void Producer::ReceiveRtcpFeedback(RTC::RTCP::FeedbackPsPacket* packet) const
{
MS_TRACE();
......@@ -451,11 +426,9 @@ namespace RTC
return;
}
else
{
// Run the timer.
this->fullFrameRequestBlockTimer->Start(FullFrameRequestBlockTimeout);
}
// Run the timer.
this->fullFrameRequestBlockTimer->Start(FullFrameRequestBlockTimeout);
for (auto& kv : this->rtpStreams)
{
......@@ -468,13 +441,14 @@ namespace RTC
this->isFullFrameRequested = false;
}
void Producer::FillKnownHeaderExtensions()
void Producer::FillHeaderExtensionIds()
{
MS_TRACE();
auto& idMapping = this->rtpMapping.headerExtensionIds;
uint8_t ssrcAudioLevelId{ 0 };
uint8_t absSendTimeId{ 0 };
uint8_t ridId{ 0 };
for (auto& exten : this->rtpParameters.headerExtensions)
{
......@@ -487,7 +461,7 @@ namespace RTC
else
ssrcAudioLevelId = exten.id;
this->knownHeaderExtensions.ssrcAudioLevelId = ssrcAudioLevelId;
this->headerExtensionIds.ssrcAudioLevel = ssrcAudioLevelId;
}
if ((absSendTimeId == 0u) && exten.type == RTC::RtpHeaderExtensionUri::Type::ABS_SEND_TIME)
......@@ -497,7 +471,17 @@ namespace RTC
else
absSendTimeId = exten.id;
this->knownHeaderExtensions.absSendTimeId = absSendTimeId;
this->headerExtensionIds.absSendTime = absSendTimeId;
}
if ((ridId == 0u) && exten.type == RTC::RtpHeaderExtensionUri::Type::RTP_STREAM_ID)
{
if (idMapping.find(exten.id) != idMapping.end())
ridId = idMapping[exten.id];
else
ridId = exten.id;
this->headerExtensionIds.rid = ridId;
}
}
}
......@@ -506,18 +490,9 @@ namespace RTC
{
MS_TRACE();
// Don't create an RtpStreamRecv if the encoding has no SSRC.
// TODO: For simulcast or, if not announced, this would be done
// dynamicall by the RtpListener when matching a RID with its SSRC.
if (encoding.ssrc == 0u)
return;
uint32_t ssrc = encoding.ssrc;
// Don't create a RtpStreamRecv if there is already one for the same SSRC.
// TODO: This may not work for SVC codecs.
if (this->rtpStreams.find(ssrc) != this->rtpStreams.end())
return;
MS_ASSERT(this->rtpStreams.find(ssrc) == this->rtpStreams.end(), "stream already exists");
// Get the codec of the stream/encoding.
auto& codec = this->rtpParameters.GetCodecForEncoding(encoding);
......@@ -558,7 +533,9 @@ namespace RTC
params.usePli = usePli;
// Create a RtpStreamRecv for receiving a media stream.
this->rtpStreams[ssrc] = new RTC::RtpStreamRecv(this, params);
auto* rtpStream = new RTC::RtpStreamRecv(this, params);
this->rtpStreams[ssrc] = rtpStream;
// Enable REMB in the transport if requested.
if (useRemb)
......@@ -576,6 +553,60 @@ namespace RTC
rtpStream->SetRtx(codec.payloadType, encoding.rtx.ssrc);
this->mapRtxStreams[encoding.rtx.ssrc] = rtpStream;
}
// Enter the stream into the profiles map.
// NOTE: This is specific to simulcast with no temporal layers.
auto profile = encoding.profile;
this->profiles[rtpStream].insert(profile);
// Don't announce default profile, but just those for simulcast/SVC.
if (profile != RTC::RtpEncodingParameters::Profile::DEFAULT)
{
for (auto& listener : this->listeners)
{
listener->OnProducerProfileEnabled(this, profile);
}
}
}
void Producer::ClearRtpStream(RTC::RtpStreamRecv* rtpStream)
{
MS_TRACE();
auto& profiles = this->profiles[rtpStream];
// Notify about the profiles being disabled.
for (auto& profile : profiles)
{
// Don't announce default profile, but just those for simulcast/SVC.
if (profile == RTC::RtpEncodingParameters::Profile::DEFAULT)
break;
for (auto& listener : this->listeners)
{
listener->OnProducerProfileDisabled(this, profile);
}
}
this->rtpStreams.erase(rtpStream->GetSsrc());
for (auto& kv : this->mapRtxStreams)
{
auto rtxSsrc = kv.first;
auto* mediaStream = kv.second;
if (mediaStream == rtpStream)
{
this->mapRtxStreams.erase(rtxSsrc);
break;
}
}
this->profiles.erase(rtpStream);
delete rtpStream;
}
void Producer::ClearRtpStreams()
......@@ -589,10 +620,30 @@ namespace RTC
delete rtpStream;
}
// Notify about all profiles being disabled.
for (auto& kv : this->profiles)
{
auto& profiles = kv.second;
for (auto profile : profiles)
{
// Don't announce default profile, but just those for simulcast/SVC.
if (profile == RTC::RtpEncodingParameters::Profile::DEFAULT)
break;
for (auto& listener : this->listeners)
{
listener->OnProducerProfileDisabled(this, profile);
}
}
}
this->rtpStreams.clear();
this->mapRtxStreams.clear();
this->profiles.clear();
}
void Producer::ApplyPayloadTypeMapping(RTC::RtpPacket* packet) const
void Producer::ApplyRtpMapping(RTC::RtpPacket* packet) const
{
MS_TRACE();
......@@ -603,16 +654,43 @@ namespace RTC
{
packet->SetPayloadType(codecPayloadTypeMap.at(payloadType));
}
auto& headerExtensionIdMap = this->rtpMapping.headerExtensionIds;
packet->MangleExtensionHeaderIds(headerExtensionIdMap);
if (this->headerExtensionIds.ssrcAudioLevel != 0u)
{
packet->AddExtensionMapping(
RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL, this->headerExtensionIds.ssrcAudioLevel);
}
if (this->headerExtensionIds.absSendTime != 0u)
{
packet->AddExtensionMapping(
RtpHeaderExtensionUri::Type::ABS_SEND_TIME, this->headerExtensionIds.absSendTime);
}
if (this->headerExtensionIds.rid != 0u)
{
packet->AddExtensionMapping(
RtpHeaderExtensionUri::Type::RTP_STREAM_ID, this->headerExtensionIds.rid);
}
}
void Producer::ApplySsrcMapping(RTC::RtpPacket* packet) const
RTC::RtpEncodingParameters::Profile Producer::GetProfile(
RTC::RtpStreamRecv* rtpStream, RTC::RtpPacket* packet)
{
MS_TRACE();
// The stream is already mapped to a profile.
if (this->profiles.find(rtpStream) != this->profiles.end())
{
auto it = this->profiles[rtpStream].begin();
auto profile = *it;
auto ssrc = packet->GetSsrc();
return profile;
}
if (this->ssrcMapping.find(ssrc) != this->ssrcMapping.end())
packet->SetSsrc(this->ssrcMapping.at(ssrc));
MS_THROW_ERROR("unknown RTP packet received [ssrc:%" PRIu32 "]", packet->GetSsrc());
}
void Producer::OnRtpStreamRecvNackRequired(
......@@ -679,6 +757,47 @@ namespace RTC
this->transport->SendRtcpPacket(&packet);
}
void Producer::OnRtpStreamHealthReport(RTC::RtpStream* rtpStream, bool healthy)
{
MS_TRACE();
auto rtpStreamRecv = static_cast<RtpStreamRecv*>(rtpStream);
MS_ASSERT(
this->profiles.find(rtpStreamRecv) != this->profiles.end(),
"stream not present in profiles map");
auto& profiles = this->profiles[rtpStreamRecv];
// The stream has transitioned to non healthy.
if (rtpStream->IsHealthy() && !healthy)
{
MS_DEBUG_TAG(rtp, "stream is now unhealthy [ssrc:%" PRIu32 "]", rtpStream->GetSsrc());
// Completely destroy the stream.
ClearRtpStream(rtpStreamRecv);
}
// The stream has transitioned to healthy.
if (!rtpStream->IsHealthy() && healthy)
{
MS_DEBUG_TAG(rtp, "stream is now healthy [ssrc:%" PRIu32 "]", rtpStream->GetSsrc());
// Notify about the profiles being disabled.
for (auto& profile : profiles)
{
// Don't announce default profile, but just those for simulcast/SVC.
if (profile == RTC::RtpEncodingParameters::Profile::DEFAULT)
break;
for (auto& listener : this->listeners)
{
listener->OnProducerProfileEnabled(this, profile);
}
}
}
}
inline void Producer::OnTimer(Timer* timer)
{
MS_TRACE();
......
......@@ -454,6 +454,16 @@ namespace RTC
// Add us as listener.
consumer->AddListener(this);
auto profiles = producer->GetProfiles();
std::set<RtpEncodingParameters::Profile>::reverse_iterator it;
for (it = profiles.rbegin(); it != profiles.rend(); ++it)
{
auto profile = *it;
consumer->AddProfile(profile);
}
// Insert into the maps.
this->consumers[consumerId] = consumer;
this->mapProducerConsumers[producer].insert(consumer);
......@@ -988,6 +998,9 @@ namespace RTC
{
// NOTE: This may throw.
rtpParameters = RTC::RtpParameters(request->data[JsonStringRtpParameters]);
// NOTE: This may throw.
consumer->Enable(transport, rtpParameters);
}
catch (const MediaSoupError& error)
{
......@@ -996,8 +1009,6 @@ namespace RTC
return;
}
consumer->Enable(transport, rtpParameters);
// Tell the Transport to handle the new Consumer.
transport->HandleConsumer(consumer);
......@@ -1070,6 +1081,56 @@ namespace RTC
break;
}
case Channel::Request::MethodId::CONSUMER_SET_PREFERRED_PROFILE:
{
static const Json::StaticString JsonStringProfile{ "profile" };
RTC::Consumer* consumer;
try
{
consumer = GetConsumerFromRequest(request);
}
catch (const MediaSoupError& error)
{
request->Reject(error.what());
return;
}
if (!request->data[JsonStringProfile].isString())
{
request->Reject("missing data.profile");
return;
}
std::string profileStr = request->data[JsonStringProfile].asString();
auto it = RTC::RtpEncodingParameters::string2Profile.find(profileStr);
if (it == RTC::RtpEncodingParameters::string2Profile.end())
{
request->Reject("unknown profile");
return;
}
auto profile = it->second;
if (profile == RTC::RtpEncodingParameters::Profile::NONE || profile == RTC::RtpEncodingParameters::Profile::DEFAULT)
{
request->Reject("invalid profile");
return;
}
consumer->SetPreferredProfile(profile);
request->Accept();
break;
}
default:
{
MS_ERROR("unknown method");
......@@ -1328,7 +1389,8 @@ namespace RTC
}
}
void Router::OnProducerRtpPacket(RTC::Producer* producer, RTC::RtpPacket* packet)
void Router::OnProducerRtpPacket(
RTC::Producer* producer, RTC::RtpPacket* packet, RTC::RtpEncodingParameters::Profile profile)
{
MS_TRACE();
......@@ -1343,7 +1405,7 @@ namespace RTC
for (auto* consumer : consumers)
{
if (consumer->IsEnabled())
consumer->SendRtpPacket(packet);
consumer->SendRtpPacket(packet, profile);
}
// Update audio levels.
......@@ -1363,6 +1425,40 @@ namespace RTC
}
}
void Router::OnProducerProfileEnabled(
RTC::Producer* producer, RTC::RtpEncodingParameters::Profile profile)
{
MS_TRACE();
MS_ASSERT(
this->mapProducerConsumers.find(producer) != this->mapProducerConsumers.end(),
"Producer not present in mapProducerConsumers");
auto& consumers = this->mapProducerConsumers[producer];
for (auto* consumer : consumers)
{
consumer->AddProfile(profile);
}
}
void Router::OnProducerProfileDisabled(
RTC::Producer* producer, RTC::RtpEncodingParameters::Profile profile)
{
MS_TRACE();
MS_ASSERT(
this->mapProducerConsumers.find(producer) != this->mapProducerConsumers.end(),
"Producer not present in mapProducerConsumers");
auto& consumers = this->mapProducerConsumers[producer];
for (auto* consumer : consumers)
{
consumer->RemoveProfile(profile);
}
}
void Router::OnConsumerClosed(RTC::Consumer* consumer)
{
MS_TRACE();
......
......@@ -7,6 +7,28 @@
namespace RTC
{
/* Class static data. */
// clang-format off
std::map<std::string, RTC::RtpEncodingParameters::Profile> RTC::RtpEncodingParameters::string2Profile =
{
{ "none", RTC::RtpEncodingParameters::Profile::NONE },
{ "default", RTC::RtpEncodingParameters::Profile::DEFAULT },
{ "low", RTC::RtpEncodingParameters::Profile::LOW },
{ "medium", RTC::RtpEncodingParameters::Profile::MEDIUM },
{ "high", RTC::RtpEncodingParameters::Profile::HIGH }
};
std::map<RTC::RtpEncodingParameters::Profile, std::string> RTC::RtpEncodingParameters::profile2String =
{
{ RTC::RtpEncodingParameters::Profile::NONE, "none" },
{ RTC::RtpEncodingParameters::Profile::DEFAULT, "default" },
{ RTC::RtpEncodingParameters::Profile::LOW, "low" },
{ RTC::RtpEncodingParameters::Profile::MEDIUM, "medium" },
{ RTC::RtpEncodingParameters::Profile::HIGH, "high" }
};
// clang-format on
/* Instance methods. */
RtpEncodingParameters::RtpEncodingParameters(Json::Value& data)
......@@ -23,6 +45,7 @@ namespace RTC
static const Json::StaticString JsonStringActive{ "active" };
static const Json::StaticString JsonStringEncodingId{ "encodingId" };
static const Json::StaticString JsonStringDependencyEncodingIds{ "dependencyEncodingIds" };
static const Json::StaticString JsonStringProfile{ "profile" };
if (!data.isObject())
MS_THROW_ERROR("RtpEncodingParameters is not an object");
......@@ -84,6 +107,24 @@ namespace RTC
this->dependencyEncodingIds.push_back(entry.asString());
}
}
// profile is optional.
if (data[JsonStringProfile].isString())
{
std::string profileStr = data[JsonStringProfile].asString();
if (string2Profile.find(profileStr) == string2Profile.end())
MS_THROW_ERROR("unknown profile");
this->profile = string2Profile[profileStr];
if (
this->profile == RTC::RtpEncodingParameters::Profile::NONE ||
this->profile == RTC::RtpEncodingParameters::Profile::DEFAULT)
{
MS_THROW_ERROR("invalid profile");
}
}
}
Json::Value RtpEncodingParameters::ToJson() const
......@@ -100,6 +141,7 @@ namespace RTC
static const Json::StaticString JsonStringActive{ "active" };
static const Json::StaticString JsonStringEncodingId{ "encodingId" };
static const Json::StaticString JsonStringDependencyEncodingIds{ "dependencyEncodingIds" };
static const Json::StaticString JsonStringProfile{ "profile" };
Json::Value json(Json::objectValue);
......@@ -149,6 +191,8 @@ namespace RTC
}
}
json[JsonStringProfile] = RtpEncodingParameters::profile2String[this->profile];
return json;
}
} // namespace RTC
......@@ -4,6 +4,7 @@
#include "Logger.hpp"
#include "MediaSoupError.hpp"
#include "RTC/RtpDictionaries.hpp"
#include <set>
#include <unordered_set>
namespace RTC
......@@ -297,5 +298,17 @@ namespace RTC
MS_THROW_ERROR("unknown encoding.codecPayloadType");
}
}
// Iterate all the encodings and ensure that profile is not repeated.
std::set<RTC::RtpEncodingParameters::Profile> profiles;
for (auto& encoding : this->encodings)
{
auto profile = encoding.profile;
auto pair = profiles.insert(profile);
if (!pair.second)
MS_THROW_ERROR("duplicated encoding.profile");
}
}
} // namespace RTC
......@@ -16,12 +16,10 @@ namespace RTC
static const Json::StaticString JsonStringSsrcTable{ "ssrcTable" };
static const Json::StaticString JsonStringMuxIdTable{ "muxIdTable" };
static const Json::StaticString JsonStringPtTable{ "ptTable" };
Json::Value json(Json::objectValue);
Json::Value jsonSsrcTable(Json::objectValue);
Json::Value jsonMuxIdTable(Json::objectValue);
Json::Value jsonPtTable(Json::objectValue);
// Add ssrcTable.
for (auto& kv : this->ssrcTable)
......@@ -43,16 +41,6 @@ namespace RTC
}
json[JsonStringMuxIdTable] = jsonMuxIdTable;
// Add ptTable.
for (auto& kv : this->ptTable)
{
auto payloadType = kv.first;
auto producer = kv.second;
jsonPtTable[std::to_string(payloadType)] = std::to_string(producer->producerId);
}
json[JsonStringPtTable] = jsonPtTable;
return json;
}
......@@ -66,7 +54,6 @@ namespace RTC
std::vector<uint32_t> previousSsrcs;
std::string previousMuxId;
std::vector<uint8_t> previousPayloadTypes;
for (auto& kv : this->ssrcTable)
{
......@@ -85,19 +72,11 @@ namespace RTC
if (existingProducer == producer)
{
previousMuxId = muxId;
break;
}
}
for (auto& kv : this->ptTable)
{
auto payloadType = kv.first;
auto& existingProducer = kv.second;
if (existingProducer == producer)
previousPayloadTypes.push_back(payloadType);
}
// First remove from the listener tables all the entries pointing to
// the given Producer.
RemoveProducer(producer);
......@@ -121,7 +100,7 @@ namespace RTC
else
{
RemoveProducer(producer);
RollbackProducer(producer, previousSsrcs, previousMuxId, previousPayloadTypes);
RollbackProducer(producer, previousSsrcs, previousMuxId);
MS_THROW_ERROR("ssrc already exists in RTP listener [ssrc:%" PRIu32 "]", ssrc);
}
......@@ -140,7 +119,7 @@ namespace RTC
else
{
RemoveProducer(producer);
RollbackProducer(producer, previousSsrcs, previousMuxId, previousPayloadTypes);
RollbackProducer(producer, previousSsrcs, previousMuxId);
MS_THROW_ERROR("ssrc already exists in RTP listener [ssrc:%" PRIu32 "]", ssrc);
}
......@@ -159,7 +138,7 @@ namespace RTC
else
{
RemoveProducer(producer);
RollbackProducer(producer, previousSsrcs, previousMuxId, previousPayloadTypes);
RollbackProducer(producer, previousSsrcs, previousMuxId);
MS_THROW_ERROR("ssrc already exists in RTP listener [ssrc:%" PRIu32 "]", ssrc);
}
......@@ -180,53 +159,12 @@ namespace RTC
else
{
RemoveProducer(producer);
RollbackProducer(producer, previousSsrcs, previousMuxId, previousPayloadTypes);
RollbackProducer(producer, previousSsrcs, previousMuxId);
MS_THROW_ERROR("muxId already exists in RTP listener [muxId:'%s']", muxId.c_str());
}
}
}
// Add entries into ptTable just if:
// - Not all the encoding.ssrc are given, or
// - Not all the encoding.rtx.ssrc are given, or
// - Not all the encoding.fec.ssrc are given.
{
auto it = rtpParameters.encodings.begin();
for (; it != rtpParameters.encodings.end(); ++it)
{
auto& encoding = *it;
if (
(encoding.ssrc == 0u) || (encoding.hasRtx && (encoding.rtx.ssrc == 0u)) ||
(encoding.hasFec && (encoding.fec.ssrc == 0u)))
{
break;
}
}
if (it != rtpParameters.encodings.end())
{
for (auto& codec : rtpParameters.codecs)
{
uint8_t payloadType = codec.payloadType;
if (!this->HasPayloadType(payloadType, producer))
{
this->ptTable[payloadType] = producer;
}
else
{
RemoveProducer(producer);
RollbackProducer(producer, previousSsrcs, previousMuxId, previousPayloadTypes);
MS_THROW_ERROR(
"payloadType already exists in RTP listener [payloadType:%" PRIu8 "]", payloadType);
}
}
}
}
}
void RtpListener::RemoveProducer(const RTC::Producer* producer)
......@@ -251,14 +189,6 @@ namespace RTC
else
++it;
}
for (auto it = this->ptTable.begin(); it != this->ptTable.end();)
{
if (it->second == producer)
it = this->ptTable.erase(it);
else
++it;
}
}
RTC::Producer* RtpListener::GetProducer(RTC::RtpPacket* packet)
......@@ -295,21 +225,6 @@ namespace RTC
// Otherwise lookup into the muxId table.
// TODO: do it.
// Otherwise lookup into the PT table.
{
auto it = this->ptTable.find(packet->GetPayloadType());
if (it != this->ptTable.end())
{
auto producer = it->second;
// Update SSRC table.
this->ssrcTable[packet->GetSsrc()] = producer;
return producer;
}
}
// TODO: We may emit "unhandledrtp" event.
return nullptr;
}
......@@ -322,18 +237,13 @@ namespace RTC
auto it = this->ssrcTable.find(ssrc);
if (it != this->ssrcTable.end())
{
return it->second;
}
return nullptr;
}
void RtpListener::RollbackProducer(
RTC::Producer* producer,
std::vector<uint32_t>& previousSsrcs,
std::string& previousMuxId,
std::vector<uint8_t>& previousPayloadTypes)
RTC::Producer* producer, std::vector<uint32_t>& previousSsrcs, std::string& previousMuxId)
{
MS_TRACE();
......@@ -344,10 +254,5 @@ namespace RTC
if (!previousMuxId.empty())
this->muxIdTable[previousMuxId] = producer;
for (auto payloadType : previousPayloadTypes)
{
this->ptTable[payloadType] = producer;
}
}
} // namespace RTC
......@@ -364,6 +364,9 @@ namespace RTC
auto packet = new RtpPacket(
header, extensionHeader, payload, this->payloadLength, this->payloadPadding, this->size);
// Clone seq32.
packet->seq32 = this->seq32;
// Parse RFC 5285 extension header.
packet->ParseExtensions();
......
......@@ -10,21 +10,30 @@ namespace RTC
{
/* Static. */
static constexpr uint32_t MinSequential{ 0 };
static constexpr uint16_t MaxDropout{ 3000 };
static constexpr uint16_t MaxMisorder{ 100 };
static constexpr uint16_t MaxMisorder{ 300 };
static constexpr uint32_t RtpSeqMod{ 1 << 16 };
static constexpr uint16_t HealthCheckPeriod{ 1000 };
/* Instance methods. */
RtpStream::RtpStream(RTC::RtpStream::Params& params) : params(params)
{
MS_TRACE();
// Set the health check timer.
this->healthCheckTimer = new Timer(this);
// Run the timer.
this->healthCheckTimer->Start(HealthCheckPeriod, HealthCheckPeriod);
}
RtpStream::~RtpStream()
{
MS_TRACE();
// Close the health check timer.
this->healthCheckTimer->Destroy();
}
bool RtpStream::ReceivePacket(RTC::RtpPacket* packet)
......@@ -38,22 +47,18 @@ namespace RTC
{
InitSeq(seq);
this->started = true;
this->maxSeq = seq - 1;
this->probation = MinSequential;
this->started = true;
this->maxSeq = seq - 1;
}
// If not a valid packet ignore it.
if (!UpdateSeq(packet))
{
if (this->probation == 0u)
{
MS_WARN_TAG(
rtp,
"invalid packet [ssrc:%" PRIu32 ", seq:%" PRIu16 "]",
packet->GetSsrc(),
packet->GetSequenceNumber());
}
MS_WARN_TAG(
rtp,
"invalid packet [ssrc:%" PRIu32 ", seq:%" PRIu16 "]",
packet->GetSsrc(),
packet->GetSequenceNumber());
return false;
}
......@@ -93,35 +98,10 @@ namespace RTC
uint16_t seq = packet->GetSequenceNumber();
uint16_t udelta = seq - this->maxSeq;
/*
* Source is not valid until MinSequential packets with
* sequential sequence numbers have been received.
*/
if (this->probation != 0u)
{
// Packet is in sequence.
if (seq == this->maxSeq + 1)
{
this->probation--;
this->maxSeq = seq;
if (this->probation == 0)
{
InitSeq(seq);
this->received++;
return true;
}
}
else
{
this->probation = MinSequential - 1;
this->maxSeq = seq;
}
return false;
}
// If the new packet sequence number is greater than the max seen but not
// "so much bigger", accept it.
// NOTE: udelta also handles the case of a new cycle, this is:
// maxSeq:65536, seq:0 => udelta:1
if (udelta < MaxDropout)
{
// In order, with permissible gap.
......@@ -133,16 +113,16 @@ namespace RTC
this->maxSeq = seq;
}
// Too old packet received (older than the allowed misorder).
// Or to new packet (more than acceptable dropout).
else if (udelta <= RtpSeqMod - MaxMisorder)
{
// The sequence number made a very large jump.
// The sequence number made a very large jump. If two sequential packets
// arrive, accept the latter.
if (seq == this->badSeq)
{
/*
* Two sequential packets -- assume that the other side
* restarted without telling us so just re-sync
* (i.e., pretend this was the first packet).
*/
// Two sequential packets. Assume that the other side restarted without
// telling us so just re-sync (i.e., pretend this was the first packet).
MS_WARN_TAG(
rtp,
"too bad sequence number, re-syncing RTP [ssrc:%" PRIu32 ", seq:%" PRIu16 "]",
......@@ -164,6 +144,11 @@ namespace RTC
return false;
}
}
// Acceptable misorder.
else
{
// Do nothing.
}
this->received++;
......@@ -192,4 +177,14 @@ namespace RTC
return json;
}
void RtpStream::OnTimer(Timer* timer)
{
MS_TRACE();
if (timer == this->healthCheckTimer)
{
this->CheckHealth();
}
}
} // namespace RTC
......@@ -7,6 +7,10 @@
namespace RTC
{
/* Static. */
static constexpr uint32_t RtpSeqMod{ 1 << 16 };
/* Instance methods. */
RtpStreamRecv::RtpStreamRecv(Listener* listener, RTC::RtpStream::Params& params)
......@@ -23,7 +27,7 @@ namespace RTC
MS_TRACE();
}
Json::Value RtpStreamRecv::ToJson() const
Json::Value RtpStreamRecv::ToJson()
{
MS_TRACE();
......@@ -32,6 +36,7 @@ namespace RTC
static const Json::StaticString JsonStringMaxTimestamp{ "maxTimestamp" };
static const Json::StaticString JsonStringTransit{ "transit" };
static const Json::StaticString JsonStringJitter{ "jitter" };
static const Json::StaticString JsonStringBitRate{ "bitrate" };
Json::Value json(Json::objectValue);
......@@ -40,6 +45,7 @@ namespace RTC
json[JsonStringMaxTimestamp] = Json::UInt{ this->maxTimestamp };
json[JsonStringTransit] = Json::UInt{ this->transit };
json[JsonStringJitter] = Json::UInt{ this->jitter };
json[JsonStringBitRate] = Json::UInt{ GetBitRate() };
return json;
}
......@@ -51,11 +57,13 @@ namespace RTC
// Call the parent method.
if (!RtpStream::ReceivePacket(packet))
{
MS_DEBUG_TAG(rtp, "packet discarded");
MS_WARN_TAG(rtp, "packet discarded");
return false;
}
this->receivedCounter.Update(packet);
// Calculate Jitter.
CalculateJitter(packet->GetTimestamp());
......@@ -129,6 +137,25 @@ namespace RTC
packet->SetExtendedSequenceNumber(
this->cycles + static_cast<uint32_t>(packet->GetSequenceNumber()));
// Set the extended sequence number into the packet.
// Ensure that the NACKed packet sequence is not higher than the one of
// the media stream.
//
// We are in the same cycle.
if (packet->GetSequenceNumber() <= this->maxSeq)
{
packet->SetExtendedSequenceNumber(
this->cycles + static_cast<uint32_t>(packet->GetSequenceNumber()));
}
// The nacket packet belongs to the previous cycle.
else
{
MS_DEBUG_TAG(rtx, "nacked packet belongs to previous seq cycle");
packet->SetExtendedSequenceNumber(
this->cycles - RtpSeqMod + static_cast<uint32_t>(packet->GetSequenceNumber()));
}
// Pass the packet to the NackGenerator.
if (this->params.useNack)
this->nackGenerator->ReceivePacket(packet);
......@@ -214,6 +241,13 @@ namespace RTC
}
}
uint32_t RtpStreamRecv::GetBitRate()
{
uint64_t now = DepLibUV::GetTime();
return this->receivedCounter.GetRate(now);
}
void RtpStreamRecv::CalculateJitter(uint32_t rtpTimestamp)
{
MS_TRACE();
......@@ -236,13 +270,26 @@ namespace RTC
// Do nothing.
}
void RtpStreamRecv::CheckHealth()
{
auto now = DepLibUV::GetTime();
bool healthy = true;
if (this->receivedCounter.GetRate(now) == 0)
healthy = false;
// NOTE: Update the 'healthy' value after notification.
this->listener->OnRtpStreamHealthReport(this, healthy);
this->healthy = healthy;
}
void RtpStreamRecv::OnNackGeneratorNackRequired(const std::vector<uint16_t>& seqNumbers)
{
MS_TRACE();
MS_ASSERT(this->params.useNack, "NACK required but not supported");
MS_WARN_TAG(
MS_DEBUG_TAG(
rtx,
"triggering NACK [ssrc:%" PRIu32 ", first seq:%" PRIu16 ", num packets:%zu]",
this->params.ssrc,
......
......@@ -28,10 +28,10 @@ namespace RTC
MS_TRACE();
// Clear the RTP buffer.
ClearBuffer();
ClearRetransmissionBuffer();
}
Json::Value RtpStreamSend::ToJson() const
Json::Value RtpStreamSend::ToJson()
{
MS_TRACE();
......@@ -59,7 +59,7 @@ namespace RTC
// Call the parent method.
if (!RtpStream::ReceivePacket(packet))
{
MS_DEBUG_TAG(rtp, "packet discarded");
MS_WARN_TAG(rtp, "packet discarded");
return false;
}
......@@ -137,6 +137,7 @@ namespace RTC
auto bufferItReverse = this->buffer.rbegin();
uint32_t bufferFirstSeq32 = (*bufferIt).seq32;
uint32_t bufferLastSeq32 = (*bufferItReverse).seq32;
bool inRange = true;
// Requested packet range not found.
if (firstSeq32 > bufferLastSeq32 || lastSeq32 < bufferFirstSeq32)
......@@ -150,20 +151,32 @@ namespace RTC
// Try again.
if (firstSeq32 > bufferLastSeq32 || lastSeq32 < bufferFirstSeq32)
{
MS_WARN_TAG(rtx, "requested packet range not in the buffer");
return;
firstSeq32 += RtpSeqMod;
lastSeq32 += RtpSeqMod;
inRange = false;
}
}
// Otherwise just return.
else
{
MS_WARN_TAG(rtx, "requested packet range not in the buffer");
return;
inRange = false;
}
}
if (!inRange)
{
MS_WARN_TAG(
rtx,
"requested packet range not in the buffer [seq:%" PRIu16 ", seq32:%" PRIu32
", bufferFirstSeq32:%" PRIu32 ", bufferLastSeq32:%" PRIu32 "]",
seq,
firstSeq32,
bufferFirstSeq32,
bufferLastSeq32);
return;
}
// Look for each requested packet.
uint64_t now = DepLibUV::GetTime();
uint32_t rtt = (this->rtt != 0u ? this->rtt : DefaultRtt);
......@@ -316,24 +329,7 @@ namespace RTC
return report;
}
void RtpStreamSend::Reset()
{
MS_TRACE();
// By setting started to 0, on next packet the RtpStream will call
// InitSeq(seq).
this->started = false;
// Also reset RtpStreamSend own members.
this->receivedBytes = 0;
this->lastPacketTimeMs = 0;
this->lastPacketRtpTimestamp = 0;
// Clear the buffer.
ClearBuffer();
}
void RtpStreamSend::ClearBuffer()
void RtpStreamSend::ClearRetransmissionBuffer()
{
MS_TRACE();
......@@ -364,7 +360,7 @@ namespace RTC
}
// Sum the packet seq number and the number of 16 bits cycles.
uint32_t packetSeq32 = uint32_t{ packet->GetSequenceNumber() } + this->cycles;
uint32_t packetSeq32 = packet->GetExtendedSequenceNumber();
BufferItem bufferItem;
bufferItem.seq32 = packetSeq32;
......@@ -444,7 +440,12 @@ namespace RTC
MS_TRACE();
// Clear the RTP buffer.
ClearBuffer();
ClearRetransmissionBuffer();
}
void RtpStreamSend::CheckHealth()
{
MS_TRACE();
}
void RtpStreamSend::SetRtx(uint8_t payloadType, uint32_t ssrc)
......
......@@ -412,12 +412,13 @@ namespace RTC
{
MS_TRACE();
// Add to the map.
this->producers.insert(producer);
// Pass it to the RtpListener.
// NOTE: This may throw.
this->rtpListener.AddProducer(producer);
// Add to the map.
this->producers.insert(producer);
// Add us as listener.
producer->AddListener(this);
}
......@@ -771,7 +772,7 @@ namespace RTC
{
MS_WARN_TAG(
rtcp,
"no Consumer found for received NACK Feedback packet "
"no Consumer found for received Feedback packet "
"[sender ssrc:%" PRIu32 ", media ssrc:%" PRIu32 "]",
feedback->GetMediaSsrc(),
feedback->GetMediaSsrc());
......@@ -1122,9 +1123,8 @@ namespace RTC
// Trick for clients performing aggressive ICE regardless we are ICE-Lite.
this->iceServer->ForceSelectedTuple(tuple);
// Apply the RTP header extension mapping into the packet (we need it for the
// bitrate estimator).
producer->ApplyExtensionIdMapping(packet);
// Pass the RTP packet to the corresponding Producer.
producer->ReceiveRtpPacket(packet);
// Feed the remote bitrate estimator (REMB).
if (this->remoteBitrateEstimator)
......@@ -1138,9 +1138,6 @@ namespace RTC
}
}
// Pass the RTP packet to the corresponding Producer.
producer->ReceiveRtpPacket(packet);
delete packet;
}
......@@ -1558,7 +1555,22 @@ namespace RTC
// Do nothing.
}
void Transport::OnProducerRtpPacket(RTC::Producer* /*producer*/, RTC::RtpPacket* /*packet*/)
void Transport::OnProducerRtpPacket(
RTC::Producer* /*producer*/,
RTC::RtpPacket* /*packet*/,
RTC::RtpEncodingParameters::Profile /*profile*/)
{
// Do nothing.
}
void Transport::OnProducerProfileEnabled(
RTC::Producer* /*producer*/, RTC::RtpEncodingParameters::Profile /*profile*/)
{
// Do nothing.
}
void Transport::OnProducerProfileDisabled(
RTC::Producer* /*producer*/, RTC::RtpEncodingParameters::Profile /*profile*/)
{
// Do nothing.
}
......
......@@ -259,6 +259,7 @@ void Worker::OnChannelRequest(Channel::UnixStreamSocket* /*channel*/, Channel::R
case Channel::Request::MethodId::CONSUMER_ENABLE:
case Channel::Request::MethodId::CONSUMER_PAUSE:
case Channel::Request::MethodId::CONSUMER_RESUME:
case Channel::Request::MethodId::CONSUMER_SET_PREFERRED_PROFILE:
{
RTC::Router* router;
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论