2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
11 #include "webrtc/video_engine/vie_receiver.h"
15 #include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
16 #include "webrtc/modules/rtp_rtcp/interface/fec_receiver.h"
17 #include "webrtc/modules/rtp_rtcp/interface/receive_statistics.h"
18 #include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
19 #include "webrtc/modules/rtp_rtcp/interface/rtp_payload_registry.h"
20 #include "webrtc/modules/rtp_rtcp/interface/rtp_receiver.h"
21 #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h"
22 #include "webrtc/modules/utility/interface/rtp_dump.h"
23 #include "webrtc/modules/video_coding/main/interface/video_coding.h"
24 #include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
25 #include "webrtc/system_wrappers/interface/tick_util.h"
26 #include "webrtc/system_wrappers/interface/trace.h"
30 ViEReceiver::ViEReceiver(const int32_t channel_id,
31 VideoCodingModule* module_vcm,
32 RemoteBitrateEstimator* remote_bitrate_estimator,
33 RtpFeedback* rtp_feedback)
34 : receive_cs_(CriticalSectionWrapper::CreateCriticalSection()),
35 channel_id_(channel_id),
36 rtp_header_parser_(RtpHeaderParser::Create()),
37 rtp_payload_registry_(new RTPPayloadRegistry(
38 channel_id, RTPPayloadStrategy::CreateStrategy(false))),
39 rtp_receiver_(RtpReceiver::CreateVideoReceiver(
40 channel_id, Clock::GetRealTimeClock(), this, rtp_feedback,
41 rtp_payload_registry_.get())),
42 rtp_receive_statistics_(ReceiveStatistics::Create(
43 Clock::GetRealTimeClock())),
44 fec_receiver_(FecReceiver::Create(channel_id, this)),
47 remote_bitrate_estimator_(remote_bitrate_estimator),
48 external_decryption_(NULL),
49 decryption_buffer_(NULL),
52 restored_packet_in_use_(false) {
53 assert(remote_bitrate_estimator);
56 ViEReceiver::~ViEReceiver() {
57 if (decryption_buffer_) {
58 delete[] decryption_buffer_;
59 decryption_buffer_ = NULL;
63 RtpDump::DestroyRtpDump(rtp_dump_);
68 bool ViEReceiver::SetReceiveCodec(const VideoCodec& video_codec) {
69 int8_t old_pltype = -1;
70 if (rtp_payload_registry_->ReceivePayloadType(video_codec.plName,
71 kVideoPayloadTypeFrequency,
73 video_codec.maxBitrate,
75 rtp_payload_registry_->DeRegisterReceivePayload(old_pltype);
78 return RegisterPayload(video_codec);
81 bool ViEReceiver::RegisterPayload(const VideoCodec& video_codec) {
82 return rtp_receiver_->RegisterReceivePayload(video_codec.plName,
84 kVideoPayloadTypeFrequency,
86 video_codec.maxBitrate) == 0;
89 void ViEReceiver::SetNackStatus(bool enable,
90 int max_nack_reordering_threshold) {
92 // Reset the threshold back to the lower default threshold when NACK is
93 // disabled since we no longer will be receiving retransmissions.
94 max_nack_reordering_threshold = kDefaultMaxReorderingThreshold;
96 rtp_receive_statistics_->SetMaxReorderingThreshold(
97 max_nack_reordering_threshold);
98 rtp_receiver_->SetNACKStatus(enable ? kNackRtcp : kNackOff);
101 void ViEReceiver::SetRtxStatus(bool enable, uint32_t ssrc) {
102 rtp_payload_registry_->SetRtxStatus(enable, ssrc);
105 void ViEReceiver::SetRtxPayloadType(uint32_t payload_type) {
106 rtp_payload_registry_->SetRtxPayloadType(payload_type);
109 uint32_t ViEReceiver::GetRemoteSsrc() const {
110 return rtp_receiver_->SSRC();
113 int ViEReceiver::GetCsrcs(uint32_t* csrcs) const {
114 return rtp_receiver_->CSRCs(csrcs);
117 int ViEReceiver::RegisterExternalDecryption(Encryption* decryption) {
118 CriticalSectionScoped cs(receive_cs_.get());
119 if (external_decryption_) {
122 decryption_buffer_ = new uint8_t[kViEMaxMtu];
123 if (decryption_buffer_ == NULL) {
126 external_decryption_ = decryption;
130 int ViEReceiver::DeregisterExternalDecryption() {
131 CriticalSectionScoped cs(receive_cs_.get());
132 if (external_decryption_ == NULL) {
135 external_decryption_ = NULL;
139 void ViEReceiver::SetRtpRtcpModule(RtpRtcp* module) {
143 RtpReceiver* ViEReceiver::GetRtpReceiver() const {
144 return rtp_receiver_.get();
147 void ViEReceiver::RegisterSimulcastRtpRtcpModules(
148 const std::list<RtpRtcp*>& rtp_modules) {
149 CriticalSectionScoped cs(receive_cs_.get());
150 rtp_rtcp_simulcast_.clear();
152 if (!rtp_modules.empty()) {
153 rtp_rtcp_simulcast_.insert(rtp_rtcp_simulcast_.begin(),
159 bool ViEReceiver::SetReceiveTimestampOffsetStatus(bool enable, int id) {
161 return rtp_header_parser_->RegisterRtpHeaderExtension(
162 kRtpExtensionTransmissionTimeOffset, id);
164 return rtp_header_parser_->DeregisterRtpHeaderExtension(
165 kRtpExtensionTransmissionTimeOffset);
169 bool ViEReceiver::SetReceiveAbsoluteSendTimeStatus(bool enable, int id) {
171 return rtp_header_parser_->RegisterRtpHeaderExtension(
172 kRtpExtensionAbsoluteSendTime, id);
174 return rtp_header_parser_->DeregisterRtpHeaderExtension(
175 kRtpExtensionAbsoluteSendTime);
179 int ViEReceiver::ReceivedRTPPacket(const void* rtp_packet,
180 int rtp_packet_length) {
181 return InsertRTPPacket(static_cast<const int8_t*>(rtp_packet),
185 int ViEReceiver::ReceivedRTCPPacket(const void* rtcp_packet,
186 int rtcp_packet_length) {
187 return InsertRTCPPacket(static_cast<const int8_t*>(rtcp_packet),
191 int32_t ViEReceiver::OnReceivedPayloadData(
192 const uint8_t* payload_data, const uint16_t payload_size,
193 const WebRtcRTPHeader* rtp_header) {
194 if (vcm_->IncomingPacket(payload_data, payload_size, *rtp_header) != 0) {
201 bool ViEReceiver::OnRecoveredPacket(const uint8_t* rtp_packet,
202 int rtp_packet_length) {
204 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
205 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVideo, channel_id_,
206 "IncomingPacket invalid RTP header");
209 header.payload_type_frequency = kVideoPayloadTypeFrequency;
210 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
213 int ViEReceiver::InsertRTPPacket(const int8_t* rtp_packet,
214 int rtp_packet_length) {
215 // TODO(mflodman) Change decrypt to get rid of this cast.
216 int8_t* tmp_ptr = const_cast<int8_t*>(rtp_packet);
217 unsigned char* received_packet = reinterpret_cast<unsigned char*>(tmp_ptr);
218 int received_packet_length = rtp_packet_length;
221 CriticalSectionScoped cs(receive_cs_.get());
226 if (external_decryption_) {
227 int decrypted_length = kViEMaxMtu;
228 external_decryption_->decrypt(channel_id_, received_packet,
229 decryption_buffer_, received_packet_length,
231 if (decrypted_length <= 0) {
232 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
233 "RTP decryption failed");
235 } else if (decrypted_length > kViEMaxMtu) {
236 WEBRTC_TRACE(webrtc::kTraceCritical, webrtc::kTraceVideo, channel_id_,
237 "InsertRTPPacket: %d bytes is allocated as RTP decrytption"
238 " output, external decryption used %d bytes. => memory is "
239 " now corrupted", kViEMaxMtu, decrypted_length);
242 received_packet = decryption_buffer_;
243 received_packet_length = decrypted_length;
247 rtp_dump_->DumpPacket(received_packet,
248 static_cast<uint16_t>(received_packet_length));
252 if (!rtp_header_parser_->Parse(received_packet, received_packet_length,
254 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
255 "Incoming packet: Invalid RTP header");
258 int payload_length = received_packet_length - header.headerLength;
259 remote_bitrate_estimator_->IncomingPacket(TickTime::MillisecondTimestamp(),
260 payload_length, header);
261 header.payload_type_frequency = kVideoPayloadTypeFrequency;
263 rtp_receive_statistics_->IncomingPacket(header, received_packet_length,
264 IsPacketRetransmitted(header));
265 rtp_payload_registry_->SetIncomingPayloadType(header);
266 return ReceivePacket(received_packet, received_packet_length, header,
267 IsPacketInOrder(header)) ? 0 : -1;
270 bool ViEReceiver::ReceivePacket(const uint8_t* packet,
272 const RTPHeader& header,
274 if (rtp_payload_registry_->IsEncapsulated(header)) {
275 return ParseAndHandleEncapsulatingHeader(packet, packet_length, header);
277 const uint8_t* payload = packet + header.headerLength;
278 int payload_length = packet_length - header.headerLength;
279 assert(payload_length >= 0);
280 PayloadUnion payload_specific;
281 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
282 &payload_specific)) {
285 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
286 payload_specific, in_order);
289 bool ViEReceiver::ParseAndHandleEncapsulatingHeader(const uint8_t* packet,
291 const RTPHeader& header) {
292 if (rtp_payload_registry_->IsRed(header)) {
293 if (fec_receiver_->AddReceivedRedPacket(
294 header, packet, packet_length,
295 rtp_payload_registry_->ulpfec_payload_type()) != 0) {
296 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
297 "Incoming RED packet error");
300 return fec_receiver_->ProcessReceivedFec() == 0;
301 } else if (rtp_payload_registry_->IsRtx(header)) {
302 // Remove the RTX header and parse the original RTP header.
303 if (packet_length < header.headerLength)
305 if (packet_length > static_cast<int>(sizeof(restored_packet_)))
307 CriticalSectionScoped cs(receive_cs_.get());
308 if (restored_packet_in_use_) {
309 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
310 "Multiple RTX headers detected, dropping packet");
313 uint8_t* restored_packet_ptr = restored_packet_;
314 if (!rtp_payload_registry_->RestoreOriginalPacket(
315 &restored_packet_ptr, packet, &packet_length, rtp_receiver_->SSRC(),
317 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
318 "Incoming RTX packet: invalid RTP header");
321 restored_packet_in_use_ = true;
322 bool ret = OnRecoveredPacket(restored_packet_ptr, packet_length);
323 restored_packet_in_use_ = false;
329 int ViEReceiver::InsertRTCPPacket(const int8_t* rtcp_packet,
330 int rtcp_packet_length) {
331 // TODO(mflodman) Change decrypt to get rid of this cast.
332 int8_t* tmp_ptr = const_cast<int8_t*>(rtcp_packet);
333 unsigned char* received_packet = reinterpret_cast<unsigned char*>(tmp_ptr);
334 int received_packet_length = rtcp_packet_length;
336 CriticalSectionScoped cs(receive_cs_.get());
341 if (external_decryption_) {
342 int decrypted_length = kViEMaxMtu;
343 external_decryption_->decrypt_rtcp(channel_id_, received_packet,
345 received_packet_length,
347 if (decrypted_length <= 0) {
348 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
349 "RTP decryption failed");
351 } else if (decrypted_length > kViEMaxMtu) {
352 WEBRTC_TRACE(webrtc::kTraceCritical, webrtc::kTraceVideo, channel_id_,
353 "InsertRTCPPacket: %d bytes is allocated as RTP "
354 " decrytption output, external decryption used %d bytes. "
355 " => memory is now corrupted",
356 kViEMaxMtu, decrypted_length);
359 received_packet = decryption_buffer_;
360 received_packet_length = decrypted_length;
364 rtp_dump_->DumpPacket(
365 received_packet, static_cast<uint16_t>(received_packet_length));
369 CriticalSectionScoped cs(receive_cs_.get());
370 std::list<RtpRtcp*>::iterator it = rtp_rtcp_simulcast_.begin();
371 while (it != rtp_rtcp_simulcast_.end()) {
372 RtpRtcp* rtp_rtcp = *it++;
373 rtp_rtcp->IncomingRtcpPacket(received_packet, received_packet_length);
376 assert(rtp_rtcp_); // Should be set by owner at construction time.
377 return rtp_rtcp_->IncomingRtcpPacket(received_packet, received_packet_length);
380 void ViEReceiver::StartReceive() {
381 CriticalSectionScoped cs(receive_cs_.get());
385 void ViEReceiver::StopReceive() {
386 CriticalSectionScoped cs(receive_cs_.get());
390 int ViEReceiver::StartRTPDump(const char file_nameUTF8[1024]) {
391 CriticalSectionScoped cs(receive_cs_.get());
393 // Restart it if it already exists and is started
396 rtp_dump_ = RtpDump::CreateRtpDump();
397 if (rtp_dump_ == NULL) {
398 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
399 "StartRTPDump: Failed to create RTP dump");
403 if (rtp_dump_->Start(file_nameUTF8) != 0) {
404 RtpDump::DestroyRtpDump(rtp_dump_);
406 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
407 "StartRTPDump: Failed to start RTP dump");
413 int ViEReceiver::StopRTPDump() {
414 CriticalSectionScoped cs(receive_cs_.get());
416 if (rtp_dump_->IsActive()) {
419 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
420 "StopRTPDump: Dump not active");
422 RtpDump::DestroyRtpDump(rtp_dump_);
425 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
426 "StopRTPDump: RTP dump not started");
432 // TODO(holmer): To be moved to ViEChannelGroup.
433 void ViEReceiver::EstimatedReceiveBandwidth(
434 unsigned int* available_bandwidth) const {
435 std::vector<unsigned int> ssrcs;
437 // LatestEstimate returns an error if there is no valid bitrate estimate, but
438 // ViEReceiver instead returns a zero estimate.
439 remote_bitrate_estimator_->LatestEstimate(&ssrcs, available_bandwidth);
440 if (std::find(ssrcs.begin(), ssrcs.end(), rtp_receiver_->SSRC()) !=
442 *available_bandwidth /= ssrcs.size();
444 *available_bandwidth = 0;
448 ReceiveStatistics* ViEReceiver::GetReceiveStatistics() const {
449 return rtp_receive_statistics_.get();
452 bool ViEReceiver::IsPacketInOrder(const RTPHeader& header) const {
453 StreamStatistician* statistician =
454 rtp_receive_statistics_->GetStatistician(header.ssrc);
457 return statistician->IsPacketInOrder(header.sequenceNumber);
460 bool ViEReceiver::IsPacketRetransmitted(const RTPHeader& header) const {
461 // Retransmissions are handled separately if RTX is enabled.
462 if (rtp_payload_registry_->RtxEnabled())
464 StreamStatistician* statistician =
465 rtp_receive_statistics_->GetStatistician(header.ssrc);
468 // Check if this is a retransmission.
469 uint16_t min_rtt = 0;
470 rtp_rtcp_->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
471 return !IsPacketInOrder(header) &&
472 statistician->IsRetransmitOfOldPacket(header, min_rtt);
474 } // namespace webrtc