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