blob: 1626dd2f5bb1efd365803da201638c84b5d488e2 [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öllerae4237e2018-10-05 11:28:38 +0200302 // TODO(nisse): Also set receiver_only = true, but that seems to break RTT
303 // estimation, resulting in test failures for
304 // PeerConnectionIntegrationTest.GetCaptureStartNtpTimeWithOldStatsApi
305 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200306 configuration.receive_statistics = rtp_receive_statistics_.get();
307
308 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200309
310 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
311 _rtpRtcpModule->SetSendingMediaStatus(false);
312 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
313 Init();
314}
315
316ChannelReceive::~ChannelReceive() {
317 Terminate();
318 RTC_DCHECK(!channel_state_.Get().playing);
319}
320
321void ChannelReceive::Init() {
322 channel_state_.Reset();
323
324 // --- Add modules to process thread (for periodic schedulation)
325 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
326
327 // --- ACM initialization
328 int error = audio_coding_->InitializeReceiver();
329 RTC_DCHECK_EQ(0, error);
330
331 // --- RTP/RTCP module initialization
332
333 // Ensure that RTCP is enabled by default for the created channel.
334 // Note that, the module will keep generating RTCP until it is explicitly
335 // disabled by the user.
336 // After StopListen (when no sockets exists), RTCP packets will no longer
337 // be transmitted since the Transport object will then be invalid.
338 // RTCP is enabled by default.
339 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200340
341 if (media_transport_) {
342 media_transport_->SetReceiveAudioSink(this);
343 }
Niels Möller530ead42018-10-04 14:28:39 +0200344}
345
346void ChannelReceive::Terminate() {
347 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200348
349 if (media_transport_) {
350 media_transport_->SetReceiveAudioSink(nullptr);
351 }
352
Niels Möller530ead42018-10-04 14:28:39 +0200353 // Must be called on the same thread as Init().
354 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
355
356 StopPlayout();
357
358 // The order to safely shutdown modules in a channel is:
359 // 1. De-register callbacks in modules
360 // 2. De-register modules in process thread
361 // 3. Destroy modules
362 int error = audio_coding_->RegisterTransportCallback(NULL);
363 RTC_DCHECK_EQ(0, error);
364
365 // De-register modules in process thread
366 if (_moduleProcessThreadPtr)
367 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
368
369 // End of modules shutdown
370}
371
372void ChannelReceive::SetSink(AudioSinkInterface* sink) {
373 rtc::CritScope cs(&_callbackCritSect);
374 audio_sink_ = sink;
375}
376
377int32_t ChannelReceive::StartPlayout() {
378 if (channel_state_.Get().playing) {
379 return 0;
380 }
381
382 channel_state_.SetPlaying(true);
383
384 return 0;
385}
386
387int32_t ChannelReceive::StopPlayout() {
388 if (!channel_state_.Get().playing) {
389 return 0;
390 }
391
392 channel_state_.SetPlaying(false);
393 _outputAudioLevel.Clear();
394
395 return 0;
396}
397
398int32_t ChannelReceive::GetRecCodec(CodecInst& codec) {
399 return (audio_coding_->ReceiveCodec(&codec));
400}
401
402std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
403 int64_t now_ms = rtc::TimeMillis();
404 std::vector<RtpSource> sources;
405 {
406 rtc::CritScope cs(&rtp_sources_lock_);
407 sources = contributing_sources_.GetSources(now_ms);
408 if (last_received_rtp_system_time_ms_ >=
409 now_ms - ContributingSources::kHistoryMs) {
410 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
411 RtpSourceType::SSRC);
412 sources.back().set_audio_level(last_received_rtp_audio_level_);
413 }
414 }
415 return sources;
416}
417
418void ChannelReceive::SetReceiveCodecs(
419 const std::map<int, SdpAudioFormat>& codecs) {
420 for (const auto& kv : codecs) {
421 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
422 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
423 }
424 audio_coding_->SetReceiveCodecs(codecs);
425}
426
Niels Möller530ead42018-10-04 14:28:39 +0200427// TODO(nisse): Move receive logic up to AudioReceiveStream.
428void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
429 int64_t now_ms = rtc::TimeMillis();
430 uint8_t audio_level;
431 bool voice_activity;
432 bool has_audio_level =
433 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
434
435 {
436 rtc::CritScope cs(&rtp_sources_lock_);
437 last_received_rtp_timestamp_ = packet.Timestamp();
438 last_received_rtp_system_time_ms_ = now_ms;
439 if (has_audio_level)
440 last_received_rtp_audio_level_ = audio_level;
441 std::vector<uint32_t> csrcs = packet.Csrcs();
442 contributing_sources_.Update(now_ms, csrcs);
443 }
444
445 // Store playout timestamp for the received RTP packet
446 UpdatePlayoutTimestamp(false);
447
448 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
449 if (it == payload_type_frequencies_.end())
450 return;
451 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
452 RtpPacketReceived packet_copy(packet);
453 packet_copy.set_payload_type_frequency(it->second);
454
455 rtp_receive_statistics_->OnRtpPacket(packet_copy);
456
457 RTPHeader header;
458 packet_copy.GetHeader(&header);
459
460 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
461}
462
463bool ChannelReceive::ReceivePacket(const uint8_t* packet,
464 size_t packet_length,
465 const RTPHeader& header) {
466 const uint8_t* payload = packet + header.headerLength;
467 assert(packet_length >= header.headerLength);
468 size_t payload_length = packet_length - header.headerLength;
469 WebRtcRTPHeader webrtc_rtp_header = {};
470 webrtc_rtp_header.header = header;
471
Benjamin Wright84583f62018-10-04 14:22:34 -0700472 size_t payload_data_length = payload_length - header.paddingLength;
473
474 // E2EE Custom Audio Frame Decryption (This is optional).
475 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
476 rtc::Buffer decrypted_audio_payload;
477 if (frame_decryptor_ != nullptr) {
478 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
479 cricket::MEDIA_TYPE_AUDIO, payload_length);
480 decrypted_audio_payload.SetSize(max_plaintext_size);
481
482 size_t bytes_written = 0;
483 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
484 header.arrOfCSRCs + header.numCSRCs);
485 int decrypt_status = frame_decryptor_->Decrypt(
486 cricket::MEDIA_TYPE_AUDIO, csrcs,
487 /*additional_data=*/nullptr,
488 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
489 decrypted_audio_payload, &bytes_written);
490
491 // In this case just interpret the failure as a silent frame.
492 if (decrypt_status != 0) {
493 bytes_written = 0;
494 }
495
496 // Resize the decrypted audio payload to the number of bytes actually
497 // written.
498 decrypted_audio_payload.SetSize(bytes_written);
499 // Update the final payload.
500 payload = decrypted_audio_payload.data();
501 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700502 } else if (crypto_options_.sframe.require_frame_encryption) {
503 RTC_DLOG(LS_ERROR)
504 << "FrameDecryptor required but not set, dropping packet";
505 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700506 }
507
Niels Möller530ead42018-10-04 14:28:39 +0200508 if (payload_data_length == 0) {
509 webrtc_rtp_header.frameType = kEmptyFrame;
510 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
511 }
512 return OnReceivedPayloadData(payload, payload_data_length,
513 &webrtc_rtp_header);
514}
515
516int32_t ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
517 // Store playout timestamp for the received RTCP packet
518 UpdatePlayoutTimestamp(true);
519
520 // Deliver RTCP packet to RTP/RTCP module for parsing
521 _rtpRtcpModule->IncomingRtcpPacket(data, length);
522
523 int64_t rtt = GetRTT();
524 if (rtt == 0) {
525 // Waiting for valid RTT.
526 return 0;
527 }
528
529 int64_t nack_window_ms = rtt;
530 if (nack_window_ms < kMinRetransmissionWindowMs) {
531 nack_window_ms = kMinRetransmissionWindowMs;
532 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
533 nack_window_ms = kMaxRetransmissionWindowMs;
534 }
535
536 uint32_t ntp_secs = 0;
537 uint32_t ntp_frac = 0;
538 uint32_t rtp_timestamp = 0;
539 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
540 &rtp_timestamp)) {
541 // Waiting for RTCP.
542 return 0;
543 }
544
545 {
546 rtc::CritScope lock(&ts_stats_lock_);
547 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
548 }
549 return 0;
550}
551
552int ChannelReceive::GetSpeechOutputLevelFullRange() const {
553 return _outputAudioLevel.LevelFullRange();
554}
555
556double ChannelReceive::GetTotalOutputEnergy() const {
557 return _outputAudioLevel.TotalEnergy();
558}
559
560double ChannelReceive::GetTotalOutputDuration() const {
561 return _outputAudioLevel.TotalDuration();
562}
563
564void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
565 rtc::CritScope cs(&volume_settings_critsect_);
566 _outputGain = scaling;
567}
568
569int ChannelReceive::SetLocalSSRC(unsigned int ssrc) {
570 _rtpRtcpModule->SetSSRC(ssrc);
571 return 0;
572}
573
574// TODO(nisse): Pass ssrc in return value instead.
575int ChannelReceive::GetRemoteSSRC(unsigned int& ssrc) {
576 ssrc = remote_ssrc_;
577 return 0;
578}
579
580void ChannelReceive::RegisterReceiverCongestionControlObjects(
581 PacketRouter* packet_router) {
582 RTC_DCHECK(packet_router);
583 RTC_DCHECK(!packet_router_);
584 constexpr bool remb_candidate = false;
585 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
586 packet_router_ = packet_router;
587}
588
589void ChannelReceive::ResetReceiverCongestionControlObjects() {
590 RTC_DCHECK(packet_router_);
591 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
592 packet_router_ = nullptr;
593}
594
595int ChannelReceive::GetRTPStatistics(CallReceiveStatistics& stats) {
596 // --- RtcpStatistics
597
598 // The jitter statistics is updated for each received RTP packet and is
599 // based on received packets.
600 RtcpStatistics statistics;
601 StreamStatistician* statistician =
602 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
603 if (statistician) {
604 statistician->GetStatistics(&statistics,
605 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
606 }
607
608 stats.fractionLost = statistics.fraction_lost;
609 stats.cumulativeLost = statistics.packets_lost;
610 stats.extendedMax = statistics.extended_highest_sequence_number;
611 stats.jitterSamples = statistics.jitter;
612
613 // --- RTT
614 stats.rttMs = GetRTT();
615
616 // --- Data counters
617
618 size_t bytesReceived(0);
619 uint32_t packetsReceived(0);
620
621 if (statistician) {
622 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
623 }
624
625 stats.bytesReceived = bytesReceived;
626 stats.packetsReceived = packetsReceived;
627
628 // --- Timestamps
629 {
630 rtc::CritScope lock(&ts_stats_lock_);
631 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
632 }
633 return 0;
634}
635
636void ChannelReceive::SetNACKStatus(bool enable, int maxNumberOfPackets) {
637 // None of these functions can fail.
638 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
639 if (enable)
640 audio_coding_->EnableNack(maxNumberOfPackets);
641 else
642 audio_coding_->DisableNack();
643}
644
645// Called when we are missing one or more packets.
646int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
647 int length) {
648 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
649}
650
651void ChannelReceive::SetAssociatedSendChannel(ChannelSend* channel) {
652 rtc::CritScope lock(&assoc_send_channel_lock_);
653 associated_send_channel_ = channel;
654}
655
656int ChannelReceive::GetNetworkStatistics(NetworkStatistics& stats) {
657 return audio_coding_->GetNetworkStatistics(&stats);
658}
659
660void ChannelReceive::GetDecodingCallStatistics(
661 AudioDecodingCallStats* stats) const {
662 audio_coding_->GetDecodingCallStatistics(stats);
663}
664
665uint32_t ChannelReceive::GetDelayEstimate() const {
666 rtc::CritScope lock(&video_sync_lock_);
667 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
668}
669
670int ChannelReceive::SetMinimumPlayoutDelay(int delayMs) {
671 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
672 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
673 RTC_DLOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
674 return -1;
675 }
676 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
677 RTC_DLOG(LS_ERROR)
678 << "SetMinimumPlayoutDelay() failed to set min playout delay";
679 return -1;
680 }
681 return 0;
682}
683
684int ChannelReceive::GetPlayoutTimestamp(unsigned int& timestamp) {
685 uint32_t playout_timestamp_rtp = 0;
686 {
687 rtc::CritScope lock(&video_sync_lock_);
688 playout_timestamp_rtp = playout_timestamp_rtp_;
689 }
690 if (playout_timestamp_rtp == 0) {
691 RTC_DLOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
692 return -1;
693 }
694 timestamp = playout_timestamp_rtp;
695 return 0;
696}
697
698absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
699 Syncable::Info info;
700 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
701 &info.capture_time_ntp_frac, nullptr, nullptr,
702 &info.capture_time_source_clock) != 0) {
703 return absl::nullopt;
704 }
705 {
706 rtc::CritScope cs(&rtp_sources_lock_);
707 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
708 return absl::nullopt;
709 }
710 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
711 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
712 }
713 return info;
714}
715
716void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
717 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
718
719 if (!jitter_buffer_playout_timestamp_) {
720 // This can happen if this channel has not received any RTP packets. In
721 // this case, NetEq is not capable of computing a playout timestamp.
722 return;
723 }
724
725 uint16_t delay_ms = 0;
726 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
727 RTC_DLOG(LS_WARNING)
728 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
729 << " playout delay from the ADM";
730 return;
731 }
732
733 RTC_DCHECK(jitter_buffer_playout_timestamp_);
734 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
735
736 // Remove the playout delay.
737 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
738
739 {
740 rtc::CritScope lock(&video_sync_lock_);
741 if (!rtcp) {
742 playout_timestamp_rtp_ = playout_timestamp;
743 }
744 playout_delay_ms_ = delay_ms;
745 }
746}
747
748int ChannelReceive::GetRtpTimestampRateHz() const {
749 const auto format = audio_coding_->ReceiveFormat();
750 // Default to the playout frequency if we've not gotten any packets yet.
751 // TODO(ossu): Zero clockrate can only happen if we've added an external
752 // decoder for a format we don't support internally. Remove once that way of
753 // adding decoders is gone!
754 return (format && format->clockrate_hz != 0)
755 ? format->clockrate_hz
756 : audio_coding_->PlayoutFrequency();
757}
758
759int64_t ChannelReceive::GetRTT() const {
760 RtcpMode method = _rtpRtcpModule->RTCP();
761 if (method == RtcpMode::kOff) {
762 return 0;
763 }
764 std::vector<RTCPReportBlock> report_blocks;
765 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
766
767 // TODO(nisse): Could we check the return value from the ->RTT() call below,
768 // instead of checking if we have any report blocks?
769 if (report_blocks.empty()) {
770 rtc::CritScope lock(&assoc_send_channel_lock_);
771 // Tries to get RTT from an associated channel.
772 if (!associated_send_channel_) {
773 return 0;
774 }
775 return associated_send_channel_->GetRTT();
776 }
777
778 int64_t rtt = 0;
779 int64_t avg_rtt = 0;
780 int64_t max_rtt = 0;
781 int64_t min_rtt = 0;
782 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
783 0) {
784 return 0;
785 }
786 return rtt;
787}
788
789} // namespace voe
790} // namespace webrtc