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 const PacketTime& packet_time) {
182 return InsertRTPPacket(static_cast<const int8_t*>(rtp_packet),
183 rtp_packet_length, packet_time);
186 int ViEReceiver::ReceivedRTCPPacket(const void* rtcp_packet,
187 int rtcp_packet_length) {
188 return InsertRTCPPacket(static_cast<const int8_t*>(rtcp_packet),
192 int32_t ViEReceiver::OnReceivedPayloadData(
193 const uint8_t* payload_data, const uint16_t payload_size,
194 const WebRtcRTPHeader* rtp_header) {
195 if (vcm_->IncomingPacket(payload_data, payload_size, *rtp_header) != 0) {
202 bool ViEReceiver::OnRecoveredPacket(const uint8_t* rtp_packet,
203 int rtp_packet_length) {
205 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
206 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVideo, channel_id_,
207 "IncomingPacket invalid RTP header");
210 header.payload_type_frequency = kVideoPayloadTypeFrequency;
211 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
214 int ViEReceiver::InsertRTPPacket(const int8_t* rtp_packet,
215 int rtp_packet_length,
216 const PacketTime& packet_time) {
217 // TODO(mflodman) Change decrypt to get rid of this cast.
218 int8_t* tmp_ptr = const_cast<int8_t*>(rtp_packet);
219 unsigned char* received_packet = reinterpret_cast<unsigned char*>(tmp_ptr);
220 int received_packet_length = rtp_packet_length;
223 CriticalSectionScoped cs(receive_cs_.get());
228 if (external_decryption_) {
229 int decrypted_length = kViEMaxMtu;
230 external_decryption_->decrypt(channel_id_, received_packet,
231 decryption_buffer_, received_packet_length,
233 if (decrypted_length <= 0) {
234 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
235 "RTP decryption failed");
237 } else if (decrypted_length > kViEMaxMtu) {
238 WEBRTC_TRACE(webrtc::kTraceCritical, webrtc::kTraceVideo, channel_id_,
239 "InsertRTPPacket: %d bytes is allocated as RTP decrytption"
240 " output, external decryption used %d bytes. => memory is "
241 " now corrupted", kViEMaxMtu, decrypted_length);
244 received_packet = decryption_buffer_;
245 received_packet_length = decrypted_length;
249 rtp_dump_->DumpPacket(received_packet,
250 static_cast<uint16_t>(received_packet_length));
254 if (!rtp_header_parser_->Parse(received_packet, received_packet_length,
256 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
257 "Incoming packet: Invalid RTP header");
260 int payload_length = received_packet_length - header.headerLength;
261 int64_t arrival_time_ms;
262 if (packet_time.timestamp != -1)
263 arrival_time_ms = (packet_time.timestamp + 500) / 1000;
265 arrival_time_ms = TickTime::MillisecondTimestamp();
267 remote_bitrate_estimator_->IncomingPacket(arrival_time_ms,
268 payload_length, header);
269 header.payload_type_frequency = kVideoPayloadTypeFrequency;
271 bool in_order = IsPacketInOrder(header);
272 rtp_receive_statistics_->IncomingPacket(
273 header, received_packet_length, IsPacketRetransmitted(header, in_order));
274 rtp_payload_registry_->SetIncomingPayloadType(header);
275 return ReceivePacket(
276 received_packet, received_packet_length, header, in_order)
281 bool ViEReceiver::ReceivePacket(const uint8_t* packet,
283 const RTPHeader& header,
285 if (rtp_payload_registry_->IsEncapsulated(header)) {
286 return ParseAndHandleEncapsulatingHeader(packet, packet_length, header);
288 const uint8_t* payload = packet + header.headerLength;
289 int payload_length = packet_length - header.headerLength;
290 assert(payload_length >= 0);
291 PayloadUnion payload_specific;
292 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
293 &payload_specific)) {
296 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
297 payload_specific, in_order);
300 bool ViEReceiver::ParseAndHandleEncapsulatingHeader(const uint8_t* packet,
302 const RTPHeader& header) {
303 if (rtp_payload_registry_->IsRed(header)) {
304 int8_t ulpfec_pt = rtp_payload_registry_->ulpfec_payload_type();
305 if (packet[header.headerLength] == ulpfec_pt)
306 rtp_receive_statistics_->FecPacketReceived(header.ssrc);
307 if (fec_receiver_->AddReceivedRedPacket(
308 header, packet, packet_length, ulpfec_pt) != 0) {
309 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
310 "Incoming RED packet error");
313 return fec_receiver_->ProcessReceivedFec() == 0;
314 } else if (rtp_payload_registry_->IsRtx(header)) {
315 // Remove the RTX header and parse the original RTP header.
316 if (packet_length < header.headerLength)
318 if (packet_length > static_cast<int>(sizeof(restored_packet_)))
320 CriticalSectionScoped cs(receive_cs_.get());
321 if (restored_packet_in_use_) {
322 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
323 "Multiple RTX headers detected, dropping packet");
326 uint8_t* restored_packet_ptr = restored_packet_;
327 if (!rtp_payload_registry_->RestoreOriginalPacket(
328 &restored_packet_ptr, packet, &packet_length, rtp_receiver_->SSRC(),
330 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
331 "Incoming RTX packet: invalid RTP header");
334 restored_packet_in_use_ = true;
335 bool ret = OnRecoveredPacket(restored_packet_ptr, packet_length);
336 restored_packet_in_use_ = false;
342 int ViEReceiver::InsertRTCPPacket(const int8_t* rtcp_packet,
343 int rtcp_packet_length) {
344 // TODO(mflodman) Change decrypt to get rid of this cast.
345 int8_t* tmp_ptr = const_cast<int8_t*>(rtcp_packet);
346 unsigned char* received_packet = reinterpret_cast<unsigned char*>(tmp_ptr);
347 int received_packet_length = rtcp_packet_length;
349 CriticalSectionScoped cs(receive_cs_.get());
354 if (external_decryption_) {
355 int decrypted_length = kViEMaxMtu;
356 external_decryption_->decrypt_rtcp(channel_id_, received_packet,
358 received_packet_length,
360 if (decrypted_length <= 0) {
361 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
362 "RTP decryption failed");
364 } else if (decrypted_length > kViEMaxMtu) {
365 WEBRTC_TRACE(webrtc::kTraceCritical, webrtc::kTraceVideo, channel_id_,
366 "InsertRTCPPacket: %d bytes is allocated as RTP "
367 " decrytption output, external decryption used %d bytes. "
368 " => memory is now corrupted",
369 kViEMaxMtu, decrypted_length);
372 received_packet = decryption_buffer_;
373 received_packet_length = decrypted_length;
377 rtp_dump_->DumpPacket(
378 received_packet, static_cast<uint16_t>(received_packet_length));
382 CriticalSectionScoped cs(receive_cs_.get());
383 std::list<RtpRtcp*>::iterator it = rtp_rtcp_simulcast_.begin();
384 while (it != rtp_rtcp_simulcast_.end()) {
385 RtpRtcp* rtp_rtcp = *it++;
386 rtp_rtcp->IncomingRtcpPacket(received_packet, received_packet_length);
389 assert(rtp_rtcp_); // Should be set by owner at construction time.
390 return rtp_rtcp_->IncomingRtcpPacket(received_packet, received_packet_length);
393 void ViEReceiver::StartReceive() {
394 CriticalSectionScoped cs(receive_cs_.get());
398 void ViEReceiver::StopReceive() {
399 CriticalSectionScoped cs(receive_cs_.get());
403 int ViEReceiver::StartRTPDump(const char file_nameUTF8[1024]) {
404 CriticalSectionScoped cs(receive_cs_.get());
406 // Restart it if it already exists and is started
409 rtp_dump_ = RtpDump::CreateRtpDump();
410 if (rtp_dump_ == NULL) {
411 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
412 "StartRTPDump: Failed to create RTP dump");
416 if (rtp_dump_->Start(file_nameUTF8) != 0) {
417 RtpDump::DestroyRtpDump(rtp_dump_);
419 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
420 "StartRTPDump: Failed to start RTP dump");
426 int ViEReceiver::StopRTPDump() {
427 CriticalSectionScoped cs(receive_cs_.get());
429 if (rtp_dump_->IsActive()) {
432 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
433 "StopRTPDump: Dump not active");
435 RtpDump::DestroyRtpDump(rtp_dump_);
438 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
439 "StopRTPDump: RTP dump not started");
445 // TODO(holmer): To be moved to ViEChannelGroup.
446 void ViEReceiver::EstimatedReceiveBandwidth(
447 unsigned int* available_bandwidth) const {
448 std::vector<unsigned int> ssrcs;
450 // LatestEstimate returns an error if there is no valid bitrate estimate, but
451 // ViEReceiver instead returns a zero estimate.
452 remote_bitrate_estimator_->LatestEstimate(&ssrcs, available_bandwidth);
453 if (std::find(ssrcs.begin(), ssrcs.end(), rtp_receiver_->SSRC()) !=
455 *available_bandwidth /= ssrcs.size();
457 *available_bandwidth = 0;
461 ReceiveStatistics* ViEReceiver::GetReceiveStatistics() const {
462 return rtp_receive_statistics_.get();
465 bool ViEReceiver::IsPacketInOrder(const RTPHeader& header) const {
466 StreamStatistician* statistician =
467 rtp_receive_statistics_->GetStatistician(header.ssrc);
470 return statistician->IsPacketInOrder(header.sequenceNumber);
473 bool ViEReceiver::IsPacketRetransmitted(const RTPHeader& header,
474 bool in_order) const {
475 // Retransmissions are handled separately if RTX is enabled.
476 if (rtp_payload_registry_->RtxEnabled())
478 StreamStatistician* statistician =
479 rtp_receive_statistics_->GetStatistician(header.ssrc);
482 // Check if this is a retransmission.
483 uint16_t min_rtt = 0;
484 rtp_rtcp_->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
486 statistician->IsRetransmitOfOldPacket(header, min_rtt);
488 } // namespace webrtc