blob: 1d6f0899e309b54aa982d10fe4f9d1e53e85eab9 [file] [log] [blame]
Niels Möller530ead42018-10-04 14:28:39 +02001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
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.
9 */
10
11#include "audio/channel_receive.h"
12
13#include <algorithm>
14#include <map>
15#include <memory>
16#include <string>
17#include <utility>
18#include <vector>
19
20#include "absl/memory/memory.h"
21#include "audio/channel_send.h"
22#include "audio/utility/audio_frame_operations.h"
23#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
24#include "logging/rtc_event_log/rtc_event_log.h"
25#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
26#include "modules/audio_device/include/audio_device.h"
27#include "modules/pacing/packet_router.h"
28#include "modules/rtp_rtcp/include/receive_statistics.h"
Yves Gerey988cc082018-10-23 12:03:01 +020029#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020030#include "modules/rtp_rtcp/source/rtp_packet_received.h"
31#include "modules/utility/include/process_thread.h"
32#include "rtc_base/checks.h"
33#include "rtc_base/criticalsection.h"
34#include "rtc_base/format_macros.h"
35#include "rtc_base/location.h"
36#include "rtc_base/logging.h"
37#include "rtc_base/thread_checker.h"
38#include "rtc_base/timeutils.h"
39#include "system_wrappers/include/metrics.h"
40
41namespace webrtc {
42namespace voe {
43
44namespace {
45
46constexpr double kAudioSampleDurationSeconds = 0.01;
47constexpr int64_t kMaxRetransmissionWindowMs = 1000;
48constexpr int64_t kMinRetransmissionWindowMs = 30;
49
50// Video Sync.
51constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
52constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
53
Niels Möller7d76a312018-10-26 12:57:07 +020054webrtc::FrameType WebrtcFrameTypeForMediaTransportFrameType(
55 MediaTransportEncodedAudioFrame::FrameType frame_type) {
56 switch (frame_type) {
57 case MediaTransportEncodedAudioFrame::FrameType::kSpeech:
58 return kAudioFrameSpeech;
59 break;
60
61 case MediaTransportEncodedAudioFrame::FrameType::
62 kDiscountinuousTransmission:
63 return kAudioFrameCN;
64 break;
65 }
66}
67
68WebRtcRTPHeader CreateWebrtcRTPHeaderForMediaTransportFrame(
69 const MediaTransportEncodedAudioFrame& frame,
70 uint64_t channel_id) {
71 webrtc::WebRtcRTPHeader webrtc_header = {};
72 webrtc_header.header.payloadType = frame.payload_type();
73 webrtc_header.header.payload_type_frequency = frame.sampling_rate_hz();
74 webrtc_header.header.timestamp = frame.starting_sample_index();
75 webrtc_header.header.sequenceNumber = frame.sequence_number();
76
77 webrtc_header.frameType =
78 WebrtcFrameTypeForMediaTransportFrameType(frame.frame_type());
79
80 webrtc_header.header.ssrc = static_cast<uint32_t>(channel_id);
81
82 // The rest are initialized by the RTPHeader constructor.
83 return webrtc_header;
84}
85
Niels Möller530ead42018-10-04 14:28:39 +020086} // namespace
87
Niels Möller530ead42018-10-04 14:28:39 +020088int32_t ChannelReceive::OnReceivedPayloadData(
89 const uint8_t* payloadData,
90 size_t payloadSize,
91 const WebRtcRTPHeader* rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +020092 // We should not be receiving any RTP packets if media_transport is set.
93 RTC_CHECK(!media_transport_);
94
Niels Möller530ead42018-10-04 14:28:39 +020095 if (!channel_state_.Get().playing) {
96 // Avoid inserting into NetEQ when we are not playing. Count the
97 // packet as discarded.
98 return 0;
99 }
100
101 // Push the incoming payload (parsed and ready for decoding) into the ACM
102 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
103 0) {
104 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
105 "push data to the ACM";
106 return -1;
107 }
108
109 int64_t round_trip_time = 0;
110 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
111
112 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
113 if (!nack_list.empty()) {
114 // Can't use nack_list.data() since it's not supported by all
115 // compilers.
116 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
117 }
118 return 0;
119}
120
Niels Möller7d76a312018-10-26 12:57:07 +0200121// MediaTransportAudioSinkInterface override.
122void ChannelReceive::OnData(uint64_t channel_id,
123 MediaTransportEncodedAudioFrame frame) {
124 RTC_CHECK(media_transport_);
125
126 if (!channel_state_.Get().playing) {
127 // Avoid inserting into NetEQ when we are not playing. Count the
128 // packet as discarded.
129 return;
130 }
131
132 // Send encoded audio frame to Decoder / NetEq.
133 if (audio_coding_->IncomingPacket(
134 frame.encoded_data().data(), frame.encoded_data().size(),
135 CreateWebrtcRTPHeaderForMediaTransportFrame(frame, channel_id)) !=
136 0) {
137 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
138 "push data to the ACM";
139 }
140}
141
Niels Möller530ead42018-10-04 14:28:39 +0200142AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
143 int sample_rate_hz,
144 AudioFrame* audio_frame) {
145 audio_frame->sample_rate_hz_ = sample_rate_hz;
146
147 unsigned int ssrc;
148 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
149 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(ssrc));
150 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
151 bool muted;
152 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
153 &muted) == -1) {
154 RTC_DLOG(LS_ERROR)
155 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
156 // In all likelihood, the audio in this frame is garbage. We return an
157 // error so that the audio mixer module doesn't add it to the mix. As
158 // a result, it won't be played out and the actions skipped here are
159 // irrelevant.
160 return AudioMixer::Source::AudioFrameInfo::kError;
161 }
162
163 if (muted) {
164 // TODO(henrik.lundin): We should be able to do better than this. But we
165 // will have to go through all the cases below where the audio samples may
166 // be used, and handle the muted case in some way.
167 AudioFrameOperations::Mute(audio_frame);
168 }
169
170 {
171 // Pass the audio buffers to an optional sink callback, before applying
172 // scaling/panning, as that applies to the mix operation.
173 // External recipients of the audio (e.g. via AudioTrack), will do their
174 // own mixing/dynamic processing.
175 rtc::CritScope cs(&_callbackCritSect);
176 if (audio_sink_) {
177 AudioSinkInterface::Data data(
178 audio_frame->data(), audio_frame->samples_per_channel_,
179 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
180 audio_frame->timestamp_);
181 audio_sink_->OnData(data);
182 }
183 }
184
185 float output_gain = 1.0f;
186 {
187 rtc::CritScope cs(&volume_settings_critsect_);
188 output_gain = _outputGain;
189 }
190
191 // Output volume scaling
192 if (output_gain < 0.99f || output_gain > 1.01f) {
193 // TODO(solenberg): Combine with mute state - this can cause clicks!
194 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
195 }
196
197 // Measure audio level (0-9)
198 // TODO(henrik.lundin) Use the |muted| information here too.
199 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
200 // https://crbug.com/webrtc/7517).
201 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
202
203 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
204 // The first frame with a valid rtp timestamp.
205 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
206 }
207
208 if (capture_start_rtp_time_stamp_ >= 0) {
209 // audio_frame.timestamp_ should be valid from now on.
210
211 // Compute elapsed time.
212 int64_t unwrap_timestamp =
213 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
214 audio_frame->elapsed_time_ms_ =
215 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
216 (GetRtpTimestampRateHz() / 1000);
217
218 {
219 rtc::CritScope lock(&ts_stats_lock_);
220 // Compute ntp time.
221 audio_frame->ntp_time_ms_ =
222 ntp_estimator_.Estimate(audio_frame->timestamp_);
223 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
224 if (audio_frame->ntp_time_ms_ > 0) {
225 // Compute |capture_start_ntp_time_ms_| so that
226 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
227 capture_start_ntp_time_ms_ =
228 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
229 }
230 }
231 }
232
233 {
234 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
235 audio_coding_->TargetDelayMs());
236 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
237 rtc::CritScope lock(&video_sync_lock_);
238 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
239 jitter_buffer_delay + playout_delay_ms_);
240 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
241 jitter_buffer_delay);
242 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
243 playout_delay_ms_);
244 }
245
246 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
247 : AudioMixer::Source::AudioFrameInfo::kNormal;
248}
249
250int ChannelReceive::PreferredSampleRate() const {
251 // Return the bigger of playout and receive frequency in the ACM.
252 return std::max(audio_coding_->ReceiveFrequency(),
253 audio_coding_->PlayoutFrequency());
254}
255
256ChannelReceive::ChannelReceive(
257 ProcessThread* module_process_thread,
258 AudioDeviceModule* audio_device_module,
Niels Möller7d76a312018-10-26 12:57:07 +0200259 MediaTransportInterface* media_transport,
Niels Möllerae4237e2018-10-05 11:28:38 +0200260 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200261 RtcEventLog* rtc_event_log,
262 uint32_t remote_ssrc,
263 size_t jitter_buffer_max_packets,
264 bool jitter_buffer_fast_playout,
265 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700266 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700267 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700268 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200269 : event_log_(rtc_event_log),
270 rtp_receive_statistics_(
271 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
272 remote_ssrc_(remote_ssrc),
273 _outputAudioLevel(),
274 ntp_estimator_(Clock::GetRealTimeClock()),
275 playout_timestamp_rtp_(0),
276 playout_delay_ms_(0),
277 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
278 capture_start_rtp_time_stamp_(-1),
279 capture_start_ntp_time_ms_(-1),
280 _moduleProcessThreadPtr(module_process_thread),
281 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200282 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700283 associated_send_channel_(nullptr),
Niels Möller7d76a312018-10-26 12:57:07 +0200284 media_transport_(media_transport),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700285 frame_decryptor_(frame_decryptor),
286 crypto_options_(crypto_options) {
Niels Möller530ead42018-10-04 14:28:39 +0200287 RTC_DCHECK(module_process_thread);
288 RTC_DCHECK(audio_device_module);
289 AudioCodingModule::Config acm_config;
290 acm_config.decoder_factory = decoder_factory;
291 acm_config.neteq_config.codec_pair_id = codec_pair_id;
292 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
293 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
294 acm_config.neteq_config.enable_muted_state = true;
295 audio_coding_.reset(AudioCodingModule::Create(acm_config));
296
297 _outputAudioLevel.Clear();
298
299 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
300 RtpRtcp::Configuration configuration;
301 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100302 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200303 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200304 configuration.receive_statistics = rtp_receive_statistics_.get();
305
306 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200307
308 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
309 _rtpRtcpModule->SetSendingMediaStatus(false);
310 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
311 Init();
312}
313
314ChannelReceive::~ChannelReceive() {
315 Terminate();
316 RTC_DCHECK(!channel_state_.Get().playing);
317}
318
319void ChannelReceive::Init() {
320 channel_state_.Reset();
321
322 // --- Add modules to process thread (for periodic schedulation)
323 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
324
325 // --- ACM initialization
326 int error = audio_coding_->InitializeReceiver();
327 RTC_DCHECK_EQ(0, error);
328
329 // --- RTP/RTCP module initialization
330
331 // Ensure that RTCP is enabled by default for the created channel.
332 // Note that, the module will keep generating RTCP until it is explicitly
333 // disabled by the user.
334 // After StopListen (when no sockets exists), RTCP packets will no longer
335 // be transmitted since the Transport object will then be invalid.
336 // RTCP is enabled by default.
337 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200338
339 if (media_transport_) {
340 media_transport_->SetReceiveAudioSink(this);
341 }
Niels Möller530ead42018-10-04 14:28:39 +0200342}
343
344void ChannelReceive::Terminate() {
345 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200346
347 if (media_transport_) {
348 media_transport_->SetReceiveAudioSink(nullptr);
349 }
350
Niels Möller530ead42018-10-04 14:28:39 +0200351 // Must be called on the same thread as Init().
352 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
353
354 StopPlayout();
355
356 // The order to safely shutdown modules in a channel is:
357 // 1. De-register callbacks in modules
358 // 2. De-register modules in process thread
359 // 3. Destroy modules
360 int error = audio_coding_->RegisterTransportCallback(NULL);
361 RTC_DCHECK_EQ(0, error);
362
363 // De-register modules in process thread
364 if (_moduleProcessThreadPtr)
365 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
366
367 // End of modules shutdown
368}
369
370void ChannelReceive::SetSink(AudioSinkInterface* sink) {
371 rtc::CritScope cs(&_callbackCritSect);
372 audio_sink_ = sink;
373}
374
Niels Möller80c67622018-11-12 13:22:47 +0100375void ChannelReceive::StartPlayout() {
Niels Möller530ead42018-10-04 14:28:39 +0200376 if (channel_state_.Get().playing) {
Niels Möller80c67622018-11-12 13:22:47 +0100377 return;
Niels Möller530ead42018-10-04 14:28:39 +0200378 }
379
380 channel_state_.SetPlaying(true);
Niels Möller530ead42018-10-04 14:28:39 +0200381}
382
Niels Möller80c67622018-11-12 13:22:47 +0100383void ChannelReceive::StopPlayout() {
Niels Möller530ead42018-10-04 14:28:39 +0200384 if (!channel_state_.Get().playing) {
Niels Möller80c67622018-11-12 13:22:47 +0100385 return;
Niels Möller530ead42018-10-04 14:28:39 +0200386 }
387
388 channel_state_.SetPlaying(false);
389 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200390}
391
Niels Möller80c67622018-11-12 13:22:47 +0100392bool ChannelReceive::GetRecCodec(CodecInst* codec) {
393 return (audio_coding_->ReceiveCodec(codec) == 0);
Niels Möller530ead42018-10-04 14:28:39 +0200394}
395
396std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
397 int64_t now_ms = rtc::TimeMillis();
398 std::vector<RtpSource> sources;
399 {
400 rtc::CritScope cs(&rtp_sources_lock_);
401 sources = contributing_sources_.GetSources(now_ms);
402 if (last_received_rtp_system_time_ms_ >=
403 now_ms - ContributingSources::kHistoryMs) {
404 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
405 RtpSourceType::SSRC);
406 sources.back().set_audio_level(last_received_rtp_audio_level_);
407 }
408 }
409 return sources;
410}
411
412void ChannelReceive::SetReceiveCodecs(
413 const std::map<int, SdpAudioFormat>& codecs) {
414 for (const auto& kv : codecs) {
415 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
416 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
417 }
418 audio_coding_->SetReceiveCodecs(codecs);
419}
420
Niels Möller530ead42018-10-04 14:28:39 +0200421// TODO(nisse): Move receive logic up to AudioReceiveStream.
422void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
423 int64_t now_ms = rtc::TimeMillis();
424 uint8_t audio_level;
425 bool voice_activity;
426 bool has_audio_level =
427 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
428
429 {
430 rtc::CritScope cs(&rtp_sources_lock_);
431 last_received_rtp_timestamp_ = packet.Timestamp();
432 last_received_rtp_system_time_ms_ = now_ms;
433 if (has_audio_level)
434 last_received_rtp_audio_level_ = audio_level;
435 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100436 contributing_sources_.Update(
437 now_ms, csrcs,
438 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200439 }
440
441 // Store playout timestamp for the received RTP packet
442 UpdatePlayoutTimestamp(false);
443
444 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
445 if (it == payload_type_frequencies_.end())
446 return;
447 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
448 RtpPacketReceived packet_copy(packet);
449 packet_copy.set_payload_type_frequency(it->second);
450
451 rtp_receive_statistics_->OnRtpPacket(packet_copy);
452
453 RTPHeader header;
454 packet_copy.GetHeader(&header);
455
456 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
457}
458
459bool ChannelReceive::ReceivePacket(const uint8_t* packet,
460 size_t packet_length,
461 const RTPHeader& header) {
462 const uint8_t* payload = packet + header.headerLength;
463 assert(packet_length >= header.headerLength);
464 size_t payload_length = packet_length - header.headerLength;
465 WebRtcRTPHeader webrtc_rtp_header = {};
466 webrtc_rtp_header.header = header;
467
Benjamin Wright84583f62018-10-04 14:22:34 -0700468 size_t payload_data_length = payload_length - header.paddingLength;
469
470 // E2EE Custom Audio Frame Decryption (This is optional).
471 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
472 rtc::Buffer decrypted_audio_payload;
473 if (frame_decryptor_ != nullptr) {
474 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
475 cricket::MEDIA_TYPE_AUDIO, payload_length);
476 decrypted_audio_payload.SetSize(max_plaintext_size);
477
478 size_t bytes_written = 0;
479 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
480 header.arrOfCSRCs + header.numCSRCs);
481 int decrypt_status = frame_decryptor_->Decrypt(
482 cricket::MEDIA_TYPE_AUDIO, csrcs,
483 /*additional_data=*/nullptr,
484 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
485 decrypted_audio_payload, &bytes_written);
486
487 // In this case just interpret the failure as a silent frame.
488 if (decrypt_status != 0) {
489 bytes_written = 0;
490 }
491
492 // Resize the decrypted audio payload to the number of bytes actually
493 // written.
494 decrypted_audio_payload.SetSize(bytes_written);
495 // Update the final payload.
496 payload = decrypted_audio_payload.data();
497 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700498 } else if (crypto_options_.sframe.require_frame_encryption) {
499 RTC_DLOG(LS_ERROR)
500 << "FrameDecryptor required but not set, dropping packet";
501 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700502 }
503
Niels Möller530ead42018-10-04 14:28:39 +0200504 if (payload_data_length == 0) {
505 webrtc_rtp_header.frameType = kEmptyFrame;
506 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
507 }
508 return OnReceivedPayloadData(payload, payload_data_length,
509 &webrtc_rtp_header);
510}
511
Niels Möller80c67622018-11-12 13:22:47 +0100512// TODO(nisse): Drop always-true return value.
513bool ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200514 // Store playout timestamp for the received RTCP packet
515 UpdatePlayoutTimestamp(true);
516
517 // Deliver RTCP packet to RTP/RTCP module for parsing
518 _rtpRtcpModule->IncomingRtcpPacket(data, length);
519
520 int64_t rtt = GetRTT();
521 if (rtt == 0) {
522 // Waiting for valid RTT.
Niels Möller80c67622018-11-12 13:22:47 +0100523 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200524 }
525
526 int64_t nack_window_ms = rtt;
527 if (nack_window_ms < kMinRetransmissionWindowMs) {
528 nack_window_ms = kMinRetransmissionWindowMs;
529 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
530 nack_window_ms = kMaxRetransmissionWindowMs;
531 }
532
533 uint32_t ntp_secs = 0;
534 uint32_t ntp_frac = 0;
535 uint32_t rtp_timestamp = 0;
536 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
537 &rtp_timestamp)) {
538 // Waiting for RTCP.
Niels Möller80c67622018-11-12 13:22:47 +0100539 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200540 }
541
542 {
543 rtc::CritScope lock(&ts_stats_lock_);
544 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
545 }
Niels Möller80c67622018-11-12 13:22:47 +0100546 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200547}
548
549int ChannelReceive::GetSpeechOutputLevelFullRange() const {
550 return _outputAudioLevel.LevelFullRange();
551}
552
553double ChannelReceive::GetTotalOutputEnergy() const {
554 return _outputAudioLevel.TotalEnergy();
555}
556
557double ChannelReceive::GetTotalOutputDuration() const {
558 return _outputAudioLevel.TotalDuration();
559}
560
561void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
562 rtc::CritScope cs(&volume_settings_critsect_);
563 _outputGain = scaling;
564}
565
Niels Möller80c67622018-11-12 13:22:47 +0100566void ChannelReceive::SetLocalSSRC(unsigned int ssrc) {
Niels Möller530ead42018-10-04 14:28:39 +0200567 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200568}
569
570// TODO(nisse): Pass ssrc in return value instead.
571int ChannelReceive::GetRemoteSSRC(unsigned int& ssrc) {
572 ssrc = remote_ssrc_;
573 return 0;
574}
575
576void ChannelReceive::RegisterReceiverCongestionControlObjects(
577 PacketRouter* packet_router) {
578 RTC_DCHECK(packet_router);
579 RTC_DCHECK(!packet_router_);
580 constexpr bool remb_candidate = false;
581 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
582 packet_router_ = packet_router;
583}
584
585void ChannelReceive::ResetReceiverCongestionControlObjects() {
586 RTC_DCHECK(packet_router_);
587 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
588 packet_router_ = nullptr;
589}
590
Niels Möller80c67622018-11-12 13:22:47 +0100591CallReceiveStatistics ChannelReceive::GetRTCPStatistics() {
Niels Möller530ead42018-10-04 14:28:39 +0200592 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100593 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200594
595 // The jitter statistics is updated for each received RTP packet and is
596 // based on received packets.
597 RtcpStatistics statistics;
598 StreamStatistician* statistician =
599 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
600 if (statistician) {
601 statistician->GetStatistics(&statistics,
602 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
603 }
604
605 stats.fractionLost = statistics.fraction_lost;
606 stats.cumulativeLost = statistics.packets_lost;
607 stats.extendedMax = statistics.extended_highest_sequence_number;
608 stats.jitterSamples = statistics.jitter;
609
610 // --- RTT
611 stats.rttMs = GetRTT();
612
613 // --- Data counters
614
615 size_t bytesReceived(0);
616 uint32_t packetsReceived(0);
617
618 if (statistician) {
619 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
620 }
621
622 stats.bytesReceived = bytesReceived;
623 stats.packetsReceived = packetsReceived;
624
625 // --- Timestamps
626 {
627 rtc::CritScope lock(&ts_stats_lock_);
628 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
629 }
Niels Möller80c67622018-11-12 13:22:47 +0100630 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200631}
632
633void ChannelReceive::SetNACKStatus(bool enable, int maxNumberOfPackets) {
634 // None of these functions can fail.
635 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
636 if (enable)
637 audio_coding_->EnableNack(maxNumberOfPackets);
638 else
639 audio_coding_->DisableNack();
640}
641
642// Called when we are missing one or more packets.
643int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
644 int length) {
645 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
646}
647
648void ChannelReceive::SetAssociatedSendChannel(ChannelSend* channel) {
649 rtc::CritScope lock(&assoc_send_channel_lock_);
650 associated_send_channel_ = channel;
651}
652
Niels Möller80c67622018-11-12 13:22:47 +0100653NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
654 NetworkStatistics stats;
655 int error = audio_coding_->GetNetworkStatistics(&stats);
656 RTC_DCHECK_EQ(0, error);
657 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200658}
659
Niels Möller80c67622018-11-12 13:22:47 +0100660AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
661 AudioDecodingCallStats stats;
662 audio_coding_->GetDecodingCallStatistics(&stats);
663 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200664}
665
666uint32_t ChannelReceive::GetDelayEstimate() const {
667 rtc::CritScope lock(&video_sync_lock_);
668 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
669}
670
Niels Möller80c67622018-11-12 13:22:47 +0100671void ChannelReceive::SetMinimumPlayoutDelay(int delayMs) {
Niels Möller530ead42018-10-04 14:28:39 +0200672 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
673 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
674 RTC_DLOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
Niels Möller80c67622018-11-12 13:22:47 +0100675 return;
Niels Möller530ead42018-10-04 14:28:39 +0200676 }
677 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
678 RTC_DLOG(LS_ERROR)
679 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200680 }
Niels Möller530ead42018-10-04 14:28:39 +0200681}
682
Niels Möller80c67622018-11-12 13:22:47 +0100683uint32_t ChannelReceive::GetPlayoutTimestamp() {
Niels Möller530ead42018-10-04 14:28:39 +0200684 {
685 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100686 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200687 }
Niels Möller530ead42018-10-04 14:28:39 +0200688}
689
690absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
691 Syncable::Info info;
692 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
693 &info.capture_time_ntp_frac, nullptr, nullptr,
694 &info.capture_time_source_clock) != 0) {
695 return absl::nullopt;
696 }
697 {
698 rtc::CritScope cs(&rtp_sources_lock_);
699 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
700 return absl::nullopt;
701 }
702 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
703 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
704 }
705 return info;
706}
707
708void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
709 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
710
711 if (!jitter_buffer_playout_timestamp_) {
712 // This can happen if this channel has not received any RTP packets. In
713 // this case, NetEq is not capable of computing a playout timestamp.
714 return;
715 }
716
717 uint16_t delay_ms = 0;
718 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
719 RTC_DLOG(LS_WARNING)
720 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
721 << " playout delay from the ADM";
722 return;
723 }
724
725 RTC_DCHECK(jitter_buffer_playout_timestamp_);
726 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
727
728 // Remove the playout delay.
729 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
730
731 {
732 rtc::CritScope lock(&video_sync_lock_);
733 if (!rtcp) {
734 playout_timestamp_rtp_ = playout_timestamp;
735 }
736 playout_delay_ms_ = delay_ms;
737 }
738}
739
740int ChannelReceive::GetRtpTimestampRateHz() const {
741 const auto format = audio_coding_->ReceiveFormat();
742 // Default to the playout frequency if we've not gotten any packets yet.
743 // TODO(ossu): Zero clockrate can only happen if we've added an external
744 // decoder for a format we don't support internally. Remove once that way of
745 // adding decoders is gone!
746 return (format && format->clockrate_hz != 0)
747 ? format->clockrate_hz
748 : audio_coding_->PlayoutFrequency();
749}
750
751int64_t ChannelReceive::GetRTT() const {
752 RtcpMode method = _rtpRtcpModule->RTCP();
753 if (method == RtcpMode::kOff) {
754 return 0;
755 }
756 std::vector<RTCPReportBlock> report_blocks;
757 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
758
759 // TODO(nisse): Could we check the return value from the ->RTT() call below,
760 // instead of checking if we have any report blocks?
761 if (report_blocks.empty()) {
762 rtc::CritScope lock(&assoc_send_channel_lock_);
763 // Tries to get RTT from an associated channel.
764 if (!associated_send_channel_) {
765 return 0;
766 }
767 return associated_send_channel_->GetRTT();
768 }
769
770 int64_t rtt = 0;
771 int64_t avg_rtt = 0;
772 int64_t max_rtt = 0;
773 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100774 // TODO(nisse): This method computes RTT based on sender reports, even though
775 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200776 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
777 0) {
778 return 0;
779 }
780 return rtt;
781}
782
783} // namespace voe
784} // namespace webrtc