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

Add VP9 SVC support (#311)

上级 9672fbdb
# Changelog
### 3.0.13 (work in progress)
### 3.1.0 (work in progress)
* Add SVC support. It includes VP9 full SVC and VP9 K-SVC as implemented by libwebrtc.
* Prefer Python 2 (if available) over Python 3. This is because there are yet pending issues with gyp + Python 3.
......
......@@ -116,9 +116,16 @@ class Channel extends EnhancedEventEmitter
this._workerLogger.error(nsPayload.toString('utf8', 1));
break;
// 88 = 'X' (a dump log).
case 88:
// eslint-disable-next-line no-console
console.log(nsPayload.toString('utf8', 1));
break;
default:
this._workerLogger.error(
'unexpected data: %s', nsPayload.toString('utf8'));
// eslint-disable-next-line no-console
console.warn(
`worker[pid:${pid}] unexpected data: %s`, nsPayload.toString('utf8'));
}
}
catch (error)
......
const ScalabilityModeRegex = new RegExp('^[LS](\\d+)T(\\d+)');
const ScalabilityModeRegex =
new RegExp('^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})(_KEY)?');
exports.parse = function(scalabilityMode)
{
const match = ScalabilityModeRegex.exec(scalabilityMode);
if (!match)
return { spatialLayers: 1, temporalLayers: 1 };
{
return {
spatialLayers : 1,
temporalLayers : 1,
ksvc : false
};
}
return {
spatialLayers : Number(match[1]),
temporalLayers : Number(match[2])
temporalLayers : Number(match[2]),
ksvc : Boolean(match[3])
};
};
......@@ -588,7 +588,8 @@ test('consumer.dump() succeeds', async () =>
},
scalabilityMode : 'S4T1',
spatialLayers : 4,
temporalLayers : 1
temporalLayers : 1,
ksvc : false
}
]);
expect(data.consumableRtpEncodings).toBeType('array');
......
......@@ -599,7 +599,8 @@ test('producer.dump() succeeds', async () =>
rtx : { ssrc: 22222223 },
scalabilityMode : 'L1T3',
spatialLayers : 1,
temporalLayers : 3
temporalLayers : 3,
ksvc : false
},
{ codecPayloadType: 112, ssrc: 22222224, rtx: { ssrc: 22222225 } },
{ codecPayloadType: 112, ssrc: 22222226, rtx: { ssrc: 22222227 } },
......
......@@ -30,11 +30,35 @@ test('mediasoup.getSupportedRtpCapabilities() returns the mediasoup RTP capabili
expect(rtpCapabilities2).not.toEqual(rtpCapabilities);
}, 500);
test('mediasoup.parseScalabilityMode() works', () =>
test('parseScalabilityMode() works', () =>
{
expect(parseScalabilityMode('L1T3')).toEqual({ spatialLayers: 1, temporalLayers: 3 });
expect(parseScalabilityMode('L3T2_KEY')).toEqual({ spatialLayers: 3, temporalLayers: 2 });
expect(parseScalabilityMode('S2T3')).toEqual({ spatialLayers: 2, temporalLayers: 3 });
expect(parseScalabilityMode('foo')).toEqual({ spatialLayers: 1, temporalLayers: 1 });
expect(parseScalabilityMode(null)).toEqual({ spatialLayers: 1, temporalLayers: 1 });
expect(parseScalabilityMode('L1T3'))
.toEqual({ spatialLayers: 1, temporalLayers: 3, ksvc: false });
expect(parseScalabilityMode('L3T2_KEY'))
.toEqual({ spatialLayers: 3, temporalLayers: 2, ksvc: true });
expect(parseScalabilityMode('S2T3'))
.toEqual({ spatialLayers: 2, temporalLayers: 3, ksvc: false });
expect(parseScalabilityMode('foo'))
.toEqual({ spatialLayers: 1, temporalLayers: 1, ksvc: false });
expect(parseScalabilityMode(null))
.toEqual({ spatialLayers: 1, temporalLayers: 1, ksvc: false });
expect(parseScalabilityMode('S0T3'))
.toEqual({ spatialLayers: 1, temporalLayers: 1, ksvc: false });
expect(parseScalabilityMode('S1T0'))
.toEqual({ spatialLayers: 1, temporalLayers: 1, ksvc: false });
expect(parseScalabilityMode('L20T3'))
.toEqual({ spatialLayers: 20, temporalLayers: 3, ksvc: false });
expect(parseScalabilityMode('S200T3'))
.toEqual({ spatialLayers: 1, temporalLayers: 1, ksvc: false });
expect(parseScalabilityMode('L4T7_KEY_SHIFT'))
.toEqual({ spatialLayers: 4, temporalLayers: 7, ksvc: true });
}, 500);
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -50,6 +50,13 @@
* Example:
* MS_DEBUG_DEV("Producer closed [producerId:%" PRIu32 "]", producerId);
*
* MS_DUMP(...)
*
* Logs always. Useful for Dump() methods.
*
* Example:
* MS_DUMP("foo");
*
* MS_ERROR(...)
*
* Logs an error if the current log level is satisfied (or if the current
......@@ -306,6 +313,22 @@ public:
#define MS_WARN_DEV_STD(desc, ...) {}
#endif
#define MS_DUMP(desc, ...) \
do \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "X" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
} \
while (false)
#define MS_DUMP_STD(desc, ...) \
do \
{ \
std::fprintf(stdout, _MS_LOG_STR_DESC desc _MS_LOG_SEPARATOR_CHAR_STD, _MS_LOG_ARG, ##__VA_ARGS__); \
std::fflush(stdout); \
} \
while (false)
#define MS_ERROR(desc, ...) \
do \
{ \
......@@ -358,6 +381,8 @@ public:
#define MS_DEBUG_DEV MS_DEBUG_DEV_STD
#undef MS_WARN_DEV
#define MS_WARN_DEV MS_WARN_DEV_STD
#undef MS_DUMP
#define MS_DUMP MS_DUMP_STD
#undef MS_ERROR
#define MS_ERROR MS_ERROR_STD
#endif
......
......@@ -5,6 +5,7 @@
#include "RTC/Codecs/H264.hpp"
#include "RTC/Codecs/PayloadDescriptorHandler.hpp"
#include "RTC/Codecs/VP8.hpp"
#include "RTC/Codecs/VP9.hpp"
#include "RTC/RtpDictionaries.hpp"
#include "RTC/RtpPacket.hpp"
......@@ -14,26 +15,109 @@ namespace RTC
{
bool CanBeKeyFrame(const RTC::RtpCodecMimeType& mimeType);
void ProcessRtpPacket(RTC::RtpPacket* packet, const RTC::RtpCodecMimeType& mimeType);
EncodingContext* GetEncodingContext(const RTC::RtpCodecMimeType& mimeType);
bool IsValidTypeForCodec(RTC::RtpParameters::Type type, const RTC::RtpCodecMimeType& mimeType);
EncodingContext* GetEncodingContext(
const RTC::RtpCodecMimeType& mimeType, uint8_t spatialLayers, uint8_t temporalLayers);
/* Inline namespace methods. */
inline bool CanBeKeyFrame(const RTC::RtpCodecMimeType& mimeType)
{
if (mimeType.type != RTC::RtpCodecMimeType::Type::VIDEO)
return false;
switch (mimeType.type)
{
case RTC::RtpCodecMimeType::Type::VIDEO:
{
switch (mimeType.subtype)
{
case RTC::RtpCodecMimeType::Subtype::VP8:
case RTC::RtpCodecMimeType::Subtype::VP9:
case RTC::RtpCodecMimeType::Subtype::H264:
return true;
default:
return false;
}
}
switch (mimeType.subtype)
default:
{
return false;
}
}
}
inline bool IsValidTypeForCodec(RTC::RtpParameters::Type type, const RTC::RtpCodecMimeType& mimeType)
{
switch (type)
{
case RTC::RtpCodecMimeType::Subtype::VP8:
case RTC::RtpCodecMimeType::Subtype::H264:
case RTC::RtpParameters::Type::NONE:
{
return false;
}
case RTC::RtpParameters::Type::SIMPLE:
{
return true;
}
case RTC::RtpParameters::Type::SIMULCAST:
{
switch (mimeType.type)
{
case RTC::RtpCodecMimeType::Type::VIDEO:
{
switch (mimeType.subtype)
{
case RTC::RtpCodecMimeType::Subtype::VP8:
case RTC::RtpCodecMimeType::Subtype::H264:
return true;
default:
return false;
}
}
default:
{
return false;
}
}
}
case RTC::RtpParameters::Type::SVC:
{
switch (mimeType.type)
{
case RTC::RtpCodecMimeType::Type::VIDEO:
{
switch (mimeType.subtype)
{
case RTC::RtpCodecMimeType::Subtype::VP9:
return true;
default:
return false;
}
}
default:
{
return false;
}
}
}
case RTC::RtpParameters::Type::PIPE:
{
return true;
}
default:
{
return false;
}
}
}
inline EncodingContext* GetEncodingContext(const RTC::RtpCodecMimeType& mimeType)
inline EncodingContext* GetEncodingContext(
const RTC::RtpCodecMimeType& mimeType, RTC::Codecs::EncodingContext::Params& params)
{
switch (mimeType.type)
{
......@@ -42,9 +126,11 @@ namespace RTC
switch (mimeType.subtype)
{
case RTC::RtpCodecMimeType::Subtype::VP8:
return new RTC::Codecs::VP8::EncodingContext();
return new RTC::Codecs::VP8::EncodingContext(params);
case RTC::RtpCodecMimeType::Subtype::VP9:
return new RTC::Codecs::VP9::EncodingContext(params);
case RTC::RtpCodecMimeType::Subtype::H264:
return new RTC::Codecs::H264::EncodingContext();
return new RTC::Codecs::H264::EncodingContext(params);
default:
return nullptr;
}
......
......@@ -30,6 +30,7 @@ namespace RTC
uint8_t tl0picidx{ 0 }; // TL0PICIDX
// Parsed values.
bool hasLid{ false };
bool hasTid{ false };
bool hasTl0picidx{ false };
bool isKeyFrame{ false };
};
......@@ -46,6 +47,7 @@ namespace RTC
class EncodingContext : public RTC::Codecs::EncodingContext
{
public:
EncodingContext(RTC::Codecs::EncodingContext::Params& params);
~EncodingContext() = default;
/* Pure virtual methods inherited from RTC::Codecs::EncodingContext. */
......@@ -62,7 +64,7 @@ namespace RTC
public:
void Dump() const override;
bool Process(RTC::Codecs::EncodingContext* encodingContext, uint8_t* data) override;
bool Process(RTC::Codecs::EncodingContext* encodingContext, uint8_t* data, bool& marker) override;
void Restore(uint8_t* data) override;
uint8_t GetSpatialLayer() const override;
uint8_t GetTemporalLayer() const override;
......@@ -75,6 +77,11 @@ namespace RTC
/* Inline EncondingContext methods. */
inline H264::EncodingContext::EncodingContext(RTC::Codecs::EncodingContext::Params& params)
: RTC::Codecs::EncodingContext(params)
{
}
inline void H264::EncodingContext::SyncRequired()
{
}
......
......@@ -19,10 +19,21 @@ namespace RTC
class EncodingContext
{
public:
EncodingContext() = default;
struct Params
{
uint8_t spatialLayers{ 1u };
uint8_t temporalLayers{ 1u };
bool ksvc{ false };
};
public:
EncodingContext(RTC::Codecs::EncodingContext::Params& params);
virtual ~EncodingContext() = default;
public:
uint8_t GetSpatialLayers() const;
uint8_t GetTemporalLayers() const;
bool IsKSvc() const;
int16_t GetTargetSpatialLayer() const;
int16_t GetTargetTemporalLayer() const;
int16_t GetCurrentSpatialLayer() const;
......@@ -34,6 +45,7 @@ namespace RTC
virtual void SyncRequired() = 0;
private:
Params params;
int16_t targetSpatialLayer{ -1 };
int16_t targetTemporalLayer{ -1 };
int16_t currentSpatialLayer{ -1 };
......@@ -42,6 +54,26 @@ namespace RTC
/* Inline instance methods. */
inline EncodingContext::EncodingContext(RTC::Codecs::EncodingContext::Params& params)
: params(params)
{
}
inline uint8_t EncodingContext::GetSpatialLayers() const
{
return this->params.spatialLayers;
}
inline uint8_t EncodingContext::GetTemporalLayers() const
{
return this->params.temporalLayers;
}
inline bool EncodingContext::IsKSvc() const
{
return this->params.ksvc;
}
inline int16_t EncodingContext::GetTargetSpatialLayer() const
{
return this->targetSpatialLayer;
......@@ -88,12 +120,12 @@ namespace RTC
virtual ~PayloadDescriptorHandler() = default;
public:
virtual void Dump() const = 0;
virtual bool Process(RTC::Codecs::EncodingContext* context, uint8_t* data) = 0;
virtual void Restore(uint8_t* data) = 0;
virtual uint8_t GetSpatialLayer() const = 0;
virtual uint8_t GetTemporalLayer() const = 0;
virtual bool IsKeyFrame() const = 0;
virtual void Dump() const = 0;
virtual bool Process(RTC::Codecs::EncodingContext* context, uint8_t* data, bool& marker) = 0;
virtual void Restore(uint8_t* data) = 0;
virtual uint8_t GetSpatialLayer() const = 0;
virtual uint8_t GetTemporalLayer() const = 0;
virtual bool IsKeyFrame() const = 0;
};
} // namespace Codecs
} // namespace RTC
......
......@@ -11,7 +11,7 @@
*
Single octet PictureID (M = 0) Dual octet PictureID (M = 1)
=============================== ============================
============================== ============================
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
......@@ -83,6 +83,7 @@ namespace RTC
class EncodingContext : public RTC::Codecs::EncodingContext
{
public:
EncodingContext(RTC::Codecs::EncodingContext::Params& params);
~EncodingContext() = default;
/* Pure virtual methods inherited from RTC::Codecs::EncodingContext. */
......@@ -104,7 +105,7 @@ namespace RTC
public:
void Dump() const override;
bool Process(RTC::Codecs::EncodingContext* encodingContext, uint8_t* data) override;
bool Process(RTC::Codecs::EncodingContext* encodingContext, uint8_t* data, bool& marker) override;
void Restore(uint8_t* data) override;
uint8_t GetSpatialLayer() const override;
uint8_t GetTemporalLayer() const override;
......@@ -117,6 +118,11 @@ namespace RTC
/* Inline EncondingContext methods. */
inline VP8::EncodingContext::EncodingContext(RTC::Codecs::EncodingContext::Params& params)
: RTC::Codecs::EncodingContext(params)
{
}
inline void VP8::EncodingContext::SyncRequired()
{
this->syncRequired = true;
......
#ifndef MS_RTC_CODECS_VP9_HPP
#define MS_RTC_CODECS_VP9_HPP
#include "common.hpp"
#include "RTC/Codecs/PayloadDescriptorHandler.hpp"
#include "RTC/RtpPacket.hpp"
#include "RTC/SeqManager.hpp"
/* https://tools.ietf.org/html/draft-ietf-payload-vp9-06
* VP9 Payload Descriptor
*
Flexible mode (with the F bit below set to 1)
=============================================
0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
|I|P|L|F|B|E|V|-| (REQUIRED)
+-+-+-+-+-+-+-+-+
I: |M| PICTURE ID | (REQUIRED)
+-+-+-+-+-+-+-+-+
M: | EXTENDED PID | (RECOMMENDED)
+-+-+-+-+-+-+-+-+
L: | TID |U| SID |D| (CONDITIONALLY RECOMMENDED)
+-+-+-+-+-+-+-+-+ -\
P,F: | P_DIFF |N| (CONDITIONALLY REQUIRED) - up to 3 times
+-+-+-+-+-+-+-+-+ -/
V: | SS |
| .. |
+-+-+-+-+-+-+-+-+
Non-flexible mode (with the F bit below set to 0)
=================================================
0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
|I|P|L|F|B|E|V|-| (REQUIRED)
+-+-+-+-+-+-+-+-+
I: |M| PICTURE ID | (RECOMMENDED)
+-+-+-+-+-+-+-+-+
M: | EXTENDED PID | (RECOMMENDED)
+-+-+-+-+-+-+-+-+
L: | TID |U| SID |D| (CONDITIONALLY RECOMMENDED)
+-+-+-+-+-+-+-+-+
| TL0PICIDX | (CONDITIONALLY REQUIRED)
+-+-+-+-+-+-+-+-+
V: | SS |
| .. |
+-+-+-+-+-+-+-+-+
*/
namespace RTC
{
namespace Codecs
{
class VP9
{
public:
struct PayloadDescriptor : public RTC::Codecs::PayloadDescriptor
{
/* Pure virtual methods inherited from RTC::Codecs::PayloadDescriptor. */
~PayloadDescriptor() = default;
void Dump() const override;
// Header.
uint8_t i : 1; // I: Picture ID (PID) present.
uint8_t p : 1; // P: Inter-picture predicted layer frame.
uint8_t l : 1; // L: Layer indices present.
uint8_t f : 1; // F: Flexible mode.
uint8_t b : 1; // B: Start of a layer frame.
uint8_t e : 1; // E: End of a layer frame.
uint8_t v : 1; // V: Scalability structure (SS) data present.
// Extension fields.
uint16_t pictureId{ 0 };
uint8_t slIndex{ 0 };
uint8_t tlIndex{ 0 };
uint8_t tl0PictureIndex;
uint8_t switchingUpPoint : 1;
uint8_t interLayerDependency : 1;
// Parsed values.
bool isKeyFrame{ false };
bool hasPictureId{ false };
bool hasOneBytePictureId{ false };
bool hasTwoBytesPictureId{ false };
bool hasSlIndex{ false };
bool hasTl0PictureIndex{ false };
bool hasTlIndex{ false };
};
public:
static VP9::PayloadDescriptor* Parse(
const uint8_t* data,
size_t len,
RTC::RtpPacket::FrameMarking* frameMarking = nullptr,
uint8_t frameMarkingLen = 0);
static void ProcessRtpPacket(RTC::RtpPacket* packet);
public:
class EncodingContext : public RTC::Codecs::EncodingContext
{
public:
EncodingContext(RTC::Codecs::EncodingContext::Params& params);
~EncodingContext() = default;
/* Pure virtual methods inherited from RTC::Codecs::EncodingContext. */
public:
void SyncRequired() override;
public:
RTC::SeqManager<uint16_t> pictureIdManager;
bool syncRequired{ false };
};
class PayloadDescriptorHandler : public RTC::Codecs::PayloadDescriptorHandler
{
public:
explicit PayloadDescriptorHandler(PayloadDescriptor* payloadDescriptor);
~PayloadDescriptorHandler() = default;
public:
void Dump() const override;
bool Process(RTC::Codecs::EncodingContext* encodingContext, uint8_t* data, bool& marker) override;
void Restore(uint8_t* data) override;
uint8_t GetSpatialLayer() const override;
uint8_t GetTemporalLayer() const override;
bool IsKeyFrame() const override;
private:
std::unique_ptr<PayloadDescriptor> payloadDescriptor;
};
};
/* Inline EncondingContext methods. */
inline VP9::EncodingContext::EncodingContext(RTC::Codecs::EncodingContext::Params& params)
: RTC::Codecs::EncodingContext(params)
{
}
inline void VP9::EncodingContext::SyncRequired()
{
this->syncRequired = true;
}
/* Inline PayloadDescriptorHandler methods. */
inline void VP9::PayloadDescriptorHandler::Dump() const
{
this->payloadDescriptor->Dump();
}
inline uint8_t VP9::PayloadDescriptorHandler::GetSpatialLayer() const
{
return this->payloadDescriptor->hasSlIndex ? this->payloadDescriptor->slIndex : 0u;
}
inline uint8_t VP9::PayloadDescriptorHandler::GetTemporalLayer() const
{
return this->payloadDescriptor->hasTlIndex ? this->payloadDescriptor->tlIndex : 0u;
}
inline bool VP9::PayloadDescriptorHandler::IsKeyFrame() const
{
return this->payloadDescriptor->isKeyFrame;
}
} // namespace Codecs
} // namespace RTC
#endif
......@@ -211,6 +211,7 @@ namespace RTC
std::string scalabilityMode;
uint8_t spatialLayers{ 1 };
uint8_t temporalLayers{ 1 };
bool ksvc{ false };
};
class RtpHeaderExtensionParameters
......
......@@ -79,9 +79,10 @@ namespace RTC
uint32_t jitter{ 0 };
uint8_t firSeqNumber{ 0 };
uint32_t reportedPacketLost{ 0 };
bool inactive{ false }; // Stream is inactive.
std::unique_ptr<RTC::NackGenerator> nackGenerator;
Timer* inactivityCheckPeriodicTimer{ nullptr };
bool inactive{ false }; // Stream is inactive.
uint64_t lastPacketAt{ 0 }; // Time last valid packet arrived.
TransmissionCounter transmissionCounter;
};
......
......@@ -72,7 +72,6 @@ namespace RTC
std::unordered_map<uint32_t, int16_t> mapMappedSsrcSpatialLayer;
std::vector<RTC::RtpStreamSend*> rtpStreams;
std::vector<RTC::RtpStream*> producerRtpStreams; // Indexed by spatial layer.
bool keyFrameSupported{ false };
bool syncRequired{ false };
RTC::SeqManager<uint16_t> rtpSeqManager;
int16_t preferredSpatialLayer{ -1 };
......
#ifndef MS_RTC_SVC_CONSUMER_HPP
#define MS_RTC_SVC_CONSUMER_HPP
#include "RTC/Codecs/PayloadDescriptorHandler.hpp"
#include "RTC/Consumer.hpp"
#include "RTC/RtpStreamSend.hpp"
#include "RTC/SeqManager.hpp"
#include <map>
namespace RTC
{
class SvcConsumer : public RTC::Consumer, public RTC::RtpStreamSend::Listener
{
public:
SvcConsumer(const std::string& id, RTC::Consumer::Listener* listener, json& data);
~SvcConsumer() override;
public:
void FillJson(json& jsonObject) const override;
void FillJsonStats(json& jsonArray) const override;
void FillJsonScore(json& jsonObject) const override;
void HandleRequest(Channel::Request* request) override;
bool IsActive() const override;
void ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t mappedSsrc) override;
void ProducerRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override;
void ProducerRtcpSenderReport(RTC::RtpStream* rtpStream, bool first) override;
void SetExternallyManagedBitrate() override;
int16_t GetBitratePriority() const override;
uint32_t UseAvailableBitrate(uint32_t bitrate) override;
uint32_t IncreaseLayer(uint32_t bitrate) override;
void ApplyLayers() override;
void SendRtpPacket(RTC::RtpPacket* packet) override;
void SendProbationRtpPacket(uint16_t seq) override;
void GetRtcp(RTC::RTCP::CompoundPacket* packet, RTC::RtpStreamSend* rtpStream, uint64_t now) override;
std::vector<RTC::RtpStreamSend*> GetRtpStreams() override;
void NeedWorstRemoteFractionLost(uint32_t mappedSsrc, uint8_t& worstRemoteFractionLost) override;
void ReceiveNack(RTC::RTCP::FeedbackRtpNackPacket* nackPacket) override;
void ReceiveKeyFrameRequest(RTC::RTCP::FeedbackPs::MessageType messageType, uint32_t ssrc) override;
void ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report) override;
uint32_t GetTransmissionRate(uint64_t now) override;
private:
void UserOnTransportConnected() override;
void UserOnTransportDisconnected() override;
void UserOnPaused() override;
void UserOnResumed() override;
void CreateRtpStream();
void RequestKeyFrame();
void MayChangeLayers(bool force = false);
bool RecalculateTargetLayers(int16_t& newTargetSpatialLayer, int16_t& newTargetTemporalLayer) const;
void UpdateTargetLayers(int16_t newTargetSpatialLayer, int16_t newTargetTemporalLayer);
void EmitScore() const;
void EmitLayersChange() const;
/* Pure virtual methods inherited from RtpStreamSend::Listener. */
public:
void OnRtpStreamScore(RTC::RtpStream* rtpStream, uint8_t score, uint8_t previousScore) override;
void OnRtpStreamRetransmitRtpPacket(
RTC::RtpStreamSend* rtpStream, RTC::RtpPacket* packet, bool probation = false) override;
private:
// Allocated by this.
RTC::RtpStreamSend* rtpStream{ nullptr };
// Others.
std::vector<RTC::RtpStreamSend*> rtpStreams;
RTC::RtpStream* producerRtpStream{ nullptr };
bool syncRequired{ false };
RTC::SeqManager<uint16_t> rtpSeqManager;
int16_t preferredSpatialLayer{ -1 };
int16_t preferredTemporalLayer{ -1 };
int16_t provisionalTargetSpatialLayer{ -1 };
int16_t provisionalTargetTemporalLayer{ -1 };
std::unique_ptr<RTC::Codecs::EncodingContext> encodingContext;
bool externallyManagedBitrate{ false };
};
/* Inline methods. */
inline bool SvcConsumer::IsActive() const
{
return (RTC::Consumer::IsActive() && this->producerRtpStream);
}
inline std::vector<RTC::RtpStreamSend*> SvcConsumer::GetRtpStreams()
{
return this->rtpStreams;
}
} // namespace RTC
#endif
......@@ -54,6 +54,7 @@
'src/RTC/SimulcastConsumer.cpp',
'src/RTC/SrtpSession.cpp',
'src/RTC/StunMessage.cpp',
'src/RTC/SvcConsumer.cpp',
'src/RTC/TcpConnection.cpp',
'src/RTC/TcpServer.cpp',
'src/RTC/Transport.cpp',
......@@ -63,6 +64,7 @@
'src/RTC/Codecs/Codecs.cpp',
'src/RTC/Codecs/H264.cpp',
'src/RTC/Codecs/VP8.cpp',
'src/RTC/Codecs/VP9.cpp',
'src/RTC/RtpDictionaries/Media.cpp',
'src/RTC/RtpDictionaries/Parameters.cpp',
'src/RTC/RtpDictionaries/RtcpFeedback.cpp',
......@@ -152,6 +154,7 @@
'include/RTC/SimulcastConsumer.hpp',
'include/RTC/SrtpSession.hpp',
'include/RTC/StunMessage.hpp',
'include/RTC/SvcConsumer.hpp',
'include/RTC/TcpConnection.hpp',
'include/RTC/TcpServer.hpp',
'include/RTC/Transport.hpp',
......@@ -162,6 +165,7 @@
'include/RTC/Codecs/PayloadDescriptorHandler.hpp',
'include/RTC/Codecs/H264.hpp',
'include/RTC/Codecs/VP8.hpp',
'include/RTC/Codecs/VP9.hpp',
'include/RTC/RTCP/Packet.hpp',
'include/RTC/RTCP/CompoundPacket.hpp',
'include/RTC/RTCP/SenderReport.hpp',
......
......@@ -26,6 +26,13 @@ namespace RTC
break;
}
case RTC::RtpCodecMimeType::Subtype::VP9:
{
RTC::Codecs::VP9::ProcessRtpPacket(packet);
break;
}
case RTC::RtpCodecMimeType::Subtype::H264:
{
RTC::Codecs::H264::ProcessRtpPacket(packet);
......
......@@ -32,6 +32,8 @@ namespace RTC
payloadDescriptor->b = frameMarking->base;
payloadDescriptor->tid = frameMarking->tid;
payloadDescriptor->hasTid = true;
if (frameMarkingLen >= 2)
{
payloadDescriptor->hasLid = true;
......@@ -143,19 +145,22 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<PayloadDescriptor>");
MS_DEBUG_DEV(" s : %s", this->s ? "true" : "false");
MS_DEBUG_DEV(" e : %s", this->e ? "true" : "false");
MS_DEBUG_DEV(" i : %s", this->i ? "true" : "false");
MS_DEBUG_DEV(" d : %s", this->d ? "true" : "false");
MS_DEBUG_DEV(" b : %s", this->b ? "true" : "false");
MS_DEBUG_DEV(" tid : %" PRIu8, this->tid);
MS_DUMP("<PayloadDescriptor>");
MS_DUMP(
" s:%" PRIu8 "|e:%" PRIu8 "|i:%" PRIu8 "|d:%" PRIu8 "|b:%" PRIu8,
this->s,
this->e,
this->i,
this->d,
this->b);
if (this->hasTid)
MS_DUMP(" tid : %" PRIu8, this->tid);
if (this->hasLid)
MS_DEBUG_DEV(" lid : %" PRIu8, this->lid);
MS_DUMP(" lid : %" PRIu8, this->lid);
if (this->hasTl0picidx)
MS_DEBUG_DEV(" tl0picidx : %" PRIu8, this->tl0picidx);
MS_DEBUG_DEV(" isKeyFrame : %s", this->isKeyFrame ? "true" : "false");
MS_DEBUG_DEV("</PayloadDescriptor>");
MS_DUMP(" tl0picidx : %" PRIu8, this->tl0picidx);
MS_DUMP(" isKeyFrame : %s", this->isKeyFrame ? "true" : "false");
MS_DUMP("</PayloadDescriptor>");
}
H264::PayloadDescriptorHandler::PayloadDescriptorHandler(H264::PayloadDescriptor* payloadDescriptor)
......@@ -166,7 +171,7 @@ namespace RTC
}
bool H264::PayloadDescriptorHandler::Process(
RTC::Codecs::EncodingContext* encodingContext, uint8_t* /*data*/)
RTC::Codecs::EncodingContext* encodingContext, uint8_t* /*data*/, bool& /*marker*/)
{
MS_TRACE();
......@@ -174,11 +179,20 @@ namespace RTC
MS_ASSERT(context->GetTargetTemporalLayer() >= 0, "target temporal layer cannot be -1");
// If a key frame, update current temporal layer.
if (this->payloadDescriptor->isKeyFrame)
context->SetCurrentTemporalLayer(context->GetTargetTemporalLayer());
// Check if the payload should contain temporal layer info.
if (context->GetTemporalLayers() > 1 && !this->payloadDescriptor->hasTid)
{
MS_WARN_TAG(rtp, "stream is supposed to have >1 temporal layers but does not have tid field");
return false;
}
if (this->payloadDescriptor->tid > context->GetTargetTemporalLayer())
// clang-format off
if (
this->payloadDescriptor->hasTid &&
this->payloadDescriptor->tid > context->GetTargetTemporalLayer()
)
// clang-format on
{
return false;
}
......@@ -188,6 +202,7 @@ namespace RTC
//
// clang-format off
// else if (
// this->payloadDescriptor->hasTid &&
// this->payloadDescriptor->tid > context->GetCurrentTemporalLayer() &&
// !this->payloadDescriptor->b
// )
......@@ -197,8 +212,15 @@ namespace RTC
// }
// Update/fix current temporal layer.
if (this->payloadDescriptor->tid > context->GetCurrentTemporalLayer())
// clang-format off
if (
this->payloadDescriptor->hasTid &&
this->payloadDescriptor->tid > context->GetCurrentTemporalLayer()
)
// clang-format on
{
context->SetCurrentTemporalLayer(this->payloadDescriptor->tid);
}
if (context->GetCurrentTemporalLayer() > context->GetTargetTemporalLayer())
context->SetCurrentTemporalLayer(context->GetTargetTemporalLayer());
......
......@@ -95,9 +95,14 @@ namespace RTC
payloadDescriptor->keyIndex = byte & 0x1F;
}
// clang-format off
if (
(len >= ++offset + 1) && payloadDescriptor->start &&
payloadDescriptor->partitionIndex == 0 && (!(data[offset] & 0x01)))
(len >= ++offset + 1) &&
payloadDescriptor->start &&
payloadDescriptor->partitionIndex == 0 &&
(!(data[offset] & 0x01))
)
// clang-format on
{
payloadDescriptor->isKeyFrame = true;
}
......@@ -147,29 +152,25 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<PayloadDescriptor>");
MS_DEBUG_DEV(" extended : %" PRIu8, this->extended);
MS_DEBUG_DEV(" nonReference : %" PRIu8, this->nonReference);
MS_DEBUG_DEV(" start : %" PRIu8, this->start);
MS_DEBUG_DEV(" partitionIndex : %" PRIu8, this->partitionIndex);
MS_DEBUG_DEV(
" i|l|t|k : %" PRIu8 "|%" PRIu8 "|%" PRIu8 "|%" PRIu8,
this->i,
this->l,
this->t,
this->k);
MS_DEBUG_DEV(" pictureId : %" PRIu16, this->pictureId);
MS_DEBUG_DEV(" tl0PictureIndex : %" PRIu8, this->tl0PictureIndex);
MS_DEBUG_DEV(" tlIndex : %" PRIu8, this->tlIndex);
MS_DEBUG_DEV(" y : %" PRIu8, this->y);
MS_DEBUG_DEV(" keyIndex : %" PRIu8, this->keyIndex);
MS_DEBUG_DEV(" isKeyFrame : %s", this->isKeyFrame ? "true" : "false");
MS_DEBUG_DEV(" hasPictureId : %s", this->hasPictureId ? "true" : "false");
MS_DEBUG_DEV(" hasOneBytePictureId : %s", this->hasOneBytePictureId ? "true" : "false");
MS_DEBUG_DEV(" hasTwoBytesPictureId : %s", this->hasTwoBytesPictureId ? "true" : "false");
MS_DEBUG_DEV(" hasTl0PictureIndex : %s", this->hasTl0PictureIndex ? "true" : "false");
MS_DEBUG_DEV(" hasTlIndex : %s", this->hasTlIndex ? "true" : "false");
MS_DEBUG_DEV("</PayloadDescriptor>");
MS_DUMP("<PayloadDescriptor>");
MS_DUMP(
" i:%" PRIu8 "|l:%" PRIu8 "|t:%" PRIu8 "|k:%" PRIu8, this->i, this->l, this->t, this->k);
MS_DUMP(" extended : %" PRIu8, this->extended);
MS_DUMP(" nonReference : %" PRIu8, this->nonReference);
MS_DUMP(" start : %" PRIu8, this->start);
MS_DUMP(" partitionIndex : %" PRIu8, this->partitionIndex);
MS_DUMP(" pictureId : %" PRIu16, this->pictureId);
MS_DUMP(" tl0PictureIndex : %" PRIu8, this->tl0PictureIndex);
MS_DUMP(" tlIndex : %" PRIu8, this->tlIndex);
MS_DUMP(" y : %" PRIu8, this->y);
MS_DUMP(" keyIndex : %" PRIu8, this->keyIndex);
MS_DUMP(" isKeyFrame : %s", this->isKeyFrame ? "true" : "false");
MS_DUMP(" hasPictureId : %s", this->hasPictureId ? "true" : "false");
MS_DUMP(" hasOneBytePictureId : %s", this->hasOneBytePictureId ? "true" : "false");
MS_DUMP(" hasTwoBytesPictureId : %s", this->hasTwoBytesPictureId ? "true" : "false");
MS_DUMP(" hasTl0PictureIndex : %s", this->hasTl0PictureIndex ? "true" : "false");
MS_DUMP(" hasTlIndex : %s", this->hasTlIndex ? "true" : "false");
MS_DUMP("</PayloadDescriptor>");
}
void VP8::PayloadDescriptor::Encode(uint8_t* data, uint16_t pictureId, uint8_t tl0PictureIndex) const
......@@ -221,7 +222,7 @@ namespace RTC
}
bool VP8::PayloadDescriptorHandler::Process(
RTC::Codecs::EncodingContext* encodingContext, uint8_t* data)
RTC::Codecs::EncodingContext* encodingContext, uint8_t* data, bool& /*marker*/)
{
MS_TRACE();
......@@ -229,6 +230,15 @@ namespace RTC
MS_ASSERT(context->GetTargetTemporalLayer() >= 0, "target temporal layer cannot be -1");
// Check if the payload should contain temporal layer info.
if (context->GetTemporalLayers() > 1 && !this->payloadDescriptor->hasTlIndex)
{
MS_WARN_TAG(
rtp, "stream is supposed to have >1 temporal layers but does not have TlIndex field");
return false;
}
// Check whether pictureId and tl0PictureIndex sync is required.
// clang-format off
if (
......@@ -244,17 +254,13 @@ namespace RTC
context->syncRequired = false;
}
// If a key frame, update current temporal layer.
if (this->payloadDescriptor->isKeyFrame)
context->SetCurrentTemporalLayer(context->GetTargetTemporalLayer());
// Incremental pictureId. Check the temporal layer.
// clang-format off
if (
this->payloadDescriptor->hasPictureId &&
this->payloadDescriptor->hasTlIndex &&
this->payloadDescriptor->hasTl0PictureIndex &&
RTC::SeqManager<uint16_t>::IsSeqHigherThan(
!RTC::SeqManager<uint16_t>::IsSeqLowerThan(
this->payloadDescriptor->pictureId,
context->pictureIdManager.GetMaxInput())
)
......@@ -310,8 +316,15 @@ namespace RTC
}
// Update/fix current temporal layer.
if (this->payloadDescriptor->tlIndex > context->GetCurrentTemporalLayer())
// clang-format off
if (
this->payloadDescriptor->hasTlIndex &&
this->payloadDescriptor->tlIndex > context->GetCurrentTemporalLayer()
)
// clang-format on
{
context->SetCurrentTemporalLayer(this->payloadDescriptor->tlIndex);
}
if (context->GetCurrentTemporalLayer() > context->GetTargetTemporalLayer())
context->SetCurrentTemporalLayer(context->GetTargetTemporalLayer());
......
#define MS_CLASS "RTC::Codecs::VP9"
// #define MS_LOG_DEV
#include "RTC/Codecs/VP9.hpp"
#include "Logger.hpp"
namespace RTC
{
namespace Codecs
{
/* Class methods. */
VP9::PayloadDescriptor* VP9::Parse(
const uint8_t* data,
size_t len,
RTC::RtpPacket::FrameMarking* /*frameMarking*/,
uint8_t /*frameMarkingLen*/)
{
MS_TRACE();
if (len < 1)
return nullptr;
std::unique_ptr<PayloadDescriptor> payloadDescriptor(new PayloadDescriptor());
size_t offset{ 0 };
uint8_t byte = data[offset];
payloadDescriptor->i = (byte >> 7) & 0x01;
payloadDescriptor->p = (byte >> 6) & 0x01;
payloadDescriptor->l = (byte >> 5) & 0x01;
payloadDescriptor->f = (byte >> 4) & 0x01;
payloadDescriptor->b = (byte >> 3) & 0x01;
payloadDescriptor->e = (byte >> 2) & 0x01;
payloadDescriptor->v = (byte >> 1) & 0x01;
if (payloadDescriptor->i)
{
if (len < ++offset + 1)
return nullptr;
byte = data[offset];
if (byte >> 7 & 0x01)
{
if (len < ++offset + 1)
return nullptr;
payloadDescriptor->pictureId = (byte & 0x7F) << 8;
payloadDescriptor->pictureId += data[offset];
payloadDescriptor->hasTwoBytesPictureId = true;
}
else
{
payloadDescriptor->pictureId = byte & 0x7F;
payloadDescriptor->hasOneBytePictureId = true;
}
payloadDescriptor->hasPictureId = true;
}
if (payloadDescriptor->l)
{
if (len < ++offset + 1)
return nullptr;
byte = data[offset];
payloadDescriptor->interLayerDependency = byte & 0x01;
payloadDescriptor->switchingUpPoint = byte >> 4 & 0x01;
payloadDescriptor->slIndex = byte >> 1 & 0x07;
payloadDescriptor->tlIndex = byte >> 5 & 0x07;
payloadDescriptor->hasSlIndex = true;
payloadDescriptor->hasTlIndex = true;
if (len < ++offset + 1)
return nullptr;
// Read TL0PICIDX if flexible mode is unset.
if (!payloadDescriptor->f)
{
payloadDescriptor->tl0PictureIndex = data[offset];
payloadDescriptor->hasTl0PictureIndex = true;
}
}
// clang-format off
if (
!payloadDescriptor->p &&
payloadDescriptor->b &&
payloadDescriptor->slIndex == 0
)
// clang-format on
{
payloadDescriptor->isKeyFrame = true;
}
return payloadDescriptor.release();
}
void VP9::ProcessRtpPacket(RTC::RtpPacket* packet)
{
MS_TRACE();
auto* data = packet->GetPayload();
auto len = packet->GetPayloadLength();
RtpPacket::FrameMarking* frameMarking{ nullptr };
uint8_t frameMarkingLen{ 0 };
// Read frame-marking.
packet->ReadFrameMarking(&frameMarking, frameMarkingLen);
PayloadDescriptor* payloadDescriptor = VP9::Parse(data, len, frameMarking, frameMarkingLen);
if (!payloadDescriptor)
return;
if (payloadDescriptor->isKeyFrame)
{
MS_DEBUG_DEV(
"key frame [spatialLayer:%" PRIu8 ", temporalLayer:%" PRIu8 "]",
packet->GetSpatialLayer(),
packet->GetTemporalLayer());
}
auto* payloadDescriptorHandler = new PayloadDescriptorHandler(payloadDescriptor);
packet->SetPayloadDescriptorHandler(payloadDescriptorHandler);
}
/* Instance methods. */
void VP9::PayloadDescriptor::Dump() const
{
MS_TRACE();
MS_DUMP("<PayloadDescriptor>");
MS_DUMP(
" i:%" PRIu8 "|p:%" PRIu8 "|l:%" PRIu8 "|f:%" PRIu8 "|b:%" PRIu8 "|e:%" PRIu8 "|v:%" PRIu8,
this->i,
this->p,
this->l,
this->f,
this->b,
this->e,
this->v);
MS_DUMP(" pictureId : %" PRIu16, this->pictureId);
MS_DUMP(" slIndex : %" PRIu8, this->slIndex);
MS_DUMP(" tlIndex : %" PRIu8, this->tlIndex);
MS_DUMP(" tl0PictureIndex : %" PRIu8, this->tl0PictureIndex);
MS_DUMP(" interLayerDependency : %" PRIu8, this->interLayerDependency);
MS_DUMP(" switchingUpPoint : %" PRIu8, this->switchingUpPoint);
MS_DUMP(" isKeyFrame : %s", this->isKeyFrame ? "true" : "false");
MS_DUMP(" hasPictureId : %s", this->hasPictureId ? "true" : "false");
MS_DUMP(" hasOneBytePictureId : %s", this->hasOneBytePictureId ? "true" : "false");
MS_DUMP(" hasTwoBytesPictureId : %s", this->hasTwoBytesPictureId ? "true" : "false");
MS_DUMP(" hasTl0PictureIndex : %s", this->hasTl0PictureIndex ? "true" : "false");
MS_DUMP(" hasSlIndex : %s", this->hasSlIndex ? "true" : "false");
MS_DUMP(" hasTlIndex : %s", this->hasTlIndex ? "true" : "false");
MS_DUMP("</PayloadDescriptor>");
}
VP9::PayloadDescriptorHandler::PayloadDescriptorHandler(VP9::PayloadDescriptor* payloadDescriptor)
{
MS_TRACE();
this->payloadDescriptor.reset(payloadDescriptor);
}
bool VP9::PayloadDescriptorHandler::Process(
RTC::Codecs::EncodingContext* encodingContext, uint8_t* /*data*/, bool& marker)
{
MS_TRACE();
auto* context = static_cast<RTC::Codecs::VP9::EncodingContext*>(encodingContext);
MS_ASSERT(context->GetTargetSpatialLayer() >= 0, "target spatial layer cannot be -1");
MS_ASSERT(context->GetTargetTemporalLayer() >= 0, "target temporal layer cannot be -1");
auto packetSpatialLayer = GetSpatialLayer();
auto packetTemporalLayer = GetTemporalLayer();
auto tmpSpatialLayer = context->GetCurrentSpatialLayer();
auto tmpTemporalLayer = context->GetCurrentTemporalLayer();
// If packet spatial or temporal layer is higher than maximum announced
// one, drop the packet.
// clang-format off
if (
packetSpatialLayer >= context->GetSpatialLayers() ||
packetTemporalLayer >= context->GetTemporalLayers()
)
// clang-format on
{
MS_WARN_TAG(
rtp, "too high packet layers %" PRIu8 ":%" PRIu8, packetSpatialLayer, packetTemporalLayer);
return false;
}
// Check whether pictureId sync is required.
// clang-format off
if (
context->syncRequired &&
this->payloadDescriptor->hasPictureId
)
// clang-format on
{
context->pictureIdManager.Sync(this->payloadDescriptor->pictureId - 1);
context->syncRequired = false;
}
// clang-format off
bool isOldPacket = (
this->payloadDescriptor->hasPictureId &&
RTC::SeqManager<uint16_t>::IsSeqLowerThan(
this->payloadDescriptor->pictureId,
context->pictureIdManager.GetMaxInput())
);
// clang-format on
// Upgrade current spatial layer if needed.
if (context->GetTargetSpatialLayer() > context->GetCurrentSpatialLayer())
{
if (this->payloadDescriptor->isKeyFrame)
{
MS_DEBUG_DEV(
"upgrading tmpSpatialLayer from %" PRIu16 " to %" PRIu16 " (packet:%" PRIu8 ":%" PRIu8
")",
context->GetCurrentSpatialLayer(),
context->GetTargetSpatialLayer(),
packetSpatialLayer,
packetTemporalLayer);
tmpSpatialLayer = context->GetTargetSpatialLayer();
tmpTemporalLayer = 0; // Just in case.
}
}
// Downgrade current spatial layer if needed.
else if (context->GetTargetSpatialLayer() < context->GetCurrentSpatialLayer())
{
// In K-SVC we must wait for a keyframe.
if (context->IsKSvc())
{
if (this->payloadDescriptor->isKeyFrame)
// clang-format on
{
MS_DEBUG_DEV(
"downgrading tmpSpatialLayer from %" PRIu16 " to %" PRIu16 " (packet:%" PRIu8
":%" PRIu8 ") after keyframe (K-SVC)",
context->GetCurrentSpatialLayer(),
context->GetTargetSpatialLayer(),
packetSpatialLayer,
packetTemporalLayer);
tmpSpatialLayer = context->GetTargetSpatialLayer();
tmpTemporalLayer = 0; // Just in case.
}
}
// In full SVC we do not need a keyframe.
else
{
// clang-format off
if (
packetSpatialLayer == context->GetTargetSpatialLayer() &&
this->payloadDescriptor->e
)
// clang-format on
{
MS_DEBUG_DEV(
"downgrading tmpSpatialLayer from %" PRIu16 " to %" PRIu16 " (packet:%" PRIu8
":%" PRIu8 ") without keyframe (full SVC)",
context->GetCurrentSpatialLayer(),
context->GetTargetSpatialLayer(),
packetSpatialLayer,
packetTemporalLayer);
tmpSpatialLayer = context->GetTargetSpatialLayer();
tmpTemporalLayer = 0; // Just in case.
}
}
}
// Filter spatial layers higher than current one (unless old packet).
if (packetSpatialLayer > tmpSpatialLayer && !isOldPacket)
return false;
// Check and handle temporal layer (unless old packet).
if (!isOldPacket)
{
// Upgrade current temporal layer if needed.
if (context->GetTargetTemporalLayer() > context->GetCurrentTemporalLayer())
{
// clang-format off
if (
packetTemporalLayer >= context->GetCurrentTemporalLayer() + 1 &&
(
context->GetCurrentTemporalLayer() == -1 ||
this->payloadDescriptor->switchingUpPoint
) &&
this->payloadDescriptor->b
)
// clang-format on
{
MS_DEBUG_DEV(
"upgrading tmpTemporalLayer from %" PRIu16 " to %" PRIu8 " (packet:%" PRIu8 ":%" PRIu8
")",
context->GetCurrentTemporalLayer(),
packetTemporalLayer,
packetSpatialLayer,
packetTemporalLayer);
tmpTemporalLayer = packetTemporalLayer;
}
}
// Downgrade current temporal layer if needed.
else if (context->GetTargetTemporalLayer() < context->GetCurrentTemporalLayer())
{
// clang-format off
if (
packetTemporalLayer == context->GetTargetTemporalLayer() &&
this->payloadDescriptor->e
)
// clang-format on
{
MS_DEBUG_DEV(
"downgrading tmpTemporalLayer from %" PRIu16 " to %" PRIu16 " (packet:%" PRIu8
":%" PRIu8 ")",
context->GetCurrentTemporalLayer(),
context->GetTargetTemporalLayer(),
packetSpatialLayer,
packetTemporalLayer);
tmpTemporalLayer = context->GetTargetTemporalLayer();
}
}
// Filter temporal layers higher than current one.
if (packetTemporalLayer > tmpTemporalLayer)
return false;
}
// Set marker bit if needed.
if (packetSpatialLayer == tmpSpatialLayer && this->payloadDescriptor->e)
marker = true;
// Update the pictureId manager.
if (this->payloadDescriptor->hasPictureId)
{
uint16_t pictureId;
context->pictureIdManager.Input(this->payloadDescriptor->pictureId, pictureId);
}
// Update current spatial layer if needed.
if (tmpSpatialLayer != context->GetCurrentSpatialLayer())
context->SetCurrentSpatialLayer(tmpSpatialLayer);
// Update current temporal layer if needed.
if (tmpTemporalLayer != context->GetCurrentTemporalLayer())
context->SetCurrentTemporalLayer(tmpTemporalLayer);
return true;
}
void VP9::PayloadDescriptorHandler::Restore(uint8_t* /*data*/)
{
MS_TRACE();
}
} // namespace Codecs
} // namespace RTC
......@@ -278,6 +278,7 @@ namespace RTC
return;
error:
if (bne != nullptr)
BN_free(bne);
......@@ -338,6 +339,7 @@ namespace RTC
return;
error:
MS_THROW_ERROR("error reading DTLS certificate and private key PEM files");
}
......@@ -479,6 +481,7 @@ namespace RTC
return;
error:
if (DtlsTransport::sslCtx != nullptr)
{
SSL_CTX_free(DtlsTransport::sslCtx);
......@@ -611,6 +614,7 @@ namespace RTC
return;
error:
// NOTE: At this point SSL_set_bio() was not called so we must free BIOs as
// well.
if (this->sslBioFromNetwork != nullptr)
......@@ -655,15 +659,15 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<DtlsTransport>");
MS_DEBUG_DEV(
MS_DUMP("<DtlsTransport>");
MS_DUMP(
" [role:%s, running:%s, handshake done:%s, connected:%s]",
(this->localRole == Role::SERVER ? "server"
: (this->localRole == Role::CLIENT ? "client" : "none")),
IsRunning() ? "yes" : "no",
this->handshakeDone ? "yes" : "no",
this->state == DtlsState::CONNECTED ? "yes" : "no");
MS_DEBUG_DEV("</DtlsTransport>");
MS_DUMP("</DtlsTransport>");
}
void DtlsTransport::Run(Role localRole)
......
......@@ -20,6 +20,11 @@ namespace RTC
if (this->rtpParameters.encodings.size() != this->consumableRtpEncodings.size())
MS_THROW_TYPE_ERROR("number of rtpParameters.encodings and consumableRtpEncodings do not match");
auto& encoding = this->rtpParameters.encodings[0];
auto* mediaCodec = this->rtpParameters.GetCodecForEncoding(encoding);
this->keyFrameSupported = RTC::Codecs::CanBeKeyFrame(mediaCodec->mimeType);
// Create RtpStreamSend instances.
CreateRtpStreams();
}
......@@ -467,8 +472,6 @@ namespace RTC
if (rtxCodec && encoding.hasRtx)
rtpStream->SetRtx(rtxCodec->payloadType, encoding.rtx.ssrc);
this->keyFrameSupported = RTC::Codecs::CanBeKeyFrame(mediaCodec->mimeType);
this->mapMappedSsrcRtpStream[encoding.ssrc] = rtpStream;
this->rtpStreams.push_back(rtpStream);
this->mapRtpStreamSyncRequired[rtpStream] = false;
......
......@@ -7,6 +7,7 @@
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
#include "Channel/Notifier.hpp"
#include "RTC/Codecs/Codecs.hpp"
#include <cstring> // std::memcpy()
namespace RTC
......@@ -40,6 +41,17 @@ namespace RTC
// Evaluate type.
this->type = RTC::RtpParameters::GetType(this->rtpParameters);
auto& encoding = this->rtpParameters.encodings[0];
auto* mediaCodec = this->rtpParameters.GetCodecForEncoding(encoding);
if (!RTC::Codecs::IsValidTypeForCodec(this->type, mediaCodec->mimeType))
{
MS_THROW_TYPE_ERROR(
"%s codec not supported for %s",
mediaCodec->mimeType.ToString().c_str(),
RTC::RtpParameters::GetTypeString(this->type).c_str());
}
auto jsonRtpMappingIt = data.find("rtpMapping");
if (jsonRtpMappingIt == data.end() || !jsonRtpMappingIt->is_object())
......
......@@ -90,16 +90,14 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<ByePacket>");
#ifdef MS_LOG_DEV
MS_DUMP("<ByePacket>");
for (auto ssrc : this->ssrcs)
{
MS_DEBUG_DEV(" ssrc : %" PRIu32, ssrc);
MS_DUMP(" ssrc : %" PRIu32, ssrc);
}
#endif
if (!this->reason.empty())
MS_DEBUG_DEV(" reason : %s", this->reason.c_str());
MS_DEBUG_DEV("</ByePacket>");
MS_DUMP(" reason : %s", this->reason.c_str());
MS_DUMP("</ByePacket>");
}
} // namespace RTCP
} // namespace RTC
......@@ -87,7 +87,7 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<CompoundPacket>");
MS_DUMP("<CompoundPacket>");
if (HasSenderReport())
{
......@@ -104,7 +104,7 @@ namespace RTC
if (this->sdesPacket.GetCount() != 0u)
this->sdesPacket.Dump();
MS_DEBUG_DEV("</CompoundPacket>");
MS_DUMP("</CompoundPacket>");
}
void CompoundPacket::AddSenderReport(SenderReport* report)
......
......@@ -88,9 +88,9 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV(" sender ssrc : %" PRIu32, GetSenderSsrc());
MS_DEBUG_DEV(" media ssrc : %" PRIu32, GetMediaSsrc());
MS_DEBUG_DEV(" size : %zu", this->GetSize());
MS_DUMP(" sender ssrc : %" PRIu32, GetSenderSsrc());
MS_DUMP(" media ssrc : %" PRIu32, GetMediaSsrc());
MS_DUMP(" size : %zu", this->GetSize());
}
/* Specialization for Ps class. */
......
......@@ -83,13 +83,13 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<%s>", FeedbackPsPacket::MessageType2String(Item::messageType).c_str());
MS_DUMP("<%s>", FeedbackPsPacket::MessageType2String(Item::messageType).c_str());
FeedbackPsPacket::Dump();
for (auto* item : this->items)
{
item->Dump();
}
MS_DEBUG_DEV("</%s>", FeedbackPsPacket::MessageType2String(Item::messageType).c_str());
MS_DUMP("</%s>", FeedbackPsPacket::MessageType2String(Item::messageType).c_str());
}
// explicit instantiation to have all FeedbackRtpPacket definitions in this file.
......
......@@ -60,9 +60,9 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsAfbPacket>");
MS_DUMP("<FeedbackPsAfbPacket>");
FeedbackPsPacket::Dump();
MS_DEBUG_DEV("</FeedbackPsAfbPacket>");
MS_DUMP("</FeedbackPsAfbPacket>");
}
} // namespace RTCP
} // namespace RTC
......@@ -41,10 +41,10 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsFirItem>");
MS_DEBUG_DEV(" ssrc : %" PRIu32, this->GetSsrc());
MS_DEBUG_DEV(" sequence number : %" PRIu8, this->GetSequenceNumber());
MS_DEBUG_DEV("</FeedbackPsFirItem>");
MS_DUMP("<FeedbackPsFirItem>");
MS_DUMP(" ssrc : %" PRIu32, this->GetSsrc());
MS_DUMP(" sequence number : %" PRIu8, this->GetSequenceNumber());
MS_DUMP("</FeedbackPsFirItem>");
}
} // namespace RTCP
} // namespace RTC
......@@ -33,9 +33,9 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsLeiItem>");
MS_DEBUG_DEV(" ssrc : %" PRIu32, this->GetSsrc());
MS_DEBUG_DEV("</FeedbackPsLeiItem>");
MS_DUMP("<FeedbackPsLeiItem>");
MS_DUMP(" ssrc : %" PRIu32, this->GetSsrc());
MS_DUMP("</FeedbackPsLeiItem>");
}
} // namespace RTCP
} // namespace RTC
......@@ -32,9 +32,9 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsPliPacket>");
MS_DUMP("<FeedbackPsPliPacket>");
FeedbackPsPacket::Dump();
MS_DEBUG_DEV("</FeedbackPsPliPacket>");
MS_DUMP("</FeedbackPsPliPacket>");
}
} // namespace RTCP
} // namespace RTC
......@@ -137,16 +137,14 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsRembPacket>");
MS_DUMP("<FeedbackPsRembPacket>");
FeedbackPsPacket::Dump();
MS_DEBUG_DEV(" bitrate (bps): %" PRIu64, this->bitrate);
#ifdef MS_LOG_DEV
MS_DUMP(" bitrate (bps): %" PRIu64, this->bitrate);
for (auto ssrc : this->ssrcs)
{
MS_DEBUG_DEV(" ssrc: %" PRIu32, ssrc);
MS_DUMP(" ssrc: %" PRIu32, ssrc);
}
#endif
MS_DEBUG_DEV("</FeedbackPsRembPacket>");
MS_DUMP("</FeedbackPsRembPacket>");
}
} // namespace RTCP
} // namespace RTC
......@@ -76,11 +76,11 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsRpsiItem>");
MS_DEBUG_DEV(" padding bits : %" PRIu8, this->header->paddingBits);
MS_DEBUG_DEV(" payload type : %" PRIu8, this->GetPayloadType());
MS_DEBUG_DEV(" length : %zu", this->GetLength());
MS_DEBUG_DEV("</FeedbackPsRpsiItem>");
MS_DUMP("<FeedbackPsRpsiItem>");
MS_DUMP(" padding bits : %" PRIu8, this->header->paddingBits);
MS_DUMP(" payload type : %" PRIu8, this->GetPayloadType());
MS_DUMP(" length : %zu", this->GetLength());
MS_DUMP("</FeedbackPsRpsiItem>");
}
} // namespace RTCP
} // namespace RTC
......@@ -39,11 +39,11 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsSliItem>");
MS_DEBUG_DEV(" first : %" PRIu16, this->first);
MS_DEBUG_DEV(" number : %" PRIu16, this->number);
MS_DEBUG_DEV(" picture id : %" PRIu8, this->pictureId);
MS_DEBUG_DEV("</FeedbackPsSliItem>");
MS_DUMP("<FeedbackPsSliItem>");
MS_DUMP(" first : %" PRIu16, this->first);
MS_DUMP(" number : %" PRIu16, this->number);
MS_DUMP(" picture id : %" PRIu8, this->pictureId);
MS_DUMP("</FeedbackPsSliItem>");
}
} // namespace RTCP
} // namespace RTC
......@@ -40,11 +40,11 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsTstItem>");
MS_DEBUG_DEV(" ssrc : %" PRIu32, this->GetSsrc());
MS_DEBUG_DEV(" sequence number : %" PRIu32, this->GetSequenceNumber());
MS_DEBUG_DEV(" index : %" PRIu32, this->GetIndex());
MS_DEBUG_DEV("</FeedbackPsTstItem>");
MS_DUMP("<FeedbackPsTstItem>");
MS_DUMP(" ssrc : %" PRIu32, this->GetSsrc());
MS_DUMP(" sequence number : %" PRIu32, this->GetSequenceNumber());
MS_DUMP(" index : %" PRIu32, this->GetIndex());
MS_DUMP("</FeedbackPsTstItem>");
}
/* Specialization for Tstr class. */
......
......@@ -50,12 +50,12 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackPsVbcmItem>");
MS_DEBUG_DEV(" ssrc : %" PRIu32, this->GetSsrc());
MS_DEBUG_DEV(" sequence number : %" PRIu8, this->GetSequenceNumber());
MS_DEBUG_DEV(" payload type : %" PRIu8, this->GetPayloadType());
MS_DEBUG_DEV(" length : %" PRIu16, this->GetLength());
MS_DEBUG_DEV("</FeedbackPsVbcmItem>");
MS_DUMP("<FeedbackPsVbcmItem>");
MS_DUMP(" ssrc : %" PRIu32, this->GetSsrc());
MS_DUMP(" sequence number : %" PRIu8, this->GetSequenceNumber());
MS_DUMP(" payload type : %" PRIu8, this->GetPayloadType());
MS_DUMP(" length : %" PRIu16, this->GetLength());
MS_DUMP("</FeedbackPsVbcmItem>");
}
} // namespace RTCP
} // namespace RTC
......@@ -73,13 +73,13 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<%s>", FeedbackRtpPacket::MessageType2String(Item::messageType).c_str());
MS_DUMP("<%s>", FeedbackRtpPacket::MessageType2String(Item::messageType).c_str());
FeedbackRtpPacket::Dump();
for (auto* item : this->items)
{
item->Dump();
}
MS_DEBUG_DEV("</%s>", FeedbackRtpPacket::MessageType2String(Item::messageType).c_str());
MS_DUMP("</%s>", FeedbackRtpPacket::MessageType2String(Item::messageType).c_str());
}
// Explicit instantiation to have all FeedbackRtpPacket definitions in this file.
......
......@@ -23,15 +23,15 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackRtpEcnItem>");
MS_DEBUG_DEV(" sequence number : %" PRIu32, this->GetSequenceNumber());
MS_DEBUG_DEV(" ect0 counter : %" PRIu32, this->GetEct0Counter());
MS_DEBUG_DEV(" ect1 counter : %" PRIu32, this->GetEct1Counter());
MS_DEBUG_DEV(" ecn ce counter : %" PRIu16, this->GetEcnCeCounter());
MS_DEBUG_DEV(" not ect counter : %" PRIu16, this->GetNotEctCounter());
MS_DEBUG_DEV(" lost packets : %" PRIu16, this->GetLostPackets());
MS_DEBUG_DEV(" duplicated packets : %" PRIu16, this->GetDuplicatedPackets());
MS_DEBUG_DEV("</FeedbackRtpEcnItem>");
MS_DUMP("<FeedbackRtpEcnItem>");
MS_DUMP(" sequence number : %" PRIu32, this->GetSequenceNumber());
MS_DUMP(" ect0 counter : %" PRIu32, this->GetEct0Counter());
MS_DUMP(" ect1 counter : %" PRIu32, this->GetEct1Counter());
MS_DUMP(" ecn ce counter : %" PRIu16, this->GetEcnCeCounter());
MS_DUMP(" not ect counter : %" PRIu16, this->GetNotEctCounter());
MS_DUMP(" lost packets : %" PRIu16, this->GetLostPackets());
MS_DUMP(" duplicated packets : %" PRIu16, this->GetDuplicatedPackets());
MS_DUMP("</FeedbackRtpEcnItem>");
}
} // namespace RTCP
} // namespace RTC
......@@ -36,10 +36,10 @@ namespace RTC
std::bitset<16> nackBitset(this->GetLostPacketBitmask());
MS_DEBUG_DEV("<FeedbackRtpNackItem>");
MS_DEBUG_DEV(" pid : %" PRIu16, this->GetPacketId());
MS_DEBUG_DEV(" bpl : %s", nackBitset.to_string().c_str());
MS_DEBUG_DEV("</FeedbackRtpNackItem>");
MS_DUMP("<FeedbackRtpNackItem>");
MS_DUMP(" pid : %" PRIu16, this->GetPacketId());
MS_DUMP(" bpl : %s", nackBitset.to_string().c_str());
MS_DUMP("</FeedbackRtpNackItem>");
}
} // namespace RTCP
} // namespace RTC
......@@ -30,9 +30,9 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackRtpSrReqPacket>");
MS_DUMP("<FeedbackRtpSrReqPacket>");
FeedbackRtpPacket::Dump();
MS_DEBUG_DEV("</FeedbackRtpSrReqPacket>");
MS_DUMP("</FeedbackRtpSrReqPacket>");
}
} // namespace RTCP
} // namespace RTC
......@@ -33,10 +33,10 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackRtpTlleiItem>");
MS_DEBUG_DEV(" pid: %" PRIu16, this->GetPacketId());
MS_DEBUG_DEV(" bpl: %" PRIu16, this->GetLostPacketBitmask());
MS_DEBUG_DEV("</FeedbackRtpTlleiItem>");
MS_DUMP("<FeedbackRtpTlleiItem>");
MS_DUMP(" pid: %" PRIu16, this->GetPacketId());
MS_DUMP(" bpl: %" PRIu16, this->GetLostPacketBitmask());
MS_DUMP("</FeedbackRtpTlleiItem>");
}
} // namespace RTCP
} // namespace RTC
......@@ -68,11 +68,11 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<FeedbackRtpTmmbItem>");
MS_DEBUG_DEV(" ssrc : %" PRIu32, this->GetSsrc());
MS_DEBUG_DEV(" bitrate : %" PRIu64, this->GetBitrate());
MS_DEBUG_DEV(" overhead : %" PRIu16, this->GetOverhead());
MS_DEBUG_DEV("</FeedbackRtpTmmbItem>");
MS_DUMP("<FeedbackRtpTmmbItem>");
MS_DUMP(" ssrc : %" PRIu32, this->GetSsrc());
MS_DUMP(" bitrate : %" PRIu64, this->GetBitrate());
MS_DUMP(" overhead : %" PRIu16, this->GetOverhead());
MS_DUMP("</FeedbackRtpTmmbItem>");
}
/* Specialization for Tmmbr class. */
......
......@@ -36,15 +36,15 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<ReceiverReport>");
MS_DEBUG_DEV(" ssrc : %" PRIu32, GetSsrc());
MS_DEBUG_DEV(" fraction lost : %" PRIu8, GetFractionLost());
MS_DEBUG_DEV(" total lost : %" PRIu32, GetTotalLost());
MS_DEBUG_DEV(" last seq : %" PRIu32, GetLastSeq());
MS_DEBUG_DEV(" jitter : %" PRIu32, GetJitter());
MS_DEBUG_DEV(" lsr : %" PRIu32, GetLastSenderReport());
MS_DEBUG_DEV(" dlsr : %" PRIu32, GetDelaySinceLastSenderReport());
MS_DEBUG_DEV("</ReceiverReport>");
MS_DUMP("<ReceiverReport>");
MS_DUMP(" ssrc : %" PRIu32, GetSsrc());
MS_DUMP(" fraction lost : %" PRIu8, GetFractionLost());
MS_DUMP(" total lost : %" PRIu32, GetTotalLost());
MS_DUMP(" last seq : %" PRIu32, GetLastSeq());
MS_DUMP(" jitter : %" PRIu32, GetJitter());
MS_DUMP(" lsr : %" PRIu32, GetLastSenderReport());
MS_DUMP(" dlsr : %" PRIu32, GetDelaySinceLastSenderReport());
MS_DUMP("</ReceiverReport>");
}
size_t ReceiverReport::Serialize(uint8_t* buffer)
......@@ -133,13 +133,13 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<ReceiverReportPacket>");
MS_DEBUG_DEV(" ssrc: %" PRIu32, static_cast<uint32_t>(ntohl(this->ssrc)));
MS_DUMP("<ReceiverReportPacket>");
MS_DUMP(" ssrc: %" PRIu32, static_cast<uint32_t>(ntohl(this->ssrc)));
for (auto* report : this->reports)
{
report->Dump();
}
MS_DEBUG_DEV("</ReceiverReportPacket>");
MS_DUMP("</ReceiverReportPacket>");
}
} // namespace RTCP
} // namespace RTC
......@@ -87,11 +87,11 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<SdesItem>");
MS_DEBUG_DEV(" type : %s", SdesItem::Type2String(this->GetType()).c_str());
MS_DEBUG_DEV(" length : %" PRIu8, this->header->length);
MS_DEBUG_DEV(" value : %.*s", this->header->length, this->header->value);
MS_DEBUG_DEV("</SdesItem>");
MS_DUMP("<SdesItem>");
MS_DUMP(" type : %s", SdesItem::Type2String(this->GetType()).c_str());
MS_DUMP(" length : %" PRIu8, this->header->length);
MS_DUMP(" value : %.*s", this->header->length, this->header->value);
MS_DUMP("</SdesItem>");
}
size_t SdesItem::Serialize(uint8_t* buffer)
......@@ -169,13 +169,13 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<SdesChunk>");
MS_DEBUG_DEV(" ssrc : %" PRIu32, static_cast<uint32_t>(ntohl(this->ssrc)));
MS_DUMP("<SdesChunk>");
MS_DUMP(" ssrc : %" PRIu32, static_cast<uint32_t>(ntohl(this->ssrc)));
for (auto* item : this->items)
{
item->Dump();
}
MS_DEBUG_DEV("</SdesChunk>");
MS_DUMP("</SdesChunk>");
}
/* Class methods. */
......@@ -228,12 +228,12 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<SdesPacket>");
MS_DUMP("<SdesPacket>");
for (auto* chunk : this->chunks)
{
chunk->Dump();
}
MS_DEBUG_DEV("</SdesPacket>");
MS_DUMP("</SdesPacket>");
}
} // namespace RTCP
} // namespace RTC
......@@ -35,14 +35,14 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<SenderReport>");
MS_DEBUG_DEV(" ssrc : %" PRIu32, GetSsrc());
MS_DEBUG_DEV(" ntp sec : %" PRIu32, GetNtpSec());
MS_DEBUG_DEV(" ntp frac : %" PRIu32, GetNtpFrac());
MS_DEBUG_DEV(" rtp ts : %" PRIu32, GetRtpTs());
MS_DEBUG_DEV(" packet count : %" PRIu32, GetPacketCount());
MS_DEBUG_DEV(" octet count : %" PRIu32, GetOctetCount());
MS_DEBUG_DEV("</SenderReport>");
MS_DUMP("<SenderReport>");
MS_DUMP(" ssrc : %" PRIu32, GetSsrc());
MS_DUMP(" ntp sec : %" PRIu32, GetNtpSec());
MS_DUMP(" ntp frac : %" PRIu32, GetNtpFrac());
MS_DUMP(" rtp ts : %" PRIu32, GetRtpTs());
MS_DUMP(" packet count : %" PRIu32, GetPacketCount());
MS_DUMP(" octet count : %" PRIu32, GetOctetCount());
MS_DUMP("</SenderReport>");
}
size_t SenderReport::Serialize(uint8_t* buffer)
......@@ -97,12 +97,12 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<SenderReportPacket>");
MS_DUMP("<SenderReportPacket>");
for (auto* report : this->reports)
{
report->Dump();
}
MS_DEBUG_DEV("</SenderReportPacket>");
MS_DUMP("</SenderReportPacket>");
}
} // namespace RTCP
} // namespace RTC
......@@ -68,7 +68,7 @@ namespace RTC
std::string scalabilityMode = jsonScalabilityModeIt->get<std::string>();
static const std::regex ScalabilityModeRegex(
"^[LS](\\d+)T(\\d+).*", std::regex_constants::ECMAScript);
"^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})(_KEY)?.*", std::regex_constants::ECMAScript);
std::smatch match;
......@@ -82,6 +82,7 @@ namespace RTC
{
this->spatialLayers = std::stoul(match[1].str());
this->temporalLayers = std::stoul(match[2].str());
this->ksvc = match.size() >= 4 && match[3].str() == "_KEY";
}
catch (std::exception& e)
{
......@@ -132,6 +133,7 @@ namespace RTC
jsonObject["scalabilityMode"] = this->scalabilityMode;
jsonObject["spatialLayers"] = this->spatialLayers;
jsonObject["temporalLayers"] = this->temporalLayers;
jsonObject["ksvc"] = this->ksvc;
}
}
} // namespace RTC
......@@ -35,12 +35,19 @@ namespace RTC
{
MS_TRACE();
// TODO: This is very basic and must be updated to detect SVC and so on.
if (rtpParameters.encodings.size() == 1)
return RtpParameters::Type::SIMPLE;
{
auto& encoding = rtpParameters.encodings[0];
if (encoding.spatialLayers > 1 || encoding.temporalLayers > 1)
return RtpParameters::Type::SVC;
else
return RtpParameters::Type::SIMPLE;
}
else if (rtpParameters.encodings.size() > 1)
{
return RtpParameters::Type::SIMULCAST;
}
return RtpParameters::Type::NONE;
}
......
......@@ -153,22 +153,22 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<RtpPacket>");
MS_DEBUG_DEV(" padding : %s", this->header->padding ? "true" : "false");
MS_DUMP("<RtpPacket>");
MS_DUMP(" padding : %s", this->header->padding ? "true" : "false");
if (HasHeaderExtension())
{
MS_DEBUG_DEV(
MS_DUMP(
" header extension : id:%" PRIu16 ",length:%zu",
GetHeaderExtensionId(),
GetHeaderExtensionLength());
}
if (HasOneByteExtensions())
{
MS_DEBUG_DEV(" RFC5285 ext style : One-Byte Header");
MS_DUMP(" RFC5285 ext style : One-Byte Header");
}
if (HasTwoBytesExtensions())
{
MS_DEBUG_DEV(" RFC5285 ext style : Two-Bytes Header");
MS_DUMP(" RFC5285 ext style : Two-Bytes Header");
}
if (HasOneByteExtensions() || HasTwoBytesExtensions())
{
......@@ -200,7 +200,7 @@ namespace RTC
extIds.begin(), extIds.end() - 1, std::ostream_iterator<std::string>(extIdsStream, ","));
extIdsStream << extIds.back();
MS_DEBUG_DEV(" RFC5285 ext ids : %s", extIdsStream.str().c_str());
MS_DUMP(" RFC5285 ext ids : %s", extIdsStream.str().c_str());
}
}
if (this->midExtensionId != 0u)
......@@ -208,37 +208,34 @@ namespace RTC
std::string mid;
if (ReadMid(mid))
MS_DEBUG_DEV(
" mid : extId:%" PRIu8 ",value:%s", this->midExtensionId, mid.c_str());
MS_DUMP(" mid : extId:%" PRIu8 ",value:%s", this->midExtensionId, mid.c_str());
}
if (this->ridExtensionId != 0u)
{
std::string rid;
if (ReadRid(rid))
MS_DEBUG_DEV(
" rid : extId:%" PRIu8 ",value:%s", this->ridExtensionId, rid.c_str());
MS_DUMP(" rid : extId:%" PRIu8 ",value:%s", this->ridExtensionId, rid.c_str());
}
if (this->rridExtensionId != 0u)
{
std::string rid;
if (ReadRid(rid))
MS_DEBUG_DEV(
" rrid : extId:%" PRIu8 ",value:%s", this->rridExtensionId, rid.c_str());
MS_DUMP(" rrid : extId:%" PRIu8 ",value:%s", this->rridExtensionId, rid.c_str());
}
if (this->absSendTimeExtensionId != 0u)
{
MS_DEBUG_DEV(" absSendTime : extId:%" PRIu8, this->absSendTimeExtensionId);
MS_DUMP(" absSendTime : extId:%" PRIu8, this->absSendTimeExtensionId);
}
// Remove once it becomes RFC.
if (this->frameMarking07ExtensionId != 0u)
{
MS_DEBUG_DEV(" frameMarking07 : extId:%" PRIu8, this->frameMarking07ExtensionId);
MS_DUMP(" frameMarking07 : extId:%" PRIu8, this->frameMarking07ExtensionId);
}
if (this->frameMarkingExtensionId != 0u)
{
MS_DEBUG_DEV(" frameMarking : extId:%" PRIu8, this->frameMarkingExtensionId);
MS_DUMP(" frameMarking : extId:%" PRIu8, this->frameMarkingExtensionId);
}
if (this->ssrcAudioLevelExtensionId != 0u)
{
......@@ -246,11 +243,13 @@ namespace RTC
bool voice;
if (ReadSsrcAudioLevel(volume, voice))
MS_DEBUG_DEV(
{
MS_DUMP(
" ssrcAudioLevel : extId:%" PRIu8 ",volume:%" PRIu8 ",voice:%s",
this->ssrcAudioLevelExtensionId,
volume,
voice ? "true" : "false");
}
}
if (this->videoOrientationExtensionId != 0u)
{
......@@ -259,26 +258,30 @@ namespace RTC
uint16_t rotation;
if (ReadVideoOrientation(camera, flip, rotation))
MS_DEBUG_DEV(
{
MS_DUMP(
" videoOrientation : extId:%" PRIu8 ",camera:%s,flip:%s,rotation:%" PRIu16,
this->videoOrientationExtensionId,
camera ? "true" : "false",
flip ? "true" : "false",
rotation);
}
}
MS_DEBUG_DEV(" csrc count : %" PRIu8, this->header->csrcCount);
MS_DEBUG_DEV(" marker : %s", HasMarker() ? "true" : "false");
MS_DEBUG_DEV(" payload type : %" PRIu8, GetPayloadType());
MS_DEBUG_DEV(" sequence number : %" PRIu16, GetSequenceNumber());
MS_DEBUG_DEV(" timestamp : %" PRIu32, GetTimestamp());
MS_DEBUG_DEV(" ssrc : %" PRIu32, GetSsrc());
MS_DEBUG_DEV(" payload size : %zu bytes", GetPayloadLength());
MS_DUMP(" csrc count : %" PRIu8, this->header->csrcCount);
MS_DUMP(" marker : %s", HasMarker() ? "true" : "false");
MS_DUMP(" payload type : %" PRIu8, GetPayloadType());
MS_DUMP(" sequence number : %" PRIu16, GetSequenceNumber());
MS_DUMP(" timestamp : %" PRIu32, GetTimestamp());
MS_DUMP(" ssrc : %" PRIu32, GetSsrc());
MS_DUMP(" payload size : %zu bytes", GetPayloadLength());
if (this->header->padding != 0u)
{
MS_DEBUG_DEV(" padding size : %" PRIu8 " bytes", this->payloadPadding);
MS_DUMP(" padding size : %" PRIu8 " bytes", this->payloadPadding);
}
MS_DEBUG_DEV(" packet size : %zu bytes", GetSize());
MS_DEBUG_DEV("</RtpPacket>");
MS_DUMP(" packet size : %zu bytes", GetSize());
MS_DUMP(" spatial layer : %" PRIu8, GetSpatialLayer());
MS_DUMP(" temporal layer : %" PRIu8, GetTemporalLayer());
MS_DUMP("</RtpPacket>");
}
void RtpPacket::SetExtensions(uint8_t type, const std::vector<GenericExtension>& extensions)
......@@ -598,7 +601,19 @@ namespace RTC
if (!this->payloadDescriptorHandler)
return true;
return this->payloadDescriptorHandler->Process(context, this->payload);
bool marker{ false };
if (this->payloadDescriptorHandler->Process(context, this->payload, marker))
{
if (marker)
SetMarker(true);
return true;
}
else
{
return false;
}
}
void RtpPacket::RestorePayload()
......
......@@ -9,10 +9,6 @@
namespace RTC
{
/* Static. */
static constexpr uint16_t InactivityCheckPeriod{ 250 };
/* TransmissionCounter methods. */
RtpStreamRecv::TransmissionCounter::TransmissionCounter(uint8_t spatialLayers, uint8_t temporalLayers)
......@@ -69,29 +65,19 @@ namespace RTC
uint32_t rate{ 0u };
// clang-format off
for (
uint8_t spatialLayerIdx{ 0u };
(
spatialLayerIdx < this->spatialLayerCounters.size() &&
spatialLayerIdx <= spatialLayer
);
++spatialLayerIdx
)
// clang-format on
// Return 0 if specified layers are not being received.
{
auto& counter = this->spatialLayerCounters[spatialLayer][temporalLayer];
if (counter.GetBitrate(now) == 0)
return 0u;
}
for (uint8_t sIdx{ 0u }; sIdx <= spatialLayer; ++sIdx)
{
// clang-format off
for (
uint8_t temporalLayerIdx{ 0u };
(
temporalLayerIdx < this->spatialLayerCounters[spatialLayerIdx].size() &&
(spatialLayerIdx < spatialLayer || temporalLayerIdx <= temporalLayer)
);
++temporalLayerIdx
)
// clang-format on
for (uint8_t tIdx{ 0u }; tIdx <= temporalLayer; ++tIdx)
{
auto& temporalLayerCounter = this->spatialLayerCounters[spatialLayerIdx][temporalLayerIdx];
auto& temporalLayerCounter = this->spatialLayerCounters[sIdx][tIdx];
rate += temporalLayerCounter.GetBitrate(now);
}
......@@ -154,14 +140,15 @@ namespace RTC
if (this->params.useNack)
this->nackGenerator.reset(new RTC::NackGenerator(this));
// Set the RTP inactivity check periodic timer.
this->inactivityCheckPeriodicTimer = new Timer(this);
// Run the RTP inactivity periodic timer (unless DTX is enabled).
if (!this->params.useDtx)
{
this->inactive = false;
this->inactivityCheckPeriodicTimer->Start(InactivityCheckPeriod, InactivityCheckPeriod);
this->inactivityCheckPeriodicTimer = new Timer(this);
// First check on 2 seconds, then every 150 ms.
this->inactivityCheckPeriodicTimer->Start(2000, 150);
this->inactive = false;
this->lastPacketAt = DepLibUV::GetTime();
}
}
......@@ -238,21 +225,24 @@ namespace RTC
}
}
// Ensure the inactivityCheckPeriodicTimer runs (unless DTX is enabled).
if (!this->params.useDtx && !this->inactivityCheckPeriodicTimer->IsActive())
{
this->inactive = false;
this->inactivityCheckPeriodicTimer->Restart();
ResetScore(10, true);
}
// Calculate Jitter.
CalculateJitter(packet->GetTimestamp());
// Increase transmission counter.
this->transmissionCounter.Update(packet);
// Ensure the inactivityCheckPeriodicTimer runs.
if (this->inactivityCheckPeriodicTimer && this->inactive)
{
this->inactivityCheckPeriodicTimer->Restart();
this->inactive = false;
ResetScore(10, /*notify*/ true);
}
// Update last packet arrival.
this->lastPacketAt = DepLibUV::GetTime();
return true;
}
......@@ -337,6 +327,18 @@ namespace RTC
// Increase transmission counter.
this->transmissionCounter.Update(packet);
// Ensure the inactivityCheckPeriodicTimer runs.
if (this->inactivityCheckPeriodicTimer && this->inactive)
{
this->inactivityCheckPeriodicTimer->Restart();
this->inactive = false;
ResetScore(10, /*notify*/ true);
}
// Update last packet arrival.
this->lastPacketAt = DepLibUV::GetTime();
return true;
}
......@@ -498,19 +500,18 @@ namespace RTC
{
MS_TRACE();
this->inactive = true;
this->inactivityCheckPeriodicTimer->Stop();
if (this->inactivityCheckPeriodicTimer)
this->inactivityCheckPeriodicTimer->Stop();
}
void RtpStreamRecv::Resume()
{
MS_TRACE();
// Restart the RTP inactivity periodic timer (unless DTX is enabled).
if (!this->params.useDtx)
if (this->inactivityCheckPeriodicTimer && !this->inactive)
{
this->inactive = false;
this->inactivityCheckPeriodicTimer->Restart();
this->lastPacketAt = DepLibUV::GetTime();
}
}
......@@ -648,18 +649,17 @@ namespace RTC
if (timer == this->inactivityCheckPeriodicTimer)
{
auto now = DepLibUV::GetTime();
auto diff = DepLibUV::GetTime() - this->lastPacketAt;
// If no RTP is being received reset the score.
if (this->transmissionCounter.GetBitrate(now) == 0)
if (diff > 400)
{
this->inactive = true;
this->inactivityCheckPeriodicTimer->Stop();
this->inactive = true;
if (GetScore() != 0)
MS_WARN_2TAGS(rtp, score, "RTP inactivity detected, resetting score to 0");
ResetScore(0, true);
ResetScore(0, /*notify*/ true);
}
}
}
......
......@@ -82,7 +82,7 @@ namespace RTC
if (it != this->dropped.end())
{
MS_WARN_TAG(rtp, "trying to send a dropped input");
MS_DEBUG_DEV("trying to send a dropped input");
return false;
}
......
......@@ -21,6 +21,11 @@ namespace RTC
if (this->consumableRtpEncodings.size() != 1)
MS_THROW_TYPE_ERROR("invalid consumableRtpEncodings with size != 1");
auto& encoding = this->rtpParameters.encodings[0];
auto* mediaCodec = this->rtpParameters.GetCodecForEncoding(encoding);
this->keyFrameSupported = RTC::Codecs::CanBeKeyFrame(mediaCodec->mimeType);
// Create RtpStreamSend instance for sending a single stream to the remote.
CreateRtpStream();
}
......@@ -308,11 +313,7 @@ namespace RTC
this->syncRequired = true;
if (IsActive())
{
this->rtpStream->Resume();
RequestKeyFrame();
}
}
void SimpleConsumer::UserOnTransportDisconnected()
......@@ -336,11 +337,7 @@ namespace RTC
this->syncRequired = true;
if (IsActive())
{
this->rtpStream->Resume();
RequestKeyFrame();
}
}
void SimpleConsumer::CreateRtpStream()
......@@ -422,8 +419,6 @@ namespace RTC
if (rtxCodec && encoding.hasRtx)
this->rtpStream->SetRtx(rtxCodec->payloadType, encoding.rtx.ssrc);
this->keyFrameSupported = RTC::Codecs::CanBeKeyFrame(mediaCodec->mimeType);
}
void SimpleConsumer::RequestKeyFrame()
......
......@@ -70,7 +70,7 @@ namespace RTC
}
else
{
// Initially set preferreSpatialLayer and preferredTemporalLayer to the
// Initially set preferredSpatialLayer and preferredTemporalLayer to the
// maximum value.
this->preferredSpatialLayer = encoding.spatialLayers - 1;
this->preferredTemporalLayer = encoding.temporalLayers - 1;
......@@ -81,6 +81,24 @@ namespace RTC
this->producerRtpStreams.insert(
this->producerRtpStreams.begin(), this->consumableRtpEncodings.size(), nullptr);
// Create the encoding context.
auto* mediaCodec = this->rtpParameters.GetCodecForEncoding(encoding);
if (!RTC::Codecs::IsValidTypeForCodec(this->type, mediaCodec->mimeType))
{
MS_THROW_TYPE_ERROR(
"%s codec not supported for simulcast", mediaCodec->mimeType.ToString().c_str());
}
RTC::Codecs::EncodingContext::Params params;
params.spatialLayers = encoding.spatialLayers;
params.temporalLayers = encoding.temporalLayers;
this->encodingContext.reset(RTC::Codecs::GetEncodingContext(mediaCodec->mimeType, params));
MS_ASSERT(this->encodingContext, "no encoding context for this codec");
// Create RtpStreamSend instance for sending a single stream to the remote.
CreateRtpStream();
}
......@@ -118,10 +136,7 @@ namespace RTC
jsonObject["targetTemporalLayer"] = this->targetTemporalLayer;
// Add currentTemporalLayer.
if (this->encodingContext)
{
jsonObject["currentTemporalLayer"] = this->encodingContext->GetCurrentTemporalLayer();
}
jsonObject["currentTemporalLayer"] = this->encodingContext->GetCurrentTemporalLayer();
}
void SimulcastConsumer::FillJsonStats(json& jsonArray) const
......@@ -327,12 +342,10 @@ namespace RTC
int16_t prioritySpatialLayer{ 0 };
// Otherwise, take the maximum available spatial layer up to the preferred
// one.
for (size_t idx{ 0 }; idx < this->producerRtpStreams.size(); ++idx)
for (size_t sIdx{ 0 }; sIdx < this->producerRtpStreams.size(); ++sIdx)
{
auto spatialLayer = static_cast<int16_t>(idx);
auto* producerRtpStream = this->producerRtpStreams.at(idx);
auto spatialLayer = static_cast<int16_t>(sIdx);
auto* producerRtpStream = this->producerRtpStreams.at(sIdx);
// Ignore spatial layers for non existing Producer streams or for those
// with score 0.
......@@ -358,8 +371,11 @@ namespace RTC
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
this->provisionalTargetSpatialLayer = -1;
this->provisionalTargetTemporalLayer = -1;
if (!RTC::Consumer::IsActive())
return 0;
return 0u;
// Calculate virtual available bitrate based on given bitrate and our
// packet lost fraction.
......@@ -374,73 +390,74 @@ namespace RTC
else
virtualBitrate = bitrate;
this->provisionalTargetSpatialLayer = -1;
this->provisionalTargetTemporalLayer = -1;
uint32_t usedBitrate{ 0 };
uint8_t maxProducerScore{ 0 };
auto now = DepLibUV::GetTime();
for (size_t idx{ 0 }; idx < this->producerRtpStreams.size(); ++idx)
for (size_t sIdx{ 0 }; sIdx < this->producerRtpStreams.size(); ++sIdx)
{
auto spatialLayer = static_cast<int16_t>(idx);
auto* producerRtpStream = this->producerRtpStreams.at(idx);
auto spatialLayer = static_cast<int16_t>(sIdx);
auto* producerRtpStream = this->producerRtpStreams.at(sIdx);
auto producerScore = producerRtpStream ? producerRtpStream->GetScore() : 0;
// Ignore spatial layers for non existing Producer streams or for those
// Ignore spatial layers for non existing producer streams or for those
// with score 0.
if (producerScore == 0)
continue;
// We may not yet switch to a different spatial layer.
// We may not yet switch to this spatial layer.
if (!CanSwitchToSpatialLayer(spatialLayer))
continue;
if (producerScore >= maxProducerScore || producerScore >= 7)
if (producerScore < maxProducerScore && producerScore < 7)
continue;
int16_t temporalLayer{ 0 };
// Check bitrate of every temporal layer.
for (; temporalLayer < producerRtpStream->GetTemporalLayers(); ++temporalLayer)
{
int16_t temporalLayer{ 0 };
auto requiredBitrate = producerRtpStream->GetBitrate(now, 0, temporalLayer);
MS_DEBUG_DEV(
"testing layers %" PRIi16 ":%" PRIi16 " [virtualBitrate:%" PRIu32
", requiredBitrate:%" PRIu32 "]",
spatialLayer,
temporalLayer,
virtualBitrate,
requiredBitrate);
// If layer is not active move to next spatial layer.
if (requiredBitrate == 0)
break;
// Check bitrate of every layer.
for (; temporalLayer < producerRtpStream->GetTemporalLayers(); ++temporalLayer)
// If this layer requires more bitrate than the given one, abort the loop
// (so use the previous chosen layers if any).
if (requiredBitrate > virtualBitrate)
goto done;
// Set provisional layers and used bitrate.
this->provisionalTargetSpatialLayer = spatialLayer;
this->provisionalTargetTemporalLayer = temporalLayer;
usedBitrate = requiredBitrate;
// If this is the preferred spatial and temporal layer, exit the loops.
// clang-format off
if (
this->provisionalTargetSpatialLayer == this->preferredSpatialLayer &&
this->provisionalTargetTemporalLayer == this->preferredTemporalLayer &&
producerScore >= 7
)
// clang-format on
{
auto requiredBitrate = producerRtpStream->GetBitrate(now, 0, temporalLayer);
MS_DEBUG_DEV(
"testing layers %" PRIi16 ":%" PRIi16 " [virtualBitrate:%" PRIu32
", requiredBitrate:%" PRIu32 "]",
spatialLayer,
temporalLayer,
virtualBitrate,
requiredBitrate);
// If this layer requires more bitrate than the given one, abort the loop
// (so use the previous chosen layers if any).
if (requiredBitrate > virtualBitrate)
goto done;
// Set provisional layers and used bitrate.
this->provisionalTargetSpatialLayer = spatialLayer;
this->provisionalTargetTemporalLayer = temporalLayer;
usedBitrate = requiredBitrate;
// If this is the preferred spatial and temporal layer, exit the loops.
// clang-format off
if (
this->provisionalTargetSpatialLayer == this->preferredSpatialLayer &&
this->provisionalTargetTemporalLayer == this->preferredTemporalLayer &&
producerScore >= 7
)
// clang-format on
{
goto done;
}
goto done;
}
// If this is the preferred or higher spatial layer and has good score,
// take it and exit.
if (spatialLayer >= this->preferredSpatialLayer && producerScore >= 7)
break;
}
// If this is the preferred or higher spatial layer and has good score,
// take it and exit.
if (spatialLayer >= this->preferredSpatialLayer && producerScore >= 7)
break;
}
done:
......@@ -474,7 +491,7 @@ namespace RTC
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
if (!RTC::Consumer::IsActive())
return 0;
return 0u;
// If already in the preferred layers, do nothing.
// clang-format off
......@@ -484,7 +501,7 @@ namespace RTC
)
// clang-format on
{
return 0;
return 0u;
}
// Calculate virtual available bitrate based on given bitrate and our
......@@ -500,67 +517,81 @@ namespace RTC
else
virtualBitrate = bitrate;
auto spatialLayer = this->provisionalTargetSpatialLayer;
auto temporalLayer = this->provisionalTargetTemporalLayer;
RTC::RtpStream* producerRtpStream{ nullptr };
auto now = DepLibUV::GetTime();
uint32_t requiredBitrate{ 0u };
int16_t spatialLayer{ 0 };
int16_t temporalLayer{ 0 };
// May upgrade from no spatial layer to spatial layer 0.
if (spatialLayer == -1)
for (size_t sIdx{ 0 }; sIdx < this->producerRtpStreams.size(); ++sIdx)
{
// This can be null.
producerRtpStream = this->producerRtpStreams.at(0);
spatialLayer = static_cast<int16_t>(sIdx);
// Take it even if it's bad.
if (producerRtpStream && producerRtpStream->GetScore() > 0)
{
// We may not yet switch to a different spatial layer.
if (!CanSwitchToSpatialLayer(0))
return 0;
// Ignore spatial layers lower than the one we already have.
if (spatialLayer < this->provisionalTargetSpatialLayer)
continue;
spatialLayer = 0;
temporalLayer = 0;
}
else
{
// Must return now since we do not even have a producerRtpStream.
return 0;
}
}
// May upgrade temporal layer.
else if (temporalLayer < this->producerRtpStreams.at(spatialLayer)->GetTemporalLayers() - 1)
{
producerRtpStream = this->producerRtpStreams.at(spatialLayer);
++temporalLayer;
}
// May upgrade spatial layer.
else if (static_cast<size_t>(spatialLayer) < this->producerRtpStreams.size() - 1)
{
// This can be null.
producerRtpStream = this->producerRtpStreams.at(++spatialLayer);
auto* producerRtpStream = this->producerRtpStreams.at(spatialLayer);
// Producer stream does not exist or it's not good. Exit.
// Producer stream does not exist or it's not good. Ignore.
if (!producerRtpStream || producerRtpStream->GetScore() < 7)
return 0;
continue;
// We may not yet switch to a different spatial layer.
// We may not yet switch to this spatial layer.
if (!CanSwitchToSpatialLayer(spatialLayer))
return 0;
continue;
// Set temporal layer to 0.
temporalLayer = 0;
}
// Otherwise we cannot change anything.
else
{
return 0;
// Check bitrate of every temporal layer.
for (; temporalLayer < producerRtpStream->GetTemporalLayers(); ++temporalLayer)
{
// If this is the preferred spatial and temporal layer, exit the loops.
// clang-format off
if (
spatialLayer == this->preferredSpatialLayer &&
temporalLayer == this->preferredTemporalLayer
)
// clang-format on
{
goto done;
}
// Ignore temporal layers lower than the one we already have (taking into account
// the spatial layer too).
// clang-format off
if (
spatialLayer == this->provisionalTargetSpatialLayer &&
temporalLayer <= this->provisionalTargetTemporalLayer
)
// clang-format on
{
continue;
}
requiredBitrate = producerRtpStream->GetLayerBitrate(now, 0, temporalLayer);
// If active layer, end iterations here. Otherwise move to next spatial layer.
if (requiredBitrate)
goto done;
else
break;
}
// If this is the preferred or higher spatial layer, take it and exit.
if (spatialLayer >= this->preferredSpatialLayer)
break;
}
auto now = DepLibUV::GetTime();
auto requiredBitrate = producerRtpStream->GetLayerBitrate(now, 0, temporalLayer);
done:
// No higher active layers found.
if (!requiredBitrate)
return 0u;
// No luck.
if (requiredBitrate > virtualBitrate)
return 0;
return 0u;
// Set provisional layers.
this->provisionalTargetSpatialLayer = spatialLayer;
......@@ -616,6 +647,9 @@ namespace RTC
if (!IsActive())
return;
if (this->targetTemporalLayer == -1)
return;
auto payloadType = packet->GetPayloadType();
// NOTE: This may happen if this Consumer supports just some codecs of those
......@@ -633,22 +667,19 @@ namespace RTC
// the current spatial layer.
if (this->currentSpatialLayer != this->targetSpatialLayer && spatialLayer == this->targetSpatialLayer)
{
// Ignore if key frame is supported and this is not one.
if (this->keyFrameSupported && !packet->IsKeyFrame())
// Ignore if not a key frame.
if (!packet->IsKeyFrame())
return;
// Update current spatial layer.
this->currentSpatialLayer = this->targetSpatialLayer;
// Update target and current temporal layer.
if (this->encodingContext)
{
this->encodingContext->SetTargetTemporalLayer(this->targetTemporalLayer);
this->encodingContext->SetCurrentTemporalLayer(this->targetTemporalLayer);
}
this->encodingContext->SetTargetTemporalLayer(this->targetTemporalLayer);
this->encodingContext->SetCurrentTemporalLayer(packet->GetTemporalLayer());
// Reset the score of our RtpStream to 10.
this->rtpStream->ResetScore(10, false);
this->rtpStream->ResetScore(10, /*notify*/ false);
// Emit the layersChange event.
EmitLayersChange();
......@@ -665,9 +696,8 @@ namespace RTC
if (spatialLayer != this->currentSpatialLayer)
return;
// If we need to sync, support key frames and this is not a key frame, ignore
// the packet.
if (this->syncRequired && this->keyFrameSupported && !packet->IsKeyFrame())
// If we need to sync and this is not a key frame, ignore the packet.
if (this->syncRequired && !packet->IsKeyFrame())
return;
// Whether this is the first packet after re-sync.
......@@ -679,7 +709,7 @@ namespace RTC
if (packet->IsKeyFrame())
MS_DEBUG_TAG(rtp, "sync key frame received");
// Sync our RTP stream's sequence number and timestamp.
// Sync our RTP stream's sequence number.
this->rtpSeqManager.Sync(packet->GetSequenceNumber() - 1);
// Sync our RTP stream's RTP timestamp.
......@@ -746,38 +776,23 @@ namespace RTC
this->tsOffset);
}
if (this->encodingContext)
this->encodingContext->SyncRequired();
this->encodingContext->SyncRequired();
this->syncRequired = false;
}
int16_t previousTemporalLayer{ 0 };
if (this->encodingContext)
previousTemporalLayer = this->encodingContext->GetCurrentTemporalLayer();
auto previousTemporalLayer = this->encodingContext->GetCurrentTemporalLayer();
// Rewrite payload if needed. Drop packet if necessary.
if (this->encodingContext && !packet->ProcessPayload(this->encodingContext.get()))
if (!packet->ProcessPayload(this->encodingContext.get()))
{
this->rtpSeqManager.Drop(packet->GetSequenceNumber());
return;
}
// Update current temporal layer if the packet honors the target temporal layer
// (just if this packet belongs to the target spatial layer).
// clang-format off
if (
this->encodingContext &&
this->currentSpatialLayer == this->targetSpatialLayer &&
previousTemporalLayer != this->targetTemporalLayer &&
this->encodingContext->GetCurrentTemporalLayer() == this->targetTemporalLayer
)
// clang-format on
{
if (previousTemporalLayer != this->encodingContext->GetCurrentTemporalLayer())
EmitLayersChange();
}
// Update RTP seq number and timestamp based on NTP offset.
uint16_t seq;
......@@ -881,8 +896,7 @@ namespace RTC
packet->SetTimestamp(origTimestamp);
// Restore the original payload if needed.
if (this->encodingContext)
packet->RestorePayload();
packet->RestorePayload();
}
void SimulcastConsumer::SendProbationRtpPacket(uint16_t seq)
......@@ -1094,10 +1108,6 @@ namespace RTC
if (rtxCodec && encoding.hasRtx)
this->rtpStream->SetRtx(rtxCodec->payloadType, encoding.rtx.ssrc);
this->keyFrameSupported = RTC::Codecs::CanBeKeyFrame(mediaCodec->mimeType);
this->encodingContext.reset(RTC::Codecs::GetEncodingContext(mediaCodec->mimeType));
}
void SimulcastConsumer::RequestKeyFrames()
......@@ -1196,10 +1206,10 @@ namespace RTC
uint8_t maxProducerScore{ 0 };
for (size_t idx{ 0 }; idx < this->producerRtpStreams.size(); ++idx)
for (size_t sIdx{ 0 }; sIdx < this->producerRtpStreams.size(); ++sIdx)
{
auto spatialLayer = static_cast<int16_t>(idx);
auto* producerRtpStream = this->producerRtpStreams.at(idx);
auto spatialLayer = static_cast<int16_t>(sIdx);
auto* producerRtpStream = this->producerRtpStreams.at(sIdx);
auto producerScore = producerRtpStream ? producerRtpStream->GetScore() : 0;
// Ignore spatial layers for non existing Producer streams or for those
......@@ -1207,20 +1217,20 @@ namespace RTC
if (producerScore == 0)
continue;
// We may not yet switch to a different spatial layer.
// We may not yet switch to this spatial layer.
if (!CanSwitchToSpatialLayer(spatialLayer))
continue;
if (producerScore >= maxProducerScore || producerScore >= 7)
{
newTargetSpatialLayer = spatialLayer;
maxProducerScore = producerScore;
if (producerScore < maxProducerScore && producerScore < 7)
continue;
// If this is the preferred or higher spatial layer and has good score,
// take it and exit.
if (spatialLayer >= this->preferredSpatialLayer && producerScore >= 7)
break;
}
newTargetSpatialLayer = spatialLayer;
maxProducerScore = producerScore;
// If this is the preferred or higher spatial layer and has good score,
// take it and exit.
if (spatialLayer >= this->preferredSpatialLayer && producerScore >= 7)
break;
}
if (newTargetSpatialLayer != -1)
......@@ -1262,18 +1272,11 @@ namespace RTC
this->targetTemporalLayer = -1;
this->currentSpatialLayer = -1;
if (this->encodingContext)
{
this->encodingContext->SetTargetTemporalLayer(-1);
this->encodingContext->SetCurrentTemporalLayer(-1);
}
this->encodingContext->SetTargetTemporalLayer(-1);
this->encodingContext->SetCurrentTemporalLayer(-1);
MS_DEBUG_TAG(
simulcast,
"target layers changed [spatial:%" PRIi16 ", temporal:%" PRIi16 ", consumerId:%s]",
this->targetSpatialLayer,
this->targetTemporalLayer,
this->id.c_str());
simulcast, "target layers changed [spatial:-1, temporal:-1, consumerId:%s]", this->id.c_str());
EmitLayersChange();
......@@ -1285,7 +1288,7 @@ namespace RTC
// If the new target spatial layer matches the current one, apply the new
// target temporal layer now.
if (this->encodingContext && this->targetSpatialLayer == this->currentSpatialLayer)
if (this->targetSpatialLayer == this->currentSpatialLayer)
this->encodingContext->SetTargetTemporalLayer(this->targetTemporalLayer);
MS_DEBUG_TAG(
......@@ -1348,18 +1351,15 @@ namespace RTC
MS_DEBUG_DEV(
"current layers changed to [spatial:%" PRIi16 ", temporal:%" PRIi16 ", consumerId:%s]",
this->currentSpatialLayer,
this->encodingContext ? this->encodingContext->GetCurrentTemporalLayer()
: static_cast<int16_t>(0),
this->encodingContext->GetCurrentTemporalLayer(),
this->id.c_str());
json data = json::object();
if (this->currentSpatialLayer >= 0)
{
data["spatialLayer"] = this->currentSpatialLayer;
if (this->encodingContext)
data["temporalLayer"] = this->encodingContext->GetCurrentTemporalLayer();
data["spatialLayer"] = this->currentSpatialLayer;
data["temporalLayer"] = this->encodingContext->GetCurrentTemporalLayer();
}
else
{
......
......@@ -324,7 +324,7 @@ namespace RTC
{
MS_TRACE();
MS_DEBUG_DEV("<StunMessage>");
MS_DUMP("<StunMessage>");
std::string klass;
switch (this->klass)
......@@ -344,15 +344,14 @@ namespace RTC
}
if (this->method == Method::BINDING)
{
MS_DEBUG_DEV(" Binding %s", klass.c_str());
MS_DUMP(" Binding %s", klass.c_str());
}
else
{
// This prints the unknown method number. Example: TURN Allocate => 0x003.
MS_DEBUG_DEV(
" %s with unknown method %#.3x", klass.c_str(), static_cast<uint16_t>(this->method));
MS_DUMP(" %s with unknown method %#.3x", klass.c_str(), static_cast<uint16_t>(this->method));
}
MS_DEBUG_DEV(" size: %zu bytes", this->size);
MS_DUMP(" size: %zu bytes", this->size);
static char transactionId[25];
......@@ -361,19 +360,19 @@ namespace RTC
// NOTE: n must be 3 because snprintf adds a \0 after printed chars.
std::snprintf(transactionId + (i * 2), 3, "%.2x", this->transactionId[i]);
}
MS_DEBUG_DEV(" transactionId: %s", transactionId);
MS_DUMP(" transactionId: %s", transactionId);
if (this->errorCode != 0u)
MS_DEBUG_DEV(" errorCode: %" PRIu16, this->errorCode);
MS_DUMP(" errorCode: %" PRIu16, this->errorCode);
if (!this->username.empty())
MS_DEBUG_DEV(" username: %s", this->username.c_str());
MS_DUMP(" username: %s", this->username.c_str());
if (this->priority != 0u)
MS_DEBUG_DEV(" priority: %" PRIu32, this->priority);
MS_DUMP(" priority: %" PRIu32, this->priority);
if (this->iceControlling != 0u)
MS_DEBUG_DEV(" iceControlling: %" PRIu64, this->iceControlling);
MS_DUMP(" iceControlling: %" PRIu64, this->iceControlling);
if (this->iceControlled != 0u)
MS_DEBUG_DEV(" iceControlled: %" PRIu64, this->iceControlled);
MS_DUMP(" iceControlled: %" PRIu64, this->iceControlled);
if (this->hasUseCandidate)
MS_DEBUG_DEV(" useCandidate");
MS_DUMP(" useCandidate");
if (this->xorMappedAddress != nullptr)
{
int family;
......@@ -382,7 +381,7 @@ namespace RTC
Utils::IP::GetAddressInfo(this->xorMappedAddress, family, ip, port);
MS_DEBUG_DEV(" xorMappedAddress: %s : %" PRIu16, ip.c_str(), port);
MS_DUMP(" xorMappedAddress: %s : %" PRIu16, ip.c_str(), port);
}
if (this->messageIntegrity != nullptr)
{
......@@ -393,12 +392,12 @@ namespace RTC
std::snprintf(messageIntegrity + (i * 2), 3, "%.2x", this->messageIntegrity[i]);
}
MS_DEBUG_DEV(" messageIntegrity: %s", messageIntegrity);
MS_DUMP(" messageIntegrity: %s", messageIntegrity);
}
if (this->hasFingerprint)
MS_DEBUG_DEV(" has fingerprint");
MS_DUMP(" has fingerprint");
MS_DEBUG_DEV("</StunMessage>");
MS_DUMP("</StunMessage>");
}
StunMessage::Authentication StunMessage::CheckAuthentication(
......
#define MS_CLASS "RTC::SvcConsumer"
// #define MS_LOG_DEV
#include "RTC/SvcConsumer.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Channel/Notifier.hpp"
#include "RTC/Codecs/Codecs.hpp"
namespace RTC
{
/* Instance methods. */
SvcConsumer::SvcConsumer(const std::string& id, RTC::Consumer::Listener* listener, json& data)
: RTC::Consumer::Consumer(id, listener, data, RTC::RtpParameters::Type::SVC)
{
MS_TRACE();
// Ensure there is a single encoding.
if (this->consumableRtpEncodings.size() != 1)
MS_THROW_TYPE_ERROR("invalid consumableRtpEncodings with size != 1");
auto& encoding = this->rtpParameters.encodings[0];
// Ensure there are multiple spatial or temporal layers.
if (encoding.spatialLayers < 2 && encoding.temporalLayers < 2)
MS_THROW_TYPE_ERROR("invalid number of layers");
auto jsonPreferredLayersIt = data.find("preferredLayers");
// Set preferredLayers (if given).
if (jsonPreferredLayersIt != data.end() && jsonPreferredLayersIt->is_object())
{
auto jsonSpatialLayerIt = jsonPreferredLayersIt->find("spatialLayer");
auto jsonTemporalLayerIt = jsonPreferredLayersIt->find("temporalLayer");
if (jsonSpatialLayerIt == jsonPreferredLayersIt->end() || !jsonSpatialLayerIt->is_number_unsigned())
{
MS_THROW_TYPE_ERROR("missing preferredLayers.spatialLayer");
}
this->preferredSpatialLayer = jsonSpatialLayerIt->get<int16_t>();
if (this->preferredSpatialLayer > encoding.spatialLayers - 1)
this->preferredSpatialLayer = encoding.spatialLayers - 1;
if (jsonTemporalLayerIt != jsonPreferredLayersIt->end() && jsonTemporalLayerIt->is_number_unsigned())
{
this->preferredTemporalLayer = jsonTemporalLayerIt->get<int16_t>();
if (this->preferredTemporalLayer > encoding.temporalLayers - 1)
this->preferredTemporalLayer = encoding.temporalLayers - 1;
}
else
{
this->preferredTemporalLayer = encoding.temporalLayers - 1;
}
}
else
{
// Initially set preferredSpatialLayer and preferredTemporalLayer to the
// maximum value.
this->preferredSpatialLayer = encoding.spatialLayers - 1;
this->preferredTemporalLayer = encoding.temporalLayers - 1;
}
// Create the encoding context.
auto* mediaCodec = this->rtpParameters.GetCodecForEncoding(encoding);
if (!RTC::Codecs::IsValidTypeForCodec(this->type, mediaCodec->mimeType))
{
MS_THROW_TYPE_ERROR("%s codec not supported for svc", mediaCodec->mimeType.ToString().c_str());
}
RTC::Codecs::EncodingContext::Params params;
params.spatialLayers = encoding.spatialLayers;
params.temporalLayers = encoding.temporalLayers;
params.ksvc = encoding.ksvc;
this->encodingContext.reset(RTC::Codecs::GetEncodingContext(mediaCodec->mimeType, params));
MS_ASSERT(this->encodingContext, "no encoding context for this codec");
// Create RtpStreamSend instance for sending a single stream to the remote.
CreateRtpStream();
}
SvcConsumer::~SvcConsumer()
{
MS_TRACE();
delete this->rtpStream;
}
void SvcConsumer::FillJson(json& jsonObject) const
{
MS_TRACE();
// Call the parent method.
RTC::Consumer::FillJson(jsonObject);
// Add rtpStream.
this->rtpStream->FillJson(jsonObject["rtpStream"]);
// Add preferredSpatialLayer.
jsonObject["preferredSpatialLayer"] = this->preferredSpatialLayer;
// Add targetSpatialLayer.
jsonObject["targetSpatialLayer"] = this->encodingContext->GetTargetSpatialLayer();
// Add currentSpatialLayer.
jsonObject["currentSpatialLayer"] = this->encodingContext->GetCurrentSpatialLayer();
// Add preferredTemporalLayer.
jsonObject["preferredTemporalLayer"] = this->preferredTemporalLayer;
// Add targetTemporalLayer.
jsonObject["targetTemporalLayer"] = this->encodingContext->GetTargetTemporalLayer();
// Add currentTemporalLayer.
jsonObject["currentTemporalLayer"] = this->encodingContext->GetCurrentTemporalLayer();
}
void SvcConsumer::FillJsonStats(json& jsonArray) const
{
MS_TRACE();
// Add stats of our send stream.
jsonArray.emplace_back(json::value_t::object);
this->rtpStream->FillJsonStats(jsonArray[0]);
// Add stats of our recv stream.
if (this->producerRtpStream)
{
jsonArray.emplace_back(json::value_t::object);
this->producerRtpStream->FillJsonStats(jsonArray[1]);
}
}
void SvcConsumer::FillJsonScore(json& jsonObject) const
{
MS_TRACE();
jsonObject["score"] = this->rtpStream->GetScore();
if (this->producerRtpStream)
jsonObject["producerScore"] = this->producerRtpStream->GetScore();
else
jsonObject["producerScore"] = 0;
}
void SvcConsumer::HandleRequest(Channel::Request* request)
{
MS_TRACE();
switch (request->methodId)
{
case Channel::Request::MethodId::CONSUMER_REQUEST_KEY_FRAME:
{
if (IsActive())
RequestKeyFrame();
request->Accept();
break;
}
case Channel::Request::MethodId::CONSUMER_SET_PREFERRED_LAYERS:
{
auto previousPreferredSpatialLayer = this->preferredSpatialLayer;
auto previousPreferredTemporalLayer = this->preferredTemporalLayer;
auto jsonSpatialLayerIt = request->data.find("spatialLayer");
auto jsonTemporalLayerIt = request->data.find("temporalLayer");
// Spatial layer.
if (jsonSpatialLayerIt == request->data.end() || !jsonSpatialLayerIt->is_number_unsigned())
{
MS_THROW_TYPE_ERROR("missing spatialLayer");
}
this->preferredSpatialLayer = jsonSpatialLayerIt->get<int16_t>();
if (this->preferredSpatialLayer > this->rtpStream->GetSpatialLayers() - 1)
this->preferredSpatialLayer = this->rtpStream->GetSpatialLayers() - 1;
// preferredTemporaLayer is optional.
if (jsonTemporalLayerIt != request->data.end() && jsonTemporalLayerIt->is_number_unsigned())
{
this->preferredTemporalLayer = jsonTemporalLayerIt->get<int16_t>();
if (this->preferredTemporalLayer > this->rtpStream->GetTemporalLayers() - 1)
this->preferredTemporalLayer = this->rtpStream->GetTemporalLayers() - 1;
}
else
{
this->preferredTemporalLayer = this->rtpStream->GetTemporalLayers() - 1;
}
MS_DEBUG_DEV(
"preferred layers changed to [spatial:%" PRIi16 ", temporal:%" PRIi16 ", consumerId:%s]",
this->preferredSpatialLayer,
this->preferredTemporalLayer,
this->id.c_str());
request->Accept();
// clang-format off
if (
IsActive() &&
(
this->preferredSpatialLayer != previousPreferredSpatialLayer ||
this->preferredTemporalLayer != previousPreferredTemporalLayer
)
)
// clang-format on
{
MayChangeLayers(/*force*/ true);
}
break;
}
default:
{
// Pass it to the parent class.
RTC::Consumer::HandleRequest(request);
}
}
}
void SvcConsumer::ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t /*mappedSsrc*/)
{
MS_TRACE();
this->producerRtpStream = rtpStream;
// Emit the score event.
EmitScore();
}
void SvcConsumer::ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t /*mappedSsrc*/)
{
MS_TRACE();
this->producerRtpStream = rtpStream;
// Request a key frame.
RequestKeyFrame();
// Emit the score event.
EmitScore();
if (IsActive())
MayChangeLayers();
}
void SvcConsumer::ProducerRtpStreamScore(
RTC::RtpStream* /*rtpStream*/, uint8_t score, uint8_t previousScore)
{
MS_TRACE();
// Emit score event.
EmitScore();
if (RTC::Consumer::IsActive())
{
// Just check target layers if the stream has died or reborned.
//
// clang-format off
if (
!this->externallyManagedBitrate ||
(score == 0 || previousScore == 0)
)
// clang-format on
{
MayChangeLayers();
}
}
}
void SvcConsumer::ProducerRtcpSenderReport(RTC::RtpStream* rtpStream, bool first)
{
MS_TRACE();
// Just interested if this is the first Sender Report for a RTP stream.
if (first)
MS_DEBUG_TAG(svc, "first SenderReport [ssrc:%" PRIu32 "]", rtpStream->GetSsrc());
else
return;
// If our RTP stream does not yet have SR, do nothing since
// we know we won't be able to switch.
if (!this->producerRtpStream || !this->producerRtpStream->GetSenderReportNtpMs())
return;
if (IsActive())
MayChangeLayers();
}
void SvcConsumer::SetExternallyManagedBitrate()
{
MS_TRACE();
this->externallyManagedBitrate = true;
}
int16_t SvcConsumer::GetBitratePriority() const
{
MS_TRACE();
if (!RTC::Consumer::IsActive())
return 0;
// Return a 0 priority if score of Producer stream is 0.
if (!this->producerRtpStream || this->producerRtpStream->GetScore() == 0)
return 0;
int16_t spatialLayer{ 0 };
int16_t prioritySpatialLayer{ 0 };
for (; spatialLayer < this->producerRtpStream->GetSpatialLayers(); ++spatialLayer)
{
// Do not choose a layer greater than the preferred one if we already found
// an available layer equal or less than the preferred one.
if (spatialLayer > this->preferredSpatialLayer && prioritySpatialLayer >= -1)
break;
// Choose this layer for now.
prioritySpatialLayer = spatialLayer;
}
// Return the choosen spatial layer plus one.
return prioritySpatialLayer + 1;
}
uint32_t SvcConsumer::UseAvailableBitrate(uint32_t bitrate)
{
MS_TRACE();
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
this->provisionalTargetSpatialLayer = -1;
this->provisionalTargetTemporalLayer = -1;
if (!RTC::Consumer::IsActive())
return 0u;
// Calculate virtual available bitrate based on given bitrate and our
// packet lost fraction.
uint32_t virtualBitrate;
auto lossPercentage = this->rtpStream->GetLossPercentage();
// TODO: We may have to not consider fraction lost with Transport-CC.
if (lossPercentage < 2)
virtualBitrate = 1.08 * bitrate;
else if (lossPercentage > 10)
virtualBitrate = (1 - 0.5 * (lossPercentage / 100)) * bitrate;
else
virtualBitrate = bitrate;
uint32_t usedBitrate{ 0 };
auto now = DepLibUV::GetTime();
int16_t spatialLayer{ 0 };
if (!this->producerRtpStream)
goto done;
if (this->producerRtpStream->GetScore() == 0)
goto done;
for (; spatialLayer < this->producerRtpStream->GetSpatialLayers(); ++spatialLayer)
{
int16_t temporalLayer{ 0 };
// Check bitrate of every temporal layer.
for (; temporalLayer < this->producerRtpStream->GetTemporalLayers(); ++temporalLayer)
{
auto requiredBitrate = this->producerRtpStream->GetBitrate(now, spatialLayer, temporalLayer);
MS_DEBUG_DEV(
"testing layers %" PRIi16 ":%" PRIi16 " [virtualBitrate:%" PRIu32
", requiredBitrate:%" PRIu32 "]",
spatialLayer,
temporalLayer,
virtualBitrate,
requiredBitrate);
// If layer is not active move to next spatial layer.
if (requiredBitrate == 0)
break;
// If this layer requires more bitrate than the given one, abort the loop
// (so use the previous chosen layers if any).
if (requiredBitrate > virtualBitrate)
goto done;
// Set provisional layers and used bitrate.
this->provisionalTargetSpatialLayer = spatialLayer;
this->provisionalTargetTemporalLayer = temporalLayer;
usedBitrate = requiredBitrate;
// If this is the preferred spatial and temporal layer, exit the loops.
// clang-format off
if (
this->provisionalTargetSpatialLayer == this->preferredSpatialLayer &&
this->provisionalTargetTemporalLayer == this->preferredTemporalLayer
)
// clang-format on
{
goto done;
}
}
// If this is the preferred or higher spatial layer, take it and exit.
if (spatialLayer >= this->preferredSpatialLayer)
break;
}
done:
MS_DEBUG_2TAGS(
bwe,
svc,
"choosing layers %" PRIi16 ":%" PRIi16 " [bitrate:%" PRIu32 ", virtualBitrate:%" PRIu32
", usedBitrate:%" PRIu32 ", consumerId:%s]",
this->provisionalTargetSpatialLayer,
this->provisionalTargetTemporalLayer,
bitrate,
virtualBitrate,
usedBitrate,
this->id.c_str());
// Must recompute usedBitrate based on given bitrate, virtualBitrate and
// usedBitrate.
if (usedBitrate <= bitrate)
return usedBitrate;
else if (usedBitrate <= virtualBitrate)
return bitrate;
else
return usedBitrate;
}
uint32_t SvcConsumer::IncreaseLayer(uint32_t bitrate)
{
MS_TRACE();
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
if (!RTC::Consumer::IsActive())
return 0u;
if (!this->producerRtpStream)
return 0u;
if (this->producerRtpStream->GetScore() == 0)
return 0u;
// If already in the preferred layers, do nothing.
// clang-format off
if (
this->provisionalTargetSpatialLayer == this->preferredSpatialLayer &&
this->provisionalTargetTemporalLayer == this->preferredTemporalLayer
)
// clang-format on
{
return 0u;
}
// Calculate virtual available bitrate based on given bitrate and our
// packet lost fraction.
uint32_t virtualBitrate;
auto lossPercentage = this->rtpStream->GetLossPercentage();
// TODO: We may have to not consider fraction lost with Transport-CC.
if (lossPercentage < 2)
virtualBitrate = 1.08 * bitrate;
else if (lossPercentage > 10)
virtualBitrate = (1 - 0.5 * (lossPercentage / 100)) * bitrate;
else
virtualBitrate = bitrate;
auto now = DepLibUV::GetTime();
uint32_t requiredBitrate{ 0u };
int16_t spatialLayer{ 0 };
int16_t temporalLayer{ 0 };
for (; spatialLayer < this->producerRtpStream->GetSpatialLayers(); ++spatialLayer)
{
// Ignore spatial layers lower than the one we already have.
if (spatialLayer < this->provisionalTargetSpatialLayer)
continue;
temporalLayer = 0;
// Check bitrate of every temporal layer.
for (; temporalLayer < this->producerRtpStream->GetTemporalLayers(); ++temporalLayer)
{
// If this is the preferred spatial and temporal layer, exit the loops.
// clang-format off
if (
spatialLayer == this->preferredSpatialLayer &&
temporalLayer == this->preferredTemporalLayer
)
// clang-format on
{
goto done;
}
// Ignore temporal layers lower than the one we already have (taking into account
// the spatial layer too).
// clang-format off
if (
spatialLayer == this->provisionalTargetSpatialLayer &&
temporalLayer <= this->provisionalTargetTemporalLayer
)
// clang-format on
{
continue;
}
requiredBitrate = producerRtpStream->GetLayerBitrate(now, spatialLayer, temporalLayer);
// If active layer, end iterations here. Otherwise move to next spatial layer.
if (requiredBitrate)
goto done;
else
break;
}
// If this is the preferred or higher spatial layer, take it and exit.
if (spatialLayer >= this->preferredSpatialLayer)
break;
}
done:
// No higher active layers found.
if (!requiredBitrate)
return 0u;
// No luck.
if (requiredBitrate > virtualBitrate)
return 0u;
// Set provisional layers.
this->provisionalTargetSpatialLayer = spatialLayer;
this->provisionalTargetTemporalLayer = temporalLayer;
MS_DEBUG_DEV(
"upgrading to layers %" PRIi16 ":%" PRIi16 " [virtualBitrate:%" PRIu32
", requiredBitrate:%" PRIu32 "]",
this->provisionalTargetSpatialLayer,
this->provisionalTargetTemporalLayer,
virtualBitrate,
requiredBitrate);
if (requiredBitrate <= bitrate)
return requiredBitrate;
else if (requiredBitrate <= virtualBitrate)
return bitrate;
else
return requiredBitrate; // NOTE: This cannot happen.
}
void SvcConsumer::ApplyLayers()
{
MS_TRACE();
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
auto provisionalTargetSpatialLayer = this->provisionalTargetSpatialLayer;
auto provisionalTargetTemporalLayer = this->provisionalTargetTemporalLayer;
// Reset provisional target layers.
this->provisionalTargetSpatialLayer = -1;
this->provisionalTargetTemporalLayer = -1;
if (!RTC::Consumer::IsActive())
return;
// clang-format off
if (
provisionalTargetSpatialLayer != this->encodingContext->GetTargetSpatialLayer() ||
provisionalTargetTemporalLayer != this->encodingContext->GetTargetTemporalLayer()
)
// clang-format on
{
UpdateTargetLayers(provisionalTargetSpatialLayer, provisionalTargetTemporalLayer);
}
}
void SvcConsumer::SendRtpPacket(RTC::RtpPacket* packet)
{
MS_TRACE();
if (!IsActive())
return;
// clang-format off
if (
this->encodingContext->GetTargetSpatialLayer() == -1 ||
this->encodingContext->GetTargetTemporalLayer() == -1
)
// clang-format on
{
return;
}
auto payloadType = packet->GetPayloadType();
// NOTE: This may happen if this Consumer supports just some codecs of those
// in the corresponding Producer.
if (this->supportedCodecPayloadTypes.find(payloadType) == this->supportedCodecPayloadTypes.end())
{
MS_DEBUG_DEV("payload type not supported [payloadType:%" PRIu8 "]", payloadType);
return;
}
// If we need to sync and this is not a key frame, ignore the packet.
if (this->syncRequired && !packet->IsKeyFrame())
return;
// Whether this is the first packet after re-sync.
bool isSyncPacket = this->syncRequired;
// Sync sequence number and timestamp if required.
if (isSyncPacket)
{
if (packet->IsKeyFrame())
MS_DEBUG_TAG(rtp, "sync key frame received");
this->rtpSeqManager.Sync(packet->GetSequenceNumber() - 1);
this->syncRequired = false;
}
auto previousSpatialLayer = this->encodingContext->GetCurrentSpatialLayer();
auto previousTemporalLayer = this->encodingContext->GetCurrentTemporalLayer();
if (!packet->ProcessPayload(this->encodingContext.get()))
{
this->rtpSeqManager.Drop(packet->GetSequenceNumber());
return;
}
// clang-format off
if (
previousSpatialLayer != this->encodingContext->GetCurrentSpatialLayer() ||
previousTemporalLayer != this->encodingContext->GetCurrentTemporalLayer()
)
// clang-format on
{
// Emit the layersChange event.
EmitLayersChange();
}
// Update RTP seq number and timestamp based on NTP offset.
uint16_t seq;
this->rtpSeqManager.Input(packet->GetSequenceNumber(), seq);
// Save original packet fields.
auto origSsrc = packet->GetSsrc();
auto origSeq = packet->GetSequenceNumber();
// Rewrite packet.
packet->SetSsrc(this->rtpParameters.encodings[0].ssrc);
packet->SetSequenceNumber(seq);
if (isSyncPacket)
{
MS_DEBUG_TAG(
rtp,
"sending sync packet [ssrc:%" PRIu32 ", seq:%" PRIu16 ", ts:%" PRIu32
"] from original [seq:%" PRIu16 "]",
packet->GetSsrc(),
packet->GetSequenceNumber(),
packet->GetTimestamp(),
origSeq);
}
// Process the packet.
if (this->rtpStream->ReceivePacket(packet))
{
// Send the packet.
this->listener->OnConsumerSendRtpPacket(this, packet);
}
else
{
MS_WARN_TAG(
rtp,
"failed to send packet [ssrc:%" PRIu32 ", seq:%" PRIu16 ", ts:%" PRIu32
"] from original [ssrc:%" PRIu32 ", seq:%" PRIu16 "]",
packet->GetSsrc(),
packet->GetSequenceNumber(),
packet->GetTimestamp(),
origSsrc,
origSeq);
}
// Restore packet fields.
packet->SetSsrc(origSsrc);
packet->SetSequenceNumber(origSeq);
// Restore the original payload if needed.
packet->RestorePayload();
}
void SvcConsumer::SendProbationRtpPacket(uint16_t seq)
{
MS_TRACE();
this->rtpStream->SendProbationRtpPacket(seq);
}
void SvcConsumer::GetRtcp(RTC::RTCP::CompoundPacket* packet, RTC::RtpStreamSend* rtpStream, uint64_t now)
{
MS_TRACE();
MS_ASSERT(rtpStream == this->rtpStream, "RTP stream does not match");
if (static_cast<float>((now - this->lastRtcpSentTime) * 1.15) < this->maxRtcpInterval)
return;
auto* report = this->rtpStream->GetRtcpSenderReport(now);
if (!report)
return;
packet->AddSenderReport(report);
// Build SDES chunk for this sender.
auto* sdesChunk = this->rtpStream->GetRtcpSdesChunk();
packet->AddSdesChunk(sdesChunk);
this->lastRtcpSentTime = now;
}
void SvcConsumer::NeedWorstRemoteFractionLost(uint32_t /*mappedSsrc*/, uint8_t& worstRemoteFractionLost)
{
MS_TRACE();
if (!IsActive())
return;
auto fractionLost = this->rtpStream->GetFractionLost();
// If our fraction lost is worse than the given one, update it.
if (fractionLost > worstRemoteFractionLost)
worstRemoteFractionLost = fractionLost;
}
void SvcConsumer::ReceiveNack(RTC::RTCP::FeedbackRtpNackPacket* nackPacket)
{
MS_TRACE();
if (!IsActive())
return;
this->rtpStream->ReceiveNack(nackPacket);
}
void SvcConsumer::ReceiveKeyFrameRequest(
RTC::RTCP::FeedbackPs::MessageType messageType, uint32_t /*ssrc*/)
{
MS_TRACE();
this->rtpStream->ReceiveKeyFrameRequest(messageType);
if (IsActive())
RequestKeyFrame();
}
void SvcConsumer::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report)
{
MS_TRACE();
this->rtpStream->ReceiveRtcpReceiverReport(report);
}
uint32_t SvcConsumer::GetTransmissionRate(uint64_t now)
{
MS_TRACE();
if (!IsActive())
return 0u;
return this->rtpStream->GetBitrate(now);
}
void SvcConsumer::UserOnTransportConnected()
{
MS_TRACE();
this->syncRequired = true;
if (IsActive())
MayChangeLayers();
}
void SvcConsumer::UserOnTransportDisconnected()
{
MS_TRACE();
this->rtpStream->Pause();
UpdateTargetLayers(-1, -1);
}
void SvcConsumer::UserOnPaused()
{
MS_TRACE();
this->rtpStream->Pause();
UpdateTargetLayers(-1, -1);
// Tell the transport so it can distribute available bitrate into other
// consumers.
if (this->externallyManagedBitrate)
this->listener->OnConsumerNeedBitrateChange(this);
}
void SvcConsumer::UserOnResumed()
{
MS_TRACE();
this->syncRequired = true;
if (IsActive())
MayChangeLayers();
}
void SvcConsumer::CreateRtpStream()
{
MS_TRACE();
auto& encoding = this->rtpParameters.encodings[0];
auto* mediaCodec = this->rtpParameters.GetCodecForEncoding(encoding);
MS_DEBUG_TAG(
rtp, "[ssrc:%" PRIu32 ", payloadType:%" PRIu8 "]", encoding.ssrc, mediaCodec->payloadType);
// Set stream params.
RTC::RtpStream::Params params;
params.ssrc = encoding.ssrc;
params.payloadType = mediaCodec->payloadType;
params.mimeType = mediaCodec->mimeType;
params.clockRate = mediaCodec->clockRate;
params.cname = this->rtpParameters.rtcp.cname;
params.spatialLayers = encoding.spatialLayers;
params.temporalLayers = encoding.temporalLayers;
// Check in band FEC in codec parameters.
if (mediaCodec->parameters.HasInteger("useinbandfec") && mediaCodec->parameters.GetInteger("useinbandfec") == 1)
{
MS_DEBUG_TAG(rtp, "in band FEC enabled");
params.useInBandFec = true;
}
// Check DTX in codec parameters.
if (mediaCodec->parameters.HasInteger("usedtx") && mediaCodec->parameters.GetInteger("usedtx") == 1)
{
MS_DEBUG_TAG(rtp, "DTX enabled");
params.useDtx = true;
}
// Check DTX in the encoding.
if (encoding.dtx)
{
MS_DEBUG_TAG(rtp, "DTX enabled");
params.useDtx = true;
}
for (auto& fb : mediaCodec->rtcpFeedback)
{
if (!params.useNack && fb.type == "nack" && fb.parameter == "")
{
MS_DEBUG_2TAGS(rtp, rtcp, "NACK supported");
params.useNack = true;
}
else if (!params.usePli && fb.type == "nack" && fb.parameter == "pli")
{
MS_DEBUG_2TAGS(rtp, rtcp, "PLI supported");
params.usePli = true;
}
else if (!params.useFir && fb.type == "ccm" && fb.parameter == "fir")
{
MS_DEBUG_2TAGS(rtp, rtcp, "FIR supported");
params.useFir = true;
}
}
// Create a RtpStreamSend for sending a single media stream.
size_t bufferSize = params.useNack ? 600 : 0;
this->rtpStream = new RTC::RtpStreamSend(this, params, bufferSize);
this->rtpStreams.push_back(this->rtpStream);
// If the Consumer is paused, tell the RtpStreamSend.
if (IsPaused() || IsProducerPaused())
this->rtpStream->Pause();
auto* rtxCodec = this->rtpParameters.GetRtxCodecForEncoding(encoding);
if (rtxCodec && encoding.hasRtx)
this->rtpStream->SetRtx(rtxCodec->payloadType, encoding.rtx.ssrc);
}
void SvcConsumer::RequestKeyFrame()
{
MS_TRACE();
if (this->kind != RTC::Media::Kind::VIDEO)
return;
auto mappedSsrc = this->consumableRtpEncodings[0].ssrc;
this->listener->OnConsumerKeyFrameRequested(this, mappedSsrc);
}
void SvcConsumer::MayChangeLayers(bool force)
{
MS_TRACE();
int16_t newTargetSpatialLayer;
int16_t newTargetTemporalLayer;
if (RecalculateTargetLayers(newTargetSpatialLayer, newTargetTemporalLayer))
{
// If bitrate externally managed, don't bother the transport unless
// the newTargetSpatialLayer has changed (or force is true).
// This is because, if bitrate is externally managed, the target temporal
// layer is managed by the available given bitrate so the transport
// will let us change it when it considers.
if (this->externallyManagedBitrate)
{
if (newTargetSpatialLayer != this->encodingContext->GetTargetSpatialLayer() || force)
this->listener->OnConsumerNeedBitrateChange(this);
}
else
{
UpdateTargetLayers(newTargetSpatialLayer, newTargetTemporalLayer);
}
}
}
bool SvcConsumer::RecalculateTargetLayers(
int16_t& newTargetSpatialLayer, int16_t& newTargetTemporalLayer) const
{
MS_TRACE();
// Start with no layers.
newTargetSpatialLayer = -1;
newTargetTemporalLayer = -1;
auto now = DepLibUV::GetTime();
int16_t spatialLayer{ 0 };
if (!this->producerRtpStream)
goto done;
if (this->producerRtpStream->GetScore() == 0)
goto done;
for (; spatialLayer < this->producerRtpStream->GetSpatialLayers(); ++spatialLayer)
{
if (!producerRtpStream->GetBitrate(now, spatialLayer, 0))
continue;
newTargetSpatialLayer = spatialLayer;
// If this is the preferred or higher spatial layer and has bitrate,
// take it and exit.
if (spatialLayer >= this->preferredSpatialLayer)
break;
}
if (newTargetSpatialLayer != -1)
{
if (newTargetSpatialLayer == this->preferredSpatialLayer)
newTargetTemporalLayer = this->preferredTemporalLayer;
else if (newTargetSpatialLayer < this->preferredSpatialLayer)
newTargetTemporalLayer = this->rtpStream->GetTemporalLayers() - 1;
else
newTargetTemporalLayer = 0;
}
done:
// Return true if any target layer changed.
// clang-format off
return (
newTargetSpatialLayer != this->encodingContext->GetTargetSpatialLayer() ||
newTargetTemporalLayer != this->encodingContext->GetTargetTemporalLayer()
);
// clang-format on
}
void SvcConsumer::UpdateTargetLayers(int16_t newTargetSpatialLayer, int16_t newTargetTemporalLayer)
{
MS_TRACE();
if (newTargetSpatialLayer == -1)
{
// Unset current and target layers.
this->encodingContext->SetTargetSpatialLayer(-1);
this->encodingContext->SetCurrentSpatialLayer(-1);
this->encodingContext->SetTargetTemporalLayer(-1);
this->encodingContext->SetCurrentTemporalLayer(-1);
MS_DEBUG_TAG(
svc, "target layers changed [spatial:-1, temporal:-1, consumerId:%s]", this->id.c_str());
EmitLayersChange();
return;
}
this->encodingContext->SetTargetSpatialLayer(newTargetSpatialLayer);
this->encodingContext->SetTargetTemporalLayer(newTargetTemporalLayer);
MS_DEBUG_TAG(
svc,
"target layers changed [spatial:%" PRIi16 ", temporal:%" PRIi16 ", consumerId:%s]",
newTargetSpatialLayer,
newTargetTemporalLayer,
this->id.c_str());
// Target spatial layer has changed.
if (newTargetSpatialLayer != this->encodingContext->GetCurrentSpatialLayer())
{
// In K-SVC always ask for a keyframe when changing target spatial layer.
if (this->encodingContext->IsKSvc())
{
MS_DEBUG_DEV("K-SVC: requesting keyframe to target spatial change");
RequestKeyFrame();
}
// In full SVC just for a keyframe when upgrading target spatial layer.
// NOTE: This is because nobody implements RTCP LRR yet.
else if (newTargetSpatialLayer > this->encodingContext->GetCurrentSpatialLayer())
{
MS_DEBUG_DEV("full SVC: requesting keyframe to target spatial upgrade");
RequestKeyFrame();
}
}
}
inline void SvcConsumer::EmitScore() const
{
MS_TRACE();
json data = json::object();
FillJsonScore(data);
Channel::Notifier::Emit(this->id, "score", data);
}
inline void SvcConsumer::EmitLayersChange() const
{
MS_TRACE();
MS_DEBUG_DEV(
"current layers changed to [spatial:%" PRIi16 ", temporal:%" PRIi16 ", consumerId:%s]",
this->encodingContext->GetCurrentSpatialLayer(),
this->encodingContext->GetCurrentTemporalLayer(),
this->id.c_str());
json data = json::object();
if (this->encodingContext->GetCurrentSpatialLayer() >= 0)
{
data["spatialLayer"] = this->encodingContext->GetCurrentSpatialLayer();
data["temporalLayer"] = this->encodingContext->GetCurrentTemporalLayer();
}
else
{
data = nullptr;
}
Channel::Notifier::Emit(this->id, "layerschange", data);
}
inline void SvcConsumer::OnRtpStreamScore(
RTC::RtpStream* /*rtpStream*/, uint8_t /*score*/, uint8_t /*previousScore*/)
{
MS_TRACE();
// Emit the score event.
EmitScore();
if (IsActive())
{
// Just check target layers if our bitrate is not externally managed.
// NOTE: For now this is a bit useless since, when locally managed, we do
// not check the Consumer score at all.
if (!this->externallyManagedBitrate)
MayChangeLayers();
}
}
inline void SvcConsumer::OnRtpStreamRetransmitRtpPacket(
RTC::RtpStreamSend* /*rtpStream*/, RTC::RtpPacket* packet, bool probation)
{
MS_TRACE();
this->listener->OnConsumerRetransmitRtpPacket(this, packet, probation);
}
} // namespace RTC
......@@ -16,6 +16,7 @@
#include "RTC/RtpDictionaries.hpp"
#include "RTC/SimpleConsumer.hpp"
#include "RTC/SimulcastConsumer.hpp"
#include "RTC/SvcConsumer.hpp"
namespace RTC
{
......@@ -287,7 +288,8 @@ namespace RTC
case RTC::RtpParameters::Type::SVC:
{
MS_THROW_TYPE_ERROR("not yet implemented type 'svc'");
// This may throw.
consumer = new RTC::SvcConsumer(consumerId, this, request->data);
break;
}
......
......@@ -930,7 +930,7 @@ namespace RTC
// Then redistribute the remaining bitrate by allowing Consumers to increase
// layer by layer.
while (remainingBitrate >= 5000)
while (remainingBitrate >= 2000)
{
auto previousRemainingBitrate = remainingBitrate;
......@@ -951,7 +951,7 @@ namespace RTC
remainingBitrate -= usedBitrate;
// No more.
if (remainingBitrate < 5000)
if (remainingBitrate < 2000)
break;
}
......
......@@ -131,15 +131,15 @@ void TcpConnection::Close()
void TcpConnection::Dump() const
{
MS_DEBUG_DEV("<TcpConnection>");
MS_DEBUG_DEV(
MS_DUMP("<TcpConnection>");
MS_DUMP(
" [TCP, local:%s :%" PRIu16 ", remote:%s :%" PRIu16 ", status:%s]",
this->localIp.c_str(),
static_cast<uint16_t>(this->localPort),
this->peerIp.c_str(),
static_cast<uint16_t>(this->peerPort),
(!this->closed) ? "open" : "closed");
MS_DEBUG_DEV("</TcpConnection>");
MS_DUMP("</TcpConnection>");
}
void TcpConnection::Setup(
......
......@@ -90,14 +90,14 @@ void TcpServer::Close()
void TcpServer::Dump() const
{
MS_DEBUG_DEV("<TcpServer>");
MS_DEBUG_DEV(
MS_DUMP("<TcpServer>");
MS_DUMP(
" [TCP, local:%s :%" PRIu16 ", status:%s, connections:%zu]",
this->localIp.c_str(),
static_cast<uint16_t>(this->localPort),
(!this->closed) ? "open" : "closed",
this->connections.size());
MS_DEBUG_DEV("</TcpServer>");
MS_DUMP("</TcpServer>");
}
bool TcpServer::SetLocalAddress()
......
......@@ -117,13 +117,13 @@ void UdpSocket::Close()
void UdpSocket::Dump() const
{
MS_DEBUG_DEV("<UdpSocket>");
MS_DEBUG_DEV(
MS_DUMP("<UdpSocket>");
MS_DUMP(
" [UDP, local:%s :%" PRIu16 ", status:%s]",
this->localIp.c_str(),
static_cast<uint16_t>(this->localPort),
(!this->closed) ? "open" : "closed");
MS_DEBUG_DEV("</UdpSocket>");
MS_DUMP("</UdpSocket>");
}
void UdpSocket::Send(const uint8_t* data, size_t len, const struct sockaddr* addr)
......@@ -324,6 +324,7 @@ inline void UdpSocket::OnUvSendError(int error) // NOLINT(misc-unused-parameters
if (this->closed)
return;
#ifdef MS_LOG_DEV
MS_DEBUG_DEV("send error: %s", uv_strerror(error));
#endif
......
......@@ -39,7 +39,7 @@ public:
{
return;
};
bool Process(Codecs::EncodingContext* /*context*/, uint8_t* /*data*/)
bool Process(Codecs::EncodingContext* /*context*/, uint8_t* /*data*/, bool& /*marker*/)
{
return true;
};
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论