blob: fbe15003bb1948b2be982af8ab412453328dff00 [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
54} // namespace
55
Niels Möller530ead42018-10-04 14:28:39 +020056int32_t ChannelReceive::OnReceivedPayloadData(
57 const uint8_t* payloadData,
58 size_t payloadSize,
59 const WebRtcRTPHeader* rtpHeader) {
60 if (!channel_state_.Get().playing) {
61 // Avoid inserting into NetEQ when we are not playing. Count the
62 // packet as discarded.
63 return 0;
64 }
65
66 // Push the incoming payload (parsed and ready for decoding) into the ACM
67 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
68 0) {
69 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
70 "push data to the ACM";
71 return -1;
72 }
73
74 int64_t round_trip_time = 0;
75 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
76
77 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
78 if (!nack_list.empty()) {
79 // Can't use nack_list.data() since it's not supported by all
80 // compilers.
81 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
82 }
83 return 0;
84}
85
86AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
87 int sample_rate_hz,
88 AudioFrame* audio_frame) {
89 audio_frame->sample_rate_hz_ = sample_rate_hz;
90
91 unsigned int ssrc;
92 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
93 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(ssrc));
94 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
95 bool muted;
96 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
97 &muted) == -1) {
98 RTC_DLOG(LS_ERROR)
99 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
100 // In all likelihood, the audio in this frame is garbage. We return an
101 // error so that the audio mixer module doesn't add it to the mix. As
102 // a result, it won't be played out and the actions skipped here are
103 // irrelevant.
104 return AudioMixer::Source::AudioFrameInfo::kError;
105 }
106
107 if (muted) {
108 // TODO(henrik.lundin): We should be able to do better than this. But we
109 // will have to go through all the cases below where the audio samples may
110 // be used, and handle the muted case in some way.
111 AudioFrameOperations::Mute(audio_frame);
112 }
113
114 {
115 // Pass the audio buffers to an optional sink callback, before applying
116 // scaling/panning, as that applies to the mix operation.
117 // External recipients of the audio (e.g. via AudioTrack), will do their
118 // own mixing/dynamic processing.
119 rtc::CritScope cs(&_callbackCritSect);
120 if (audio_sink_) {
121 AudioSinkInterface::Data data(
122 audio_frame->data(), audio_frame->samples_per_channel_,
123 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
124 audio_frame->timestamp_);
125 audio_sink_->OnData(data);
126 }
127 }
128
129 float output_gain = 1.0f;
130 {
131 rtc::CritScope cs(&volume_settings_critsect_);
132 output_gain = _outputGain;
133 }
134
135 // Output volume scaling
136 if (output_gain < 0.99f || output_gain > 1.01f) {
137 // TODO(solenberg): Combine with mute state - this can cause clicks!
138 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
139 }
140
141 // Measure audio level (0-9)
142 // TODO(henrik.lundin) Use the |muted| information here too.
143 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
144 // https://crbug.com/webrtc/7517).
145 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
146
147 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
148 // The first frame with a valid rtp timestamp.
149 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
150 }
151
152 if (capture_start_rtp_time_stamp_ >= 0) {
153 // audio_frame.timestamp_ should be valid from now on.
154
155 // Compute elapsed time.
156 int64_t unwrap_timestamp =
157 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
158 audio_frame->elapsed_time_ms_ =
159 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
160 (GetRtpTimestampRateHz() / 1000);
161
162 {
163 rtc::CritScope lock(&ts_stats_lock_);
164 // Compute ntp time.
165 audio_frame->ntp_time_ms_ =
166 ntp_estimator_.Estimate(audio_frame->timestamp_);
167 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
168 if (audio_frame->ntp_time_ms_ > 0) {
169 // Compute |capture_start_ntp_time_ms_| so that
170 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
171 capture_start_ntp_time_ms_ =
172 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
173 }
174 }
175 }
176
177 {
178 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
179 audio_coding_->TargetDelayMs());
180 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
181 rtc::CritScope lock(&video_sync_lock_);
182 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
183 jitter_buffer_delay + playout_delay_ms_);
184 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
185 jitter_buffer_delay);
186 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
187 playout_delay_ms_);
188 }
189
190 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
191 : AudioMixer::Source::AudioFrameInfo::kNormal;
192}
193
194int ChannelReceive::PreferredSampleRate() const {
195 // Return the bigger of playout and receive frequency in the ACM.
196 return std::max(audio_coding_->ReceiveFrequency(),
197 audio_coding_->PlayoutFrequency());
198}
199
200ChannelReceive::ChannelReceive(
201 ProcessThread* module_process_thread,
202 AudioDeviceModule* audio_device_module,
Niels Möllerae4237e2018-10-05 11:28:38 +0200203 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200204 RtcEventLog* rtc_event_log,
205 uint32_t remote_ssrc,
206 size_t jitter_buffer_max_packets,
207 bool jitter_buffer_fast_playout,
208 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700209 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700210 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700211 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200212 : event_log_(rtc_event_log),
213 rtp_receive_statistics_(
214 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
215 remote_ssrc_(remote_ssrc),
216 _outputAudioLevel(),
217 ntp_estimator_(Clock::GetRealTimeClock()),
218 playout_timestamp_rtp_(0),
219 playout_delay_ms_(0),
220 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
221 capture_start_rtp_time_stamp_(-1),
222 capture_start_ntp_time_ms_(-1),
223 _moduleProcessThreadPtr(module_process_thread),
224 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200225 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700226 associated_send_channel_(nullptr),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700227 frame_decryptor_(frame_decryptor),
228 crypto_options_(crypto_options) {
Niels Möller530ead42018-10-04 14:28:39 +0200229 RTC_DCHECK(module_process_thread);
230 RTC_DCHECK(audio_device_module);
231 AudioCodingModule::Config acm_config;
232 acm_config.decoder_factory = decoder_factory;
233 acm_config.neteq_config.codec_pair_id = codec_pair_id;
234 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
235 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
236 acm_config.neteq_config.enable_muted_state = true;
237 audio_coding_.reset(AudioCodingModule::Create(acm_config));
238
239 _outputAudioLevel.Clear();
240
241 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
242 RtpRtcp::Configuration configuration;
243 configuration.audio = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200244 // TODO(nisse): Also set receiver_only = true, but that seems to break RTT
245 // estimation, resulting in test failures for
246 // PeerConnectionIntegrationTest.GetCaptureStartNtpTimeWithOldStatsApi
247 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200248 configuration.receive_statistics = rtp_receive_statistics_.get();
249
250 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200251
252 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
253 _rtpRtcpModule->SetSendingMediaStatus(false);
254 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
255 Init();
256}
257
258ChannelReceive::~ChannelReceive() {
259 Terminate();
260 RTC_DCHECK(!channel_state_.Get().playing);
261}
262
263void ChannelReceive::Init() {
264 channel_state_.Reset();
265
266 // --- Add modules to process thread (for periodic schedulation)
267 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
268
269 // --- ACM initialization
270 int error = audio_coding_->InitializeReceiver();
271 RTC_DCHECK_EQ(0, error);
272
273 // --- RTP/RTCP module initialization
274
275 // Ensure that RTCP is enabled by default for the created channel.
276 // Note that, the module will keep generating RTCP until it is explicitly
277 // disabled by the user.
278 // After StopListen (when no sockets exists), RTCP packets will no longer
279 // be transmitted since the Transport object will then be invalid.
280 // RTCP is enabled by default.
281 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
282}
283
284void ChannelReceive::Terminate() {
285 RTC_DCHECK(construction_thread_.CalledOnValidThread());
286 // Must be called on the same thread as Init().
287 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
288
289 StopPlayout();
290
291 // The order to safely shutdown modules in a channel is:
292 // 1. De-register callbacks in modules
293 // 2. De-register modules in process thread
294 // 3. Destroy modules
295 int error = audio_coding_->RegisterTransportCallback(NULL);
296 RTC_DCHECK_EQ(0, error);
297
298 // De-register modules in process thread
299 if (_moduleProcessThreadPtr)
300 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
301
302 // End of modules shutdown
303}
304
305void ChannelReceive::SetSink(AudioSinkInterface* sink) {
306 rtc::CritScope cs(&_callbackCritSect);
307 audio_sink_ = sink;
308}
309
310int32_t ChannelReceive::StartPlayout() {
311 if (channel_state_.Get().playing) {
312 return 0;
313 }
314
315 channel_state_.SetPlaying(true);
316
317 return 0;
318}
319
320int32_t ChannelReceive::StopPlayout() {
321 if (!channel_state_.Get().playing) {
322 return 0;
323 }
324
325 channel_state_.SetPlaying(false);
326 _outputAudioLevel.Clear();
327
328 return 0;
329}
330
331int32_t ChannelReceive::GetRecCodec(CodecInst& codec) {
332 return (audio_coding_->ReceiveCodec(&codec));
333}
334
335std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
336 int64_t now_ms = rtc::TimeMillis();
337 std::vector<RtpSource> sources;
338 {
339 rtc::CritScope cs(&rtp_sources_lock_);
340 sources = contributing_sources_.GetSources(now_ms);
341 if (last_received_rtp_system_time_ms_ >=
342 now_ms - ContributingSources::kHistoryMs) {
343 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
344 RtpSourceType::SSRC);
345 sources.back().set_audio_level(last_received_rtp_audio_level_);
346 }
347 }
348 return sources;
349}
350
351void ChannelReceive::SetReceiveCodecs(
352 const std::map<int, SdpAudioFormat>& codecs) {
353 for (const auto& kv : codecs) {
354 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
355 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
356 }
357 audio_coding_->SetReceiveCodecs(codecs);
358}
359
Niels Möller530ead42018-10-04 14:28:39 +0200360// TODO(nisse): Move receive logic up to AudioReceiveStream.
361void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
362 int64_t now_ms = rtc::TimeMillis();
363 uint8_t audio_level;
364 bool voice_activity;
365 bool has_audio_level =
366 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
367
368 {
369 rtc::CritScope cs(&rtp_sources_lock_);
370 last_received_rtp_timestamp_ = packet.Timestamp();
371 last_received_rtp_system_time_ms_ = now_ms;
372 if (has_audio_level)
373 last_received_rtp_audio_level_ = audio_level;
374 std::vector<uint32_t> csrcs = packet.Csrcs();
375 contributing_sources_.Update(now_ms, csrcs);
376 }
377
378 // Store playout timestamp for the received RTP packet
379 UpdatePlayoutTimestamp(false);
380
381 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
382 if (it == payload_type_frequencies_.end())
383 return;
384 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
385 RtpPacketReceived packet_copy(packet);
386 packet_copy.set_payload_type_frequency(it->second);
387
388 rtp_receive_statistics_->OnRtpPacket(packet_copy);
389
390 RTPHeader header;
391 packet_copy.GetHeader(&header);
392
393 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
394}
395
396bool ChannelReceive::ReceivePacket(const uint8_t* packet,
397 size_t packet_length,
398 const RTPHeader& header) {
399 const uint8_t* payload = packet + header.headerLength;
400 assert(packet_length >= header.headerLength);
401 size_t payload_length = packet_length - header.headerLength;
402 WebRtcRTPHeader webrtc_rtp_header = {};
403 webrtc_rtp_header.header = header;
404
Benjamin Wright84583f62018-10-04 14:22:34 -0700405 size_t payload_data_length = payload_length - header.paddingLength;
406
407 // E2EE Custom Audio Frame Decryption (This is optional).
408 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
409 rtc::Buffer decrypted_audio_payload;
410 if (frame_decryptor_ != nullptr) {
411 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
412 cricket::MEDIA_TYPE_AUDIO, payload_length);
413 decrypted_audio_payload.SetSize(max_plaintext_size);
414
415 size_t bytes_written = 0;
416 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
417 header.arrOfCSRCs + header.numCSRCs);
418 int decrypt_status = frame_decryptor_->Decrypt(
419 cricket::MEDIA_TYPE_AUDIO, csrcs,
420 /*additional_data=*/nullptr,
421 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
422 decrypted_audio_payload, &bytes_written);
423
424 // In this case just interpret the failure as a silent frame.
425 if (decrypt_status != 0) {
426 bytes_written = 0;
427 }
428
429 // Resize the decrypted audio payload to the number of bytes actually
430 // written.
431 decrypted_audio_payload.SetSize(bytes_written);
432 // Update the final payload.
433 payload = decrypted_audio_payload.data();
434 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700435 } else if (crypto_options_.sframe.require_frame_encryption) {
436 RTC_DLOG(LS_ERROR)
437 << "FrameDecryptor required but not set, dropping packet";
438 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700439 }
440
Niels Möller530ead42018-10-04 14:28:39 +0200441 if (payload_data_length == 0) {
442 webrtc_rtp_header.frameType = kEmptyFrame;
443 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
444 }
445 return OnReceivedPayloadData(payload, payload_data_length,
446 &webrtc_rtp_header);
447}
448
449int32_t ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
450 // Store playout timestamp for the received RTCP packet
451 UpdatePlayoutTimestamp(true);
452
453 // Deliver RTCP packet to RTP/RTCP module for parsing
454 _rtpRtcpModule->IncomingRtcpPacket(data, length);
455
456 int64_t rtt = GetRTT();
457 if (rtt == 0) {
458 // Waiting for valid RTT.
459 return 0;
460 }
461
462 int64_t nack_window_ms = rtt;
463 if (nack_window_ms < kMinRetransmissionWindowMs) {
464 nack_window_ms = kMinRetransmissionWindowMs;
465 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
466 nack_window_ms = kMaxRetransmissionWindowMs;
467 }
468
469 uint32_t ntp_secs = 0;
470 uint32_t ntp_frac = 0;
471 uint32_t rtp_timestamp = 0;
472 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
473 &rtp_timestamp)) {
474 // Waiting for RTCP.
475 return 0;
476 }
477
478 {
479 rtc::CritScope lock(&ts_stats_lock_);
480 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
481 }
482 return 0;
483}
484
485int ChannelReceive::GetSpeechOutputLevelFullRange() const {
486 return _outputAudioLevel.LevelFullRange();
487}
488
489double ChannelReceive::GetTotalOutputEnergy() const {
490 return _outputAudioLevel.TotalEnergy();
491}
492
493double ChannelReceive::GetTotalOutputDuration() const {
494 return _outputAudioLevel.TotalDuration();
495}
496
497void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
498 rtc::CritScope cs(&volume_settings_critsect_);
499 _outputGain = scaling;
500}
501
502int ChannelReceive::SetLocalSSRC(unsigned int ssrc) {
503 _rtpRtcpModule->SetSSRC(ssrc);
504 return 0;
505}
506
507// TODO(nisse): Pass ssrc in return value instead.
508int ChannelReceive::GetRemoteSSRC(unsigned int& ssrc) {
509 ssrc = remote_ssrc_;
510 return 0;
511}
512
513void ChannelReceive::RegisterReceiverCongestionControlObjects(
514 PacketRouter* packet_router) {
515 RTC_DCHECK(packet_router);
516 RTC_DCHECK(!packet_router_);
517 constexpr bool remb_candidate = false;
518 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
519 packet_router_ = packet_router;
520}
521
522void ChannelReceive::ResetReceiverCongestionControlObjects() {
523 RTC_DCHECK(packet_router_);
524 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
525 packet_router_ = nullptr;
526}
527
528int ChannelReceive::GetRTPStatistics(CallReceiveStatistics& stats) {
529 // --- RtcpStatistics
530
531 // The jitter statistics is updated for each received RTP packet and is
532 // based on received packets.
533 RtcpStatistics statistics;
534 StreamStatistician* statistician =
535 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
536 if (statistician) {
537 statistician->GetStatistics(&statistics,
538 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
539 }
540
541 stats.fractionLost = statistics.fraction_lost;
542 stats.cumulativeLost = statistics.packets_lost;
543 stats.extendedMax = statistics.extended_highest_sequence_number;
544 stats.jitterSamples = statistics.jitter;
545
546 // --- RTT
547 stats.rttMs = GetRTT();
548
549 // --- Data counters
550
551 size_t bytesReceived(0);
552 uint32_t packetsReceived(0);
553
554 if (statistician) {
555 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
556 }
557
558 stats.bytesReceived = bytesReceived;
559 stats.packetsReceived = packetsReceived;
560
561 // --- Timestamps
562 {
563 rtc::CritScope lock(&ts_stats_lock_);
564 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
565 }
566 return 0;
567}
568
569void ChannelReceive::SetNACKStatus(bool enable, int maxNumberOfPackets) {
570 // None of these functions can fail.
571 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
572 if (enable)
573 audio_coding_->EnableNack(maxNumberOfPackets);
574 else
575 audio_coding_->DisableNack();
576}
577
578// Called when we are missing one or more packets.
579int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
580 int length) {
581 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
582}
583
584void ChannelReceive::SetAssociatedSendChannel(ChannelSend* channel) {
585 rtc::CritScope lock(&assoc_send_channel_lock_);
586 associated_send_channel_ = channel;
587}
588
589int ChannelReceive::GetNetworkStatistics(NetworkStatistics& stats) {
590 return audio_coding_->GetNetworkStatistics(&stats);
591}
592
593void ChannelReceive::GetDecodingCallStatistics(
594 AudioDecodingCallStats* stats) const {
595 audio_coding_->GetDecodingCallStatistics(stats);
596}
597
598uint32_t ChannelReceive::GetDelayEstimate() const {
599 rtc::CritScope lock(&video_sync_lock_);
600 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
601}
602
603int ChannelReceive::SetMinimumPlayoutDelay(int delayMs) {
604 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
605 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
606 RTC_DLOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
607 return -1;
608 }
609 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
610 RTC_DLOG(LS_ERROR)
611 << "SetMinimumPlayoutDelay() failed to set min playout delay";
612 return -1;
613 }
614 return 0;
615}
616
617int ChannelReceive::GetPlayoutTimestamp(unsigned int& timestamp) {
618 uint32_t playout_timestamp_rtp = 0;
619 {
620 rtc::CritScope lock(&video_sync_lock_);
621 playout_timestamp_rtp = playout_timestamp_rtp_;
622 }
623 if (playout_timestamp_rtp == 0) {
624 RTC_DLOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
625 return -1;
626 }
627 timestamp = playout_timestamp_rtp;
628 return 0;
629}
630
631absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
632 Syncable::Info info;
633 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
634 &info.capture_time_ntp_frac, nullptr, nullptr,
635 &info.capture_time_source_clock) != 0) {
636 return absl::nullopt;
637 }
638 {
639 rtc::CritScope cs(&rtp_sources_lock_);
640 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
641 return absl::nullopt;
642 }
643 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
644 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
645 }
646 return info;
647}
648
649void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
650 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
651
652 if (!jitter_buffer_playout_timestamp_) {
653 // This can happen if this channel has not received any RTP packets. In
654 // this case, NetEq is not capable of computing a playout timestamp.
655 return;
656 }
657
658 uint16_t delay_ms = 0;
659 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
660 RTC_DLOG(LS_WARNING)
661 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
662 << " playout delay from the ADM";
663 return;
664 }
665
666 RTC_DCHECK(jitter_buffer_playout_timestamp_);
667 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
668
669 // Remove the playout delay.
670 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
671
672 {
673 rtc::CritScope lock(&video_sync_lock_);
674 if (!rtcp) {
675 playout_timestamp_rtp_ = playout_timestamp;
676 }
677 playout_delay_ms_ = delay_ms;
678 }
679}
680
681int ChannelReceive::GetRtpTimestampRateHz() const {
682 const auto format = audio_coding_->ReceiveFormat();
683 // Default to the playout frequency if we've not gotten any packets yet.
684 // TODO(ossu): Zero clockrate can only happen if we've added an external
685 // decoder for a format we don't support internally. Remove once that way of
686 // adding decoders is gone!
687 return (format && format->clockrate_hz != 0)
688 ? format->clockrate_hz
689 : audio_coding_->PlayoutFrequency();
690}
691
692int64_t ChannelReceive::GetRTT() const {
693 RtcpMode method = _rtpRtcpModule->RTCP();
694 if (method == RtcpMode::kOff) {
695 return 0;
696 }
697 std::vector<RTCPReportBlock> report_blocks;
698 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
699
700 // TODO(nisse): Could we check the return value from the ->RTT() call below,
701 // instead of checking if we have any report blocks?
702 if (report_blocks.empty()) {
703 rtc::CritScope lock(&assoc_send_channel_lock_);
704 // Tries to get RTT from an associated channel.
705 if (!associated_send_channel_) {
706 return 0;
707 }
708 return associated_send_channel_->GetRTT();
709 }
710
711 int64_t rtt = 0;
712 int64_t avg_rtt = 0;
713 int64_t max_rtt = 0;
714 int64_t min_rtt = 0;
715 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
716 0) {
717 return 0;
718 }
719 return rtt;
720}
721
722} // namespace voe
723} // namespace webrtc