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