blob: 483147fa9eed00e4e60fb1b4bdb0531560f911da [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"
Niels Möller349ade32018-11-16 09:50:42 +010021#include "audio/audio_level.h"
Niels Möller530ead42018-10-04 14:28:39 +020022#include "audio/channel_send.h"
23#include "audio/utility/audio_frame_operations.h"
24#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
25#include "logging/rtc_event_log/rtc_event_log.h"
26#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
Niels Möller349ade32018-11-16 09:50:42 +010027#include "modules/audio_coding/include/audio_coding_module.h"
Niels Möller530ead42018-10-04 14:28:39 +020028#include "modules/audio_device/include/audio_device.h"
29#include "modules/pacing/packet_router.h"
30#include "modules/rtp_rtcp/include/receive_statistics.h"
Niels Möller349ade32018-11-16 09:50:42 +010031#include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
32#include "modules/rtp_rtcp/include/rtp_rtcp.h"
33#include "modules/rtp_rtcp/source/contributing_sources.h"
Yves Gerey988cc082018-10-23 12:03:01 +020034#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020035#include "modules/rtp_rtcp/source/rtp_packet_received.h"
36#include "modules/utility/include/process_thread.h"
37#include "rtc_base/checks.h"
38#include "rtc_base/criticalsection.h"
39#include "rtc_base/format_macros.h"
40#include "rtc_base/location.h"
41#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010042#include "rtc_base/numerics/safe_minmax.h"
43#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020044#include "rtc_base/thread_checker.h"
45#include "rtc_base/timeutils.h"
46#include "system_wrappers/include/metrics.h"
47
48namespace webrtc {
49namespace voe {
50
51namespace {
52
53constexpr double kAudioSampleDurationSeconds = 0.01;
54constexpr int64_t kMaxRetransmissionWindowMs = 1000;
55constexpr int64_t kMinRetransmissionWindowMs = 30;
56
57// Video Sync.
58constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
59constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
60
Niels Möller7d76a312018-10-26 12:57:07 +020061webrtc::FrameType WebrtcFrameTypeForMediaTransportFrameType(
62 MediaTransportEncodedAudioFrame::FrameType frame_type) {
63 switch (frame_type) {
64 case MediaTransportEncodedAudioFrame::FrameType::kSpeech:
65 return kAudioFrameSpeech;
66 break;
67
68 case MediaTransportEncodedAudioFrame::FrameType::
69 kDiscountinuousTransmission:
70 return kAudioFrameCN;
71 break;
72 }
73}
74
75WebRtcRTPHeader CreateWebrtcRTPHeaderForMediaTransportFrame(
76 const MediaTransportEncodedAudioFrame& frame,
77 uint64_t channel_id) {
78 webrtc::WebRtcRTPHeader webrtc_header = {};
79 webrtc_header.header.payloadType = frame.payload_type();
80 webrtc_header.header.payload_type_frequency = frame.sampling_rate_hz();
81 webrtc_header.header.timestamp = frame.starting_sample_index();
82 webrtc_header.header.sequenceNumber = frame.sequence_number();
83
84 webrtc_header.frameType =
85 WebrtcFrameTypeForMediaTransportFrameType(frame.frame_type());
86
87 webrtc_header.header.ssrc = static_cast<uint32_t>(channel_id);
88
89 // The rest are initialized by the RTPHeader constructor.
90 return webrtc_header;
91}
92
Niels Möller349ade32018-11-16 09:50:42 +010093class ChannelReceive : public ChannelReceiveInterface,
94 public MediaTransportAudioSinkInterface {
95 public:
96 // Used for receive streams.
97 ChannelReceive(ProcessThread* module_process_thread,
98 AudioDeviceModule* audio_device_module,
99 MediaTransportInterface* media_transport,
100 Transport* rtcp_send_transport,
101 RtcEventLog* rtc_event_log,
102 uint32_t remote_ssrc,
103 size_t jitter_buffer_max_packets,
104 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100105 int jitter_buffer_min_delay_ms,
Niels Möller349ade32018-11-16 09:50:42 +0100106 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
107 absl::optional<AudioCodecPairId> codec_pair_id,
108 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
109 const webrtc::CryptoOptions& crypto_options);
110 ~ChannelReceive() override;
111
112 void SetSink(AudioSinkInterface* sink) override;
113
114 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
115
116 // API methods
117
118 void StartPlayout() override;
119 void StopPlayout() override;
120
121 // Codecs
122 bool GetRecCodec(CodecInst* codec) const override;
123
124 bool ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
125
126 // RtpPacketSinkInterface.
127 void OnRtpPacket(const RtpPacketReceived& packet) override;
128
129 // Muting, Volume and Level.
130 void SetChannelOutputVolumeScaling(float scaling) override;
131 int GetSpeechOutputLevelFullRange() const override;
132 // See description of "totalAudioEnergy" in the WebRTC stats spec:
133 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
134 double GetTotalOutputEnergy() const override;
135 double GetTotalOutputDuration() const override;
136
137 // Stats.
138 NetworkStatistics GetNetworkStatistics() const override;
139 AudioDecodingCallStats GetDecodingCallStatistics() const override;
140
141 // Audio+Video Sync.
142 uint32_t GetDelayEstimate() const override;
143 void SetMinimumPlayoutDelay(int delayMs) override;
144 uint32_t GetPlayoutTimestamp() const override;
145
146 // Produces the transport-related timestamps; current_delay_ms is left unset.
147 absl::optional<Syncable::Info> GetSyncInfo() const override;
148
149 // RTP+RTCP
150 void SetLocalSSRC(unsigned int ssrc) override;
151
152 void RegisterReceiverCongestionControlObjects(
153 PacketRouter* packet_router) override;
154 void ResetReceiverCongestionControlObjects() override;
155
156 CallReceiveStatistics GetRTCPStatistics() const override;
157 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
158
159 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
160 int sample_rate_hz,
161 AudioFrame* audio_frame) override;
162
163 int PreferredSampleRate() const override;
164
165 // Associate to a send channel.
166 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100167 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100168
169 std::vector<RtpSource> GetSources() const override;
170
171 private:
Niels Möller349ade32018-11-16 09:50:42 +0100172 bool ReceivePacket(const uint8_t* packet,
173 size_t packet_length,
174 const RTPHeader& header);
175 int ResendPackets(const uint16_t* sequence_numbers, int length);
176 void UpdatePlayoutTimestamp(bool rtcp);
177
178 int GetRtpTimestampRateHz() const;
179 int64_t GetRTT() const;
180
181 // MediaTransportAudioSinkInterface override;
182 void OnData(uint64_t channel_id,
183 MediaTransportEncodedAudioFrame frame) override;
184
185 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
186 size_t payloadSize,
187 const WebRtcRTPHeader* rtpHeader);
188
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100189 bool Playing() const {
190 rtc::CritScope lock(&playing_lock_);
191 return playing_;
192 }
193
Niels Möller349ade32018-11-16 09:50:42 +0100194 // Thread checkers document and lock usage of some methods to specific threads
195 // we know about. The goal is to eventually split up voe::ChannelReceive into
196 // parts with single-threaded semantics, and thereby reduce the need for
197 // locks.
198 rtc::ThreadChecker worker_thread_checker_;
199 rtc::ThreadChecker module_process_thread_checker_;
200 // Methods accessed from audio and video threads are checked for sequential-
201 // only access. We don't necessarily own and control these threads, so thread
202 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
203 // audio thread to another, but access is still sequential.
204 rtc::RaceChecker audio_thread_race_checker_;
205 rtc::RaceChecker video_capture_thread_race_checker_;
206 rtc::CriticalSection _callbackCritSect;
207 rtc::CriticalSection volume_settings_critsect_;
208
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100209 rtc::CriticalSection playing_lock_;
210 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100211
212 RtcEventLog* const event_log_;
213
214 // Indexed by payload type.
215 std::map<uint8_t, int> payload_type_frequencies_;
216
217 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
218 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
219 const uint32_t remote_ssrc_;
220
221 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
222 // queried on the worker thread.
223 rtc::CriticalSection rtp_sources_lock_;
224 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
225 absl::optional<uint32_t> last_received_rtp_timestamp_
226 RTC_GUARDED_BY(&rtp_sources_lock_);
227 absl::optional<int64_t> last_received_rtp_system_time_ms_
228 RTC_GUARDED_BY(&rtp_sources_lock_);
229 absl::optional<uint8_t> last_received_rtp_audio_level_
230 RTC_GUARDED_BY(&rtp_sources_lock_);
231
232 std::unique_ptr<AudioCodingModule> audio_coding_;
233 AudioSinkInterface* audio_sink_ = nullptr;
234 AudioLevel _outputAudioLevel;
235
236 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
237
238 // Timestamp of the audio pulled from NetEq.
239 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
240
241 rtc::CriticalSection video_sync_lock_;
242 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
243 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
244
245 rtc::CriticalSection ts_stats_lock_;
246
247 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
248 // The rtp timestamp of the first played out audio frame.
249 int64_t capture_start_rtp_time_stamp_;
250 // The capture ntp time (in local timebase) of the first played out audio
251 // frame.
252 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
253
254 // uses
255 ProcessThread* _moduleProcessThreadPtr;
256 AudioDeviceModule* _audioDeviceModulePtr;
257 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
258
259 // An associated send channel.
260 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100261 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100262 RTC_GUARDED_BY(assoc_send_channel_lock_);
263
264 PacketRouter* packet_router_ = nullptr;
265
266 rtc::ThreadChecker construction_thread_;
267
268 MediaTransportInterface* const media_transport_;
269
270 // E2EE Audio Frame Decryption
271 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
272 webrtc::CryptoOptions crypto_options_;
273};
Niels Möller530ead42018-10-04 14:28:39 +0200274
Niels Möller530ead42018-10-04 14:28:39 +0200275int32_t ChannelReceive::OnReceivedPayloadData(
276 const uint8_t* payloadData,
277 size_t payloadSize,
278 const WebRtcRTPHeader* rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200279 // We should not be receiving any RTP packets if media_transport is set.
280 RTC_CHECK(!media_transport_);
281
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100282 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200283 // Avoid inserting into NetEQ when we are not playing. Count the
284 // packet as discarded.
285 return 0;
286 }
287
288 // Push the incoming payload (parsed and ready for decoding) into the ACM
289 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
290 0) {
291 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
292 "push data to the ACM";
293 return -1;
294 }
295
296 int64_t round_trip_time = 0;
297 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
298
299 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
300 if (!nack_list.empty()) {
301 // Can't use nack_list.data() since it's not supported by all
302 // compilers.
303 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
304 }
305 return 0;
306}
307
Niels Möller7d76a312018-10-26 12:57:07 +0200308// MediaTransportAudioSinkInterface override.
309void ChannelReceive::OnData(uint64_t channel_id,
310 MediaTransportEncodedAudioFrame frame) {
311 RTC_CHECK(media_transport_);
312
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100313 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200314 // Avoid inserting into NetEQ when we are not playing. Count the
315 // packet as discarded.
316 return;
317 }
318
319 // Send encoded audio frame to Decoder / NetEq.
320 if (audio_coding_->IncomingPacket(
321 frame.encoded_data().data(), frame.encoded_data().size(),
322 CreateWebrtcRTPHeaderForMediaTransportFrame(frame, channel_id)) !=
323 0) {
324 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
325 "push data to the ACM";
326 }
327}
328
Niels Möller530ead42018-10-04 14:28:39 +0200329AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
330 int sample_rate_hz,
331 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100332 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200333 audio_frame->sample_rate_hz_ = sample_rate_hz;
334
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100335 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
336
Niels Möller530ead42018-10-04 14:28:39 +0200337 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
338 bool muted;
339 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
340 &muted) == -1) {
341 RTC_DLOG(LS_ERROR)
342 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
343 // In all likelihood, the audio in this frame is garbage. We return an
344 // error so that the audio mixer module doesn't add it to the mix. As
345 // a result, it won't be played out and the actions skipped here are
346 // irrelevant.
347 return AudioMixer::Source::AudioFrameInfo::kError;
348 }
349
350 if (muted) {
351 // TODO(henrik.lundin): We should be able to do better than this. But we
352 // will have to go through all the cases below where the audio samples may
353 // be used, and handle the muted case in some way.
354 AudioFrameOperations::Mute(audio_frame);
355 }
356
357 {
358 // Pass the audio buffers to an optional sink callback, before applying
359 // scaling/panning, as that applies to the mix operation.
360 // External recipients of the audio (e.g. via AudioTrack), will do their
361 // own mixing/dynamic processing.
362 rtc::CritScope cs(&_callbackCritSect);
363 if (audio_sink_) {
364 AudioSinkInterface::Data data(
365 audio_frame->data(), audio_frame->samples_per_channel_,
366 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
367 audio_frame->timestamp_);
368 audio_sink_->OnData(data);
369 }
370 }
371
372 float output_gain = 1.0f;
373 {
374 rtc::CritScope cs(&volume_settings_critsect_);
375 output_gain = _outputGain;
376 }
377
378 // Output volume scaling
379 if (output_gain < 0.99f || output_gain > 1.01f) {
380 // TODO(solenberg): Combine with mute state - this can cause clicks!
381 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
382 }
383
384 // Measure audio level (0-9)
385 // TODO(henrik.lundin) Use the |muted| information here too.
386 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
387 // https://crbug.com/webrtc/7517).
388 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
389
390 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
391 // The first frame with a valid rtp timestamp.
392 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
393 }
394
395 if (capture_start_rtp_time_stamp_ >= 0) {
396 // audio_frame.timestamp_ should be valid from now on.
397
398 // Compute elapsed time.
399 int64_t unwrap_timestamp =
400 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
401 audio_frame->elapsed_time_ms_ =
402 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
403 (GetRtpTimestampRateHz() / 1000);
404
405 {
406 rtc::CritScope lock(&ts_stats_lock_);
407 // Compute ntp time.
408 audio_frame->ntp_time_ms_ =
409 ntp_estimator_.Estimate(audio_frame->timestamp_);
410 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
411 if (audio_frame->ntp_time_ms_ > 0) {
412 // Compute |capture_start_ntp_time_ms_| so that
413 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
414 capture_start_ntp_time_ms_ =
415 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
416 }
417 }
418 }
419
420 {
421 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
422 audio_coding_->TargetDelayMs());
423 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
424 rtc::CritScope lock(&video_sync_lock_);
425 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
426 jitter_buffer_delay + playout_delay_ms_);
427 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
428 jitter_buffer_delay);
429 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
430 playout_delay_ms_);
431 }
432
433 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
434 : AudioMixer::Source::AudioFrameInfo::kNormal;
435}
436
437int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100438 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200439 // Return the bigger of playout and receive frequency in the ACM.
440 return std::max(audio_coding_->ReceiveFrequency(),
441 audio_coding_->PlayoutFrequency());
442}
443
444ChannelReceive::ChannelReceive(
445 ProcessThread* module_process_thread,
446 AudioDeviceModule* audio_device_module,
Niels Möller7d76a312018-10-26 12:57:07 +0200447 MediaTransportInterface* media_transport,
Niels Möllerae4237e2018-10-05 11:28:38 +0200448 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200449 RtcEventLog* rtc_event_log,
450 uint32_t remote_ssrc,
451 size_t jitter_buffer_max_packets,
452 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100453 int jitter_buffer_min_delay_ms,
Niels Möller530ead42018-10-04 14:28:39 +0200454 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700455 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700456 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700457 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200458 : event_log_(rtc_event_log),
459 rtp_receive_statistics_(
460 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
461 remote_ssrc_(remote_ssrc),
462 _outputAudioLevel(),
463 ntp_estimator_(Clock::GetRealTimeClock()),
464 playout_timestamp_rtp_(0),
465 playout_delay_ms_(0),
466 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
467 capture_start_rtp_time_stamp_(-1),
468 capture_start_ntp_time_ms_(-1),
469 _moduleProcessThreadPtr(module_process_thread),
470 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200471 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700472 associated_send_channel_(nullptr),
Niels Möller7d76a312018-10-26 12:57:07 +0200473 media_transport_(media_transport),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700474 frame_decryptor_(frame_decryptor),
475 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100476 // TODO(nisse): Use _moduleProcessThreadPtr instead?
477 module_process_thread_checker_.DetachFromThread();
478
Niels Möller530ead42018-10-04 14:28:39 +0200479 RTC_DCHECK(module_process_thread);
480 RTC_DCHECK(audio_device_module);
481 AudioCodingModule::Config acm_config;
482 acm_config.decoder_factory = decoder_factory;
483 acm_config.neteq_config.codec_pair_id = codec_pair_id;
484 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
485 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100486 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200487 acm_config.neteq_config.enable_muted_state = true;
488 audio_coding_.reset(AudioCodingModule::Create(acm_config));
489
490 _outputAudioLevel.Clear();
491
492 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
493 RtpRtcp::Configuration configuration;
494 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100495 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200496 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200497 configuration.receive_statistics = rtp_receive_statistics_.get();
498
499 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200500
501 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
502 _rtpRtcpModule->SetSendingMediaStatus(false);
503 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200504
Niels Möller530ead42018-10-04 14:28:39 +0200505 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
506
Niels Möller530ead42018-10-04 14:28:39 +0200507 // Ensure that RTCP is enabled by default for the created channel.
508 // Note that, the module will keep generating RTCP until it is explicitly
509 // disabled by the user.
510 // After StopListen (when no sockets exists), RTCP packets will no longer
511 // be transmitted since the Transport object will then be invalid.
512 // RTCP is enabled by default.
513 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200514
515 if (media_transport_) {
516 media_transport_->SetReceiveAudioSink(this);
517 }
Niels Möller530ead42018-10-04 14:28:39 +0200518}
519
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100520ChannelReceive::~ChannelReceive() {
Niels Möller530ead42018-10-04 14:28:39 +0200521 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200522
523 if (media_transport_) {
524 media_transport_->SetReceiveAudioSink(nullptr);
525 }
526
Niels Möller530ead42018-10-04 14:28:39 +0200527 StopPlayout();
528
Niels Möller530ead42018-10-04 14:28:39 +0200529 int error = audio_coding_->RegisterTransportCallback(NULL);
530 RTC_DCHECK_EQ(0, error);
531
Niels Möller530ead42018-10-04 14:28:39 +0200532 if (_moduleProcessThreadPtr)
533 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200534}
535
536void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Niels Möller349ade32018-11-16 09:50:42 +0100537 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200538 rtc::CritScope cs(&_callbackCritSect);
539 audio_sink_ = sink;
540}
541
Niels Möller80c67622018-11-12 13:22:47 +0100542void ChannelReceive::StartPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100543 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100544 rtc::CritScope lock(&playing_lock_);
545 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200546}
547
Niels Möller80c67622018-11-12 13:22:47 +0100548void ChannelReceive::StopPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100549 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100550 rtc::CritScope lock(&playing_lock_);
551 playing_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200552 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200553}
554
Niels Möller349ade32018-11-16 09:50:42 +0100555bool ChannelReceive::GetRecCodec(CodecInst* codec) const {
556 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100557 return (audio_coding_->ReceiveCodec(codec) == 0);
Niels Möller530ead42018-10-04 14:28:39 +0200558}
559
560std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Niels Möller349ade32018-11-16 09:50:42 +0100561 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200562 int64_t now_ms = rtc::TimeMillis();
563 std::vector<RtpSource> sources;
564 {
565 rtc::CritScope cs(&rtp_sources_lock_);
566 sources = contributing_sources_.GetSources(now_ms);
567 if (last_received_rtp_system_time_ms_ >=
568 now_ms - ContributingSources::kHistoryMs) {
569 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
570 RtpSourceType::SSRC);
571 sources.back().set_audio_level(last_received_rtp_audio_level_);
572 }
573 }
574 return sources;
575}
576
577void ChannelReceive::SetReceiveCodecs(
578 const std::map<int, SdpAudioFormat>& codecs) {
Niels Möller349ade32018-11-16 09:50:42 +0100579 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200580 for (const auto& kv : codecs) {
581 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
582 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
583 }
584 audio_coding_->SetReceiveCodecs(codecs);
585}
586
Niels Möller349ade32018-11-16 09:50:42 +0100587// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200588void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
589 int64_t now_ms = rtc::TimeMillis();
590 uint8_t audio_level;
591 bool voice_activity;
592 bool has_audio_level =
593 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
594
595 {
596 rtc::CritScope cs(&rtp_sources_lock_);
597 last_received_rtp_timestamp_ = packet.Timestamp();
598 last_received_rtp_system_time_ms_ = now_ms;
599 if (has_audio_level)
600 last_received_rtp_audio_level_ = audio_level;
601 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100602 contributing_sources_.Update(
603 now_ms, csrcs,
604 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200605 }
606
607 // Store playout timestamp for the received RTP packet
608 UpdatePlayoutTimestamp(false);
609
610 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
611 if (it == payload_type_frequencies_.end())
612 return;
613 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
614 RtpPacketReceived packet_copy(packet);
615 packet_copy.set_payload_type_frequency(it->second);
616
617 rtp_receive_statistics_->OnRtpPacket(packet_copy);
618
619 RTPHeader header;
620 packet_copy.GetHeader(&header);
621
622 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
623}
624
625bool ChannelReceive::ReceivePacket(const uint8_t* packet,
626 size_t packet_length,
627 const RTPHeader& header) {
628 const uint8_t* payload = packet + header.headerLength;
629 assert(packet_length >= header.headerLength);
630 size_t payload_length = packet_length - header.headerLength;
631 WebRtcRTPHeader webrtc_rtp_header = {};
632 webrtc_rtp_header.header = header;
633
Benjamin Wright84583f62018-10-04 14:22:34 -0700634 size_t payload_data_length = payload_length - header.paddingLength;
635
636 // E2EE Custom Audio Frame Decryption (This is optional).
637 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
638 rtc::Buffer decrypted_audio_payload;
639 if (frame_decryptor_ != nullptr) {
640 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
641 cricket::MEDIA_TYPE_AUDIO, payload_length);
642 decrypted_audio_payload.SetSize(max_plaintext_size);
643
644 size_t bytes_written = 0;
645 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
646 header.arrOfCSRCs + header.numCSRCs);
647 int decrypt_status = frame_decryptor_->Decrypt(
648 cricket::MEDIA_TYPE_AUDIO, csrcs,
649 /*additional_data=*/nullptr,
650 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
651 decrypted_audio_payload, &bytes_written);
652
653 // In this case just interpret the failure as a silent frame.
654 if (decrypt_status != 0) {
655 bytes_written = 0;
656 }
657
658 // Resize the decrypted audio payload to the number of bytes actually
659 // written.
660 decrypted_audio_payload.SetSize(bytes_written);
661 // Update the final payload.
662 payload = decrypted_audio_payload.data();
663 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700664 } else if (crypto_options_.sframe.require_frame_encryption) {
665 RTC_DLOG(LS_ERROR)
666 << "FrameDecryptor required but not set, dropping packet";
667 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700668 }
669
Niels Möller530ead42018-10-04 14:28:39 +0200670 if (payload_data_length == 0) {
671 webrtc_rtp_header.frameType = kEmptyFrame;
672 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
673 }
674 return OnReceivedPayloadData(payload, payload_data_length,
675 &webrtc_rtp_header);
676}
677
Niels Möller349ade32018-11-16 09:50:42 +0100678// May be called on either worker thread or network thread.
Niels Möller80c67622018-11-12 13:22:47 +0100679// TODO(nisse): Drop always-true return value.
680bool ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200681 // Store playout timestamp for the received RTCP packet
682 UpdatePlayoutTimestamp(true);
683
684 // Deliver RTCP packet to RTP/RTCP module for parsing
685 _rtpRtcpModule->IncomingRtcpPacket(data, length);
686
687 int64_t rtt = GetRTT();
688 if (rtt == 0) {
689 // Waiting for valid RTT.
Niels Möller80c67622018-11-12 13:22:47 +0100690 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200691 }
692
693 int64_t nack_window_ms = rtt;
694 if (nack_window_ms < kMinRetransmissionWindowMs) {
695 nack_window_ms = kMinRetransmissionWindowMs;
696 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
697 nack_window_ms = kMaxRetransmissionWindowMs;
698 }
699
700 uint32_t ntp_secs = 0;
701 uint32_t ntp_frac = 0;
702 uint32_t rtp_timestamp = 0;
703 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
704 &rtp_timestamp)) {
705 // Waiting for RTCP.
Niels Möller80c67622018-11-12 13:22:47 +0100706 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200707 }
708
709 {
710 rtc::CritScope lock(&ts_stats_lock_);
711 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
712 }
Niels Möller80c67622018-11-12 13:22:47 +0100713 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200714}
715
716int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Niels Möller349ade32018-11-16 09:50:42 +0100717 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200718 return _outputAudioLevel.LevelFullRange();
719}
720
721double ChannelReceive::GetTotalOutputEnergy() const {
Niels Möller349ade32018-11-16 09:50:42 +0100722 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200723 return _outputAudioLevel.TotalEnergy();
724}
725
726double ChannelReceive::GetTotalOutputDuration() const {
Niels Möller349ade32018-11-16 09:50:42 +0100727 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200728 return _outputAudioLevel.TotalDuration();
729}
730
731void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Niels Möller349ade32018-11-16 09:50:42 +0100732 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200733 rtc::CritScope cs(&volume_settings_critsect_);
734 _outputGain = scaling;
735}
736
Niels Möller349ade32018-11-16 09:50:42 +0100737void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
738 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200739 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200740}
741
Niels Möller530ead42018-10-04 14:28:39 +0200742void ChannelReceive::RegisterReceiverCongestionControlObjects(
743 PacketRouter* packet_router) {
Niels Möller349ade32018-11-16 09:50:42 +0100744 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200745 RTC_DCHECK(packet_router);
746 RTC_DCHECK(!packet_router_);
747 constexpr bool remb_candidate = false;
748 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
749 packet_router_ = packet_router;
750}
751
752void ChannelReceive::ResetReceiverCongestionControlObjects() {
Niels Möller349ade32018-11-16 09:50:42 +0100753 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200754 RTC_DCHECK(packet_router_);
755 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
756 packet_router_ = nullptr;
757}
758
Niels Möller349ade32018-11-16 09:50:42 +0100759CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
760 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200761 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100762 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200763
764 // The jitter statistics is updated for each received RTP packet and is
765 // based on received packets.
766 RtcpStatistics statistics;
767 StreamStatistician* statistician =
768 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
769 if (statistician) {
770 statistician->GetStatistics(&statistics,
771 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
772 }
773
774 stats.fractionLost = statistics.fraction_lost;
775 stats.cumulativeLost = statistics.packets_lost;
776 stats.extendedMax = statistics.extended_highest_sequence_number;
777 stats.jitterSamples = statistics.jitter;
778
779 // --- RTT
780 stats.rttMs = GetRTT();
781
782 // --- Data counters
783
784 size_t bytesReceived(0);
785 uint32_t packetsReceived(0);
786
787 if (statistician) {
788 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
789 }
790
791 stats.bytesReceived = bytesReceived;
792 stats.packetsReceived = packetsReceived;
793
794 // --- Timestamps
795 {
796 rtc::CritScope lock(&ts_stats_lock_);
797 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
798 }
Niels Möller80c67622018-11-12 13:22:47 +0100799 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200800}
801
Niels Möller349ade32018-11-16 09:50:42 +0100802void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
803 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200804 // None of these functions can fail.
Niels Möller349ade32018-11-16 09:50:42 +0100805 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller530ead42018-10-04 14:28:39 +0200806 if (enable)
Niels Möller349ade32018-11-16 09:50:42 +0100807 audio_coding_->EnableNack(max_packets);
Niels Möller530ead42018-10-04 14:28:39 +0200808 else
809 audio_coding_->DisableNack();
810}
811
812// Called when we are missing one or more packets.
813int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
814 int length) {
815 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
816}
817
Niels Möllerdced9f62018-11-19 10:27:07 +0100818void ChannelReceive::SetAssociatedSendChannel(
819 const ChannelSendInterface* channel) {
Niels Möller349ade32018-11-16 09:50:42 +0100820 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200821 rtc::CritScope lock(&assoc_send_channel_lock_);
822 associated_send_channel_ = channel;
823}
824
Niels Möller80c67622018-11-12 13:22:47 +0100825NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100826 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100827 NetworkStatistics stats;
828 int error = audio_coding_->GetNetworkStatistics(&stats);
829 RTC_DCHECK_EQ(0, error);
830 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200831}
832
Niels Möller80c67622018-11-12 13:22:47 +0100833AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100834 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100835 AudioDecodingCallStats stats;
836 audio_coding_->GetDecodingCallStatistics(&stats);
837 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200838}
839
840uint32_t ChannelReceive::GetDelayEstimate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100841 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() ||
842 module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200843 rtc::CritScope lock(&video_sync_lock_);
844 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
845}
846
Niels Möller349ade32018-11-16 09:50:42 +0100847void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
848 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
849 // Limit to range accepted by both VoE and ACM, so we're at least getting as
850 // close as possible, instead of failing.
851 delay_ms = rtc::SafeClamp(delay_ms, 0, 10000);
852 if ((delay_ms < kVoiceEngineMinMinPlayoutDelayMs) ||
853 (delay_ms > kVoiceEngineMaxMinPlayoutDelayMs)) {
Niels Möller530ead42018-10-04 14:28:39 +0200854 RTC_DLOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
Niels Möller80c67622018-11-12 13:22:47 +0100855 return;
Niels Möller530ead42018-10-04 14:28:39 +0200856 }
Niels Möller349ade32018-11-16 09:50:42 +0100857 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200858 RTC_DLOG(LS_ERROR)
859 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200860 }
Niels Möller530ead42018-10-04 14:28:39 +0200861}
862
Niels Möller349ade32018-11-16 09:50:42 +0100863uint32_t ChannelReceive::GetPlayoutTimestamp() const {
864 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200865 {
866 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100867 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200868 }
Niels Möller530ead42018-10-04 14:28:39 +0200869}
870
871absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Niels Möller349ade32018-11-16 09:50:42 +0100872 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200873 Syncable::Info info;
874 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
875 &info.capture_time_ntp_frac, nullptr, nullptr,
876 &info.capture_time_source_clock) != 0) {
877 return absl::nullopt;
878 }
879 {
880 rtc::CritScope cs(&rtp_sources_lock_);
881 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
882 return absl::nullopt;
883 }
884 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
885 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
886 }
887 return info;
888}
889
890void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
891 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
892
893 if (!jitter_buffer_playout_timestamp_) {
894 // This can happen if this channel has not received any RTP packets. In
895 // this case, NetEq is not capable of computing a playout timestamp.
896 return;
897 }
898
899 uint16_t delay_ms = 0;
900 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
901 RTC_DLOG(LS_WARNING)
902 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
903 << " playout delay from the ADM";
904 return;
905 }
906
907 RTC_DCHECK(jitter_buffer_playout_timestamp_);
908 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
909
910 // Remove the playout delay.
911 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
912
913 {
914 rtc::CritScope lock(&video_sync_lock_);
915 if (!rtcp) {
916 playout_timestamp_rtp_ = playout_timestamp;
917 }
918 playout_delay_ms_ = delay_ms;
919 }
920}
921
922int ChannelReceive::GetRtpTimestampRateHz() const {
923 const auto format = audio_coding_->ReceiveFormat();
924 // Default to the playout frequency if we've not gotten any packets yet.
925 // TODO(ossu): Zero clockrate can only happen if we've added an external
926 // decoder for a format we don't support internally. Remove once that way of
927 // adding decoders is gone!
928 return (format && format->clockrate_hz != 0)
929 ? format->clockrate_hz
930 : audio_coding_->PlayoutFrequency();
931}
932
933int64_t ChannelReceive::GetRTT() const {
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800934 if (media_transport_) {
935 auto target_rate = media_transport_->GetLatestTargetTransferRate();
936 if (target_rate.has_value()) {
937 return target_rate->network_estimate.round_trip_time.ms();
938 }
939
940 return 0;
941 }
Niels Möller530ead42018-10-04 14:28:39 +0200942 RtcpMode method = _rtpRtcpModule->RTCP();
943 if (method == RtcpMode::kOff) {
944 return 0;
945 }
946 std::vector<RTCPReportBlock> report_blocks;
947 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
948
949 // TODO(nisse): Could we check the return value from the ->RTT() call below,
950 // instead of checking if we have any report blocks?
951 if (report_blocks.empty()) {
952 rtc::CritScope lock(&assoc_send_channel_lock_);
953 // Tries to get RTT from an associated channel.
954 if (!associated_send_channel_) {
955 return 0;
956 }
957 return associated_send_channel_->GetRTT();
958 }
959
960 int64_t rtt = 0;
961 int64_t avg_rtt = 0;
962 int64_t max_rtt = 0;
963 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100964 // TODO(nisse): This method computes RTT based on sender reports, even though
965 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200966 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
967 0) {
968 return 0;
969 }
970 return rtt;
971}
972
Niels Möller349ade32018-11-16 09:50:42 +0100973} // namespace
974
975std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
976 ProcessThread* module_process_thread,
977 AudioDeviceModule* audio_device_module,
978 MediaTransportInterface* media_transport,
979 Transport* rtcp_send_transport,
980 RtcEventLog* rtc_event_log,
981 uint32_t remote_ssrc,
982 size_t jitter_buffer_max_packets,
983 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100984 int jitter_buffer_min_delay_ms,
Niels Möller349ade32018-11-16 09:50:42 +0100985 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
986 absl::optional<AudioCodecPairId> codec_pair_id,
987 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
988 const webrtc::CryptoOptions& crypto_options) {
989 return absl::make_unique<ChannelReceive>(
990 module_process_thread, audio_device_module, media_transport,
991 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100992 jitter_buffer_max_packets, jitter_buffer_fast_playout,
993 jitter_buffer_min_delay_ms, decoder_factory, codec_pair_id,
994 frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100995}
996
Niels Möller530ead42018-10-04 14:28:39 +0200997} // namespace voe
998} // namespace webrtc