#define MS_CLASS "RTC::SimpleConsumer"
#include "RTC/SimpleConsumer.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Channel/ChannelNotifier.hpp"
#include "RTC/Codecs/Tools.hpp"
namespace RTC
{
SimpleConsumer::SimpleConsumer(
const std::string& id, const std::string& producerId, RTC::Consumer::Listener* listener, json& data)
: RTC::Consumer::Consumer(id, producerId, listener, data, RTC::RtpParameters::Type::SIMPLE)
{
MS_TRACE();
if (this->consumableRtpEncodings.size() != 1u)
MS_THROW_TYPE_ERROR("invalid consumableRtpEncodings with size != 1");
auto& encoding = this->rtpParameters.encodings[0];
const auto* mediaCodec = this->rtpParameters.GetCodecForEncoding(encoding);
this->keyFrameSupported = RTC::Codecs::Tools::CanBeKeyFrame(mediaCodec->mimeType);
CreateRtpStream();
RTC::Codecs::EncodingContext::Params params;
this->encodingContext.reset(RTC::Codecs::Tools::GetEncodingContext(mediaCodec->mimeType, params));
if (
mediaCodec->mimeType.type == RTC::RtpCodecMimeType::Type::AUDIO &&
(mediaCodec->mimeType.subtype == RTC::RtpCodecMimeType::Subtype::OPUS ||
mediaCodec->mimeType.subtype == RTC::RtpCodecMimeType::Subtype::MULTIOPUS))
{
auto jsonIgnoreDtx = data.find("ignoreDtx");
if (jsonIgnoreDtx != data.end() && jsonIgnoreDtx->is_boolean())
{
auto ignoreDtx = jsonIgnoreDtx->get<bool>();
this->encodingContext->SetIgnoreDtx(ignoreDtx);
}
}
}
SimpleConsumer::~SimpleConsumer()
{
MS_TRACE();
delete this->rtpStream;
}
void SimpleConsumer::FillJson(json& jsonObject) const
{
MS_TRACE();
RTC::Consumer::FillJson(jsonObject);
this->rtpStream->FillJson(jsonObject["rtpStream"]);
}
void SimpleConsumer::FillJsonStats(json& jsonArray) const
{
MS_TRACE();
jsonArray.emplace_back(json::value_t::object);
this->rtpStream->FillJsonStats(jsonArray[0]);
if (this->producerRtpStream)
{
jsonArray.emplace_back(json::value_t::object);
this->producerRtpStream->FillJsonStats(jsonArray[1]);
}
}
void SimpleConsumer::FillJsonScore(json& jsonObject) const
{
MS_TRACE();
MS_ASSERT(this->producerRtpStreamScores, "producerRtpStreamScores not set");
jsonObject["score"] = this->rtpStream->GetScore();
if (this->producerRtpStream)
jsonObject["producerScore"] = this->producerRtpStream->GetScore();
else
jsonObject["producerScore"] = 0;
jsonObject["producerScores"] = *this->producerRtpStreamScores;
}
void SimpleConsumer::HandleRequest(Channel::ChannelRequest* request)
{
MS_TRACE();
switch (request->methodId)
{
case Channel::ChannelRequest::MethodId::CONSUMER_REQUEST_KEY_FRAME:
{
if (IsActive())
RequestKeyFrame();
request->Accept();
break;
}
case Channel::ChannelRequest::MethodId::CONSUMER_SET_PREFERRED_LAYERS:
{
request->Accept();
break;
}
default:
{
RTC::Consumer::HandleRequest(request);
}
}
}
void SimpleConsumer::ProducerRtpStream(RTC::RtpStream* rtpStream, uint32_t )
{
MS_TRACE();
this->producerRtpStream = rtpStream;
}
void SimpleConsumer::ProducerNewRtpStream(RTC::RtpStream* rtpStream, uint32_t )
{
MS_TRACE();
this->producerRtpStream = rtpStream;
EmitScore();
}
void SimpleConsumer::ProducerRtpStreamScore(
RTC::RtpStream* , uint8_t , uint8_t )
{
MS_TRACE();
EmitScore();
}
void SimpleConsumer::ProducerRtcpSenderReport(RTC::RtpStream* , bool )
{
MS_TRACE();
}
uint8_t SimpleConsumer::GetBitratePriority() const
{
MS_TRACE();
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
if (this->kind != RTC::Media::Kind::VIDEO)
return 0u;
if (!IsActive())
return 0u;
return this->priority;
}
uint32_t SimpleConsumer::IncreaseLayer(uint32_t bitrate, bool )
{
MS_TRACE();
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
MS_ASSERT(this->kind == RTC::Media::Kind::VIDEO, "should be video");
MS_ASSERT(IsActive(), "should be active");
if (this->managingBitrate)
return 0u;
this->managingBitrate = true;
auto nowMs = DepLibUV::GetTimeMs();
auto desiredBitrate = this->producerRtpStream->GetBitrate(nowMs);
if (desiredBitrate < bitrate)
return desiredBitrate;
else
return bitrate;
}
void SimpleConsumer::ApplyLayers()
{
MS_TRACE();
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
MS_ASSERT(this->kind == RTC::Media::Kind::VIDEO, "should be video");
MS_ASSERT(IsActive(), "should be active");
this->managingBitrate = false;
}
uint32_t SimpleConsumer::GetDesiredBitrate() const
{
MS_TRACE();
MS_ASSERT(this->externallyManagedBitrate, "bitrate is not externally managed");
if (this->kind != RTC::Media::Kind::VIDEO)
return 0u;
if (!IsActive())
return 0u;
auto nowMs = DepLibUV::GetTimeMs();
auto desiredBitrate = this->producerRtpStream->GetBitrate(nowMs);
auto maxBitrate = this->rtpParameters.encodings[0].maxBitrate;
if (maxBitrate > desiredBitrate)
desiredBitrate = maxBitrate;
return desiredBitrate;
}
void SimpleConsumer::SendRtpPacket(std::shared_ptr<RTC::RtpPacket> packet)
{
MS_TRACE();
if (!IsActive())
return;
auto payloadType = packet->GetPayloadType();
if (this->supportedCodecPayloadTypes.find(payloadType) == this->supportedCodecPayloadTypes.end())
{
MS_DEBUG_DEV("payload type not supported [payloadType:%" PRIu8 "]", payloadType);
return;
}
bool marker;
if (!packet->ProcessPayload(this->encodingContext.get(), marker))
{
MS_DEBUG_TAG(
rtp,
"discarding packet [ssrc:%" PRIu32 ", seq:%" PRIu16 ", ts:%" PRIu32 "]",
packet->GetSsrc(),
packet->GetSequenceNumber(),
packet->GetTimestamp());
this->rtpSeqManager.Drop(packet->GetSequenceNumber());
return;
}
if (this->syncRequired && this->keyFrameSupported && !packet->IsKeyFrame())
return;
bool isSyncPacket = this->syncRequired;
if (isSyncPacket)
{
if (packet->IsKeyFrame())
MS_DEBUG_TAG(rtp, "sync key frame received");
this->rtpSeqManager.Sync(packet->GetSequenceNumber() - 1);
this->syncRequired = false;
}
uint16_t seq;
this->rtpSeqManager.Input(packet->GetSequenceNumber(), seq);
auto origSsrc = packet->GetSsrc();
auto origSeq = packet->GetSequenceNumber();
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);
}
if (this->rtpStream->ReceivePacket(packet))
{
this->listener->OnConsumerSendRtpPacket(this, packet.get());
EmitTraceEventRtpAndKeyFrameTypes(packet.get());
}
else
{
MS_WARN_TAG(
rtp,
"failed to send packet [ssrc:%" PRIu32 ", seq:%" PRIu16 ", ts:%" PRIu32
"] from original [seq:%" PRIu16 "]",
packet->GetSsrc(),
packet->GetSequenceNumber(),
packet->GetTimestamp(),
origSeq);
}
packet->SetSsrc(origSsrc);
packet->SetSequenceNumber(origSeq);
}
void SimpleConsumer::GetRtcp(
RTC::RTCP::CompoundPacket* packet, RTC::RtpStreamSend* rtpStream, uint64_t nowMs)
{
MS_TRACE();
MS_ASSERT(rtpStream == this->rtpStream, "RTP stream does not match");
if (static_cast<float>((nowMs - this->lastRtcpSentTime) * 1.15) < this->maxRtcpInterval)
return;
auto* report = this->rtpStream->GetRtcpSenderReport(nowMs);
if (!report)
return;
packet->AddSenderReport(report);
auto* sdesChunk = this->rtpStream->GetRtcpSdesChunk();
packet->AddSdesChunk(sdesChunk);
auto* dlrr = this->rtpStream->GetRtcpXrDelaySinceLastRr(nowMs);
if (dlrr)
{
auto* report = new RTC::RTCP::DelaySinceLastRr();
report->AddSsrcInfo(dlrr);
packet->AddDelaySinceLastRr(report);
}
this->lastRtcpSentTime = nowMs;
}
void SimpleConsumer::NeedWorstRemoteFractionLost(
uint32_t , uint8_t& worstRemoteFractionLost)
{
MS_TRACE();
if (!IsActive())
return;
auto fractionLost = this->rtpStream->GetFractionLost();
if (fractionLost > worstRemoteFractionLost)
worstRemoteFractionLost = fractionLost;
}
void SimpleConsumer::ReceiveNack(RTC::RTCP::FeedbackRtpNackPacket* nackPacket)
{
MS_TRACE();
if (!IsActive())
return;
EmitTraceEventNackType();
this->rtpStream->ReceiveNack(nackPacket);
}
void SimpleConsumer::ReceiveKeyFrameRequest(
RTC::RTCP::FeedbackPs::MessageType messageType, uint32_t ssrc)
{
MS_TRACE();
switch (messageType)
{
case RTC::RTCP::FeedbackPs::MessageType::PLI:
{
EmitTraceEventPliType(ssrc);
break;
}
case RTC::RTCP::FeedbackPs::MessageType::FIR:
{
EmitTraceEventFirType(ssrc);
break;
}
default:;
}
this->rtpStream->ReceiveKeyFrameRequest(messageType);
if (IsActive())
RequestKeyFrame();
}
void SimpleConsumer::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report)
{
MS_TRACE();
this->rtpStream->ReceiveRtcpReceiverReport(report);
}
void SimpleConsumer::ReceiveRtcpXrReceiverReferenceTime(RTC::RTCP::ReceiverReferenceTime* report)
{
MS_TRACE();
this->rtpStream->ReceiveRtcpXrReceiverReferenceTime(report);
}
uint32_t SimpleConsumer::GetTransmissionRate(uint64_t nowMs)
{
MS_TRACE();
if (!IsActive())
return 0u;
return this->rtpStream->GetBitrate(nowMs);
}
float SimpleConsumer::GetRtt() const
{
MS_TRACE();
return this->rtpStream->GetRtt();
}
void SimpleConsumer::UserOnTransportConnected()
{
MS_TRACE();
this->syncRequired = true;
if (IsActive())
RequestKeyFrame();
}
void SimpleConsumer::UserOnTransportDisconnected()
{
MS_TRACE();
this->rtpStream->Pause();
}
void SimpleConsumer::UserOnPaused()
{
MS_TRACE();
this->rtpStream->Pause();
if (this->externallyManagedBitrate && this->kind == RTC::Media::Kind::VIDEO)
this->listener->OnConsumerNeedZeroBitrate(this);
}
void SimpleConsumer::UserOnResumed()
{
MS_TRACE();
this->syncRequired = true;
if (IsActive())
RequestKeyFrame();
}
void SimpleConsumer::CreateRtpStream()
{
MS_TRACE();
auto& encoding = this->rtpParameters.encodings[0];
const auto* mediaCodec = this->rtpParameters.GetCodecForEncoding(encoding);
MS_DEBUG_TAG(
rtp, "[ssrc:%" PRIu32 ", payloadType:%" PRIu8 "]", encoding.ssrc, mediaCodec->payloadType);
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;
if (mediaCodec->parameters.HasInteger("useinbandfec") && mediaCodec->parameters.GetInteger("useinbandfec") == 1)
{
MS_DEBUG_TAG(rtp, "in band FEC enabled");
params.useInBandFec = true;
}
if (mediaCodec->parameters.HasInteger("usedtx") && mediaCodec->parameters.GetInteger("usedtx") == 1)
{
MS_DEBUG_TAG(rtp, "DTX enabled");
params.useDtx = true;
}
if (encoding.dtx)
{
MS_DEBUG_TAG(rtp, "DTX enabled");
params.useDtx = true;
}
for (const auto& fb : mediaCodec->rtcpFeedback)
{
if (!params.useNack && fb.type == "nack" && fb.parameter.empty())
{
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;
}
}
this->rtpStream = new RTC::RtpStreamSend(this, params, this->rtpParameters.mid);
this->rtpStreams.push_back(this->rtpStream);
if (IsPaused() || IsProducerPaused())
this->rtpStream->Pause();
const auto* rtxCodec = this->rtpParameters.GetRtxCodecForEncoding(encoding);
if (rtxCodec && encoding.hasRtx)
this->rtpStream->SetRtx(rtxCodec->payloadType, encoding.rtx.ssrc);
}
void SimpleConsumer::RequestKeyFrame()
{
MS_TRACE();
if (this->kind != RTC::Media::Kind::VIDEO)
return;
auto mappedSsrc = this->consumableRtpEncodings[0].ssrc;
this->listener->OnConsumerKeyFrameRequested(this, mappedSsrc);
}
inline void SimpleConsumer::EmitScore() const
{
MS_TRACE();
json data = json::object();
FillJsonScore(data);
Channel::ChannelNotifier::Emit(this->id, "score", data);
}
inline void SimpleConsumer::OnRtpStreamScore(
RTC::RtpStream* , uint8_t , uint8_t )
{
MS_TRACE();
EmitScore();
}
inline void SimpleConsumer::OnRtpStreamRetransmitRtpPacket(
RTC::RtpStreamSend* , RTC::RtpPacket* packet)
{
MS_TRACE();
this->listener->OnConsumerRetransmitRtpPacket(this, packet);
EmitTraceEventRtpAndKeyFrameTypes(packet, this->rtpStream->HasRtx());
}
}