blob: aa6043811a3c306490acb4cac1c9700a36f4f2d2 [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"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020034#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010035#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möller530ead42018-10-04 14:28:39 +020036#include "modules/utility/include/process_thread.h"
37#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/critical_section.h"
Niels Möller530ead42018-10-04 14:28:39 +020039#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"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "rtc_base/time_utils.h"
Bjorn A Mellemda4f0932019-07-30 08:34:03 -070046#include "system_wrappers/include/field_trial.h"
Niels Möller530ead42018-10-04 14:28:39 +020047#include "system_wrappers/include/metrics.h"
48
49namespace webrtc {
50namespace voe {
51
52namespace {
53
54constexpr double kAudioSampleDurationSeconds = 0.01;
Niels Möller530ead42018-10-04 14:28:39 +020055
56// Video Sync.
57constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
58constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
59
Bjorn A Mellemda4f0932019-07-30 08:34:03 -070060// Field trial which controls whether to report standard-compliant bytes
61// sent/received per stream. If enabled, padding and headers are not included
62// in bytes sent or received.
63constexpr char kUseStandardBytesStats[] = "WebRTC-UseStandardBytesStats";
64
Niels Möllerafb5dbb2019-02-15 15:21:47 +010065RTPHeader CreateRTPHeaderForMediaTransportFrame(
Sergey Silkine049eba2019-02-18 09:52:26 +000066 const MediaTransportEncodedAudioFrame& frame,
67 uint64_t channel_id) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +010068 webrtc::RTPHeader rtp_header;
69 rtp_header.payloadType = frame.payload_type();
70 rtp_header.payload_type_frequency = frame.sampling_rate_hz();
71 rtp_header.timestamp = frame.starting_sample_index();
72 rtp_header.sequenceNumber = frame.sequence_number();
Niels Möller7d76a312018-10-26 12:57:07 +020073
Sergey Silkine049eba2019-02-18 09:52:26 +000074 rtp_header.ssrc = static_cast<uint32_t>(channel_id);
Niels Möller7d76a312018-10-26 12:57:07 +020075
76 // The rest are initialized by the RTPHeader constructor.
Niels Möllerafb5dbb2019-02-15 15:21:47 +010077 return rtp_header;
Niels Möller7d76a312018-10-26 12:57:07 +020078}
79
Niels Möller349ade32018-11-16 09:50:42 +010080class ChannelReceive : public ChannelReceiveInterface,
81 public MediaTransportAudioSinkInterface {
82 public:
83 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +010084 ChannelReceive(Clock* clock,
85 ProcessThread* module_process_thread,
Niels Möller349ade32018-11-16 09:50:42 +010086 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -070087 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +010088 Transport* rtcp_send_transport,
89 RtcEventLog* rtc_event_log,
90 uint32_t remote_ssrc,
91 size_t jitter_buffer_max_packets,
92 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010093 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +010094 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +010095 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
96 absl::optional<AudioCodecPairId> codec_pair_id,
97 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
98 const webrtc::CryptoOptions& crypto_options);
99 ~ChannelReceive() override;
100
101 void SetSink(AudioSinkInterface* sink) override;
102
103 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
104
105 // API methods
106
107 void StartPlayout() override;
108 void StopPlayout() override;
109
110 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000111 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
112 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100113
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100114 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100115
116 // RtpPacketSinkInterface.
117 void OnRtpPacket(const RtpPacketReceived& packet) override;
118
119 // Muting, Volume and Level.
120 void SetChannelOutputVolumeScaling(float scaling) override;
121 int GetSpeechOutputLevelFullRange() const override;
122 // See description of "totalAudioEnergy" in the WebRTC stats spec:
123 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
124 double GetTotalOutputEnergy() const override;
125 double GetTotalOutputDuration() const override;
126
127 // Stats.
128 NetworkStatistics GetNetworkStatistics() const override;
129 AudioDecodingCallStats GetDecodingCallStatistics() const override;
130
131 // Audio+Video Sync.
132 uint32_t GetDelayEstimate() const override;
133 void SetMinimumPlayoutDelay(int delayMs) override;
134 uint32_t GetPlayoutTimestamp() const override;
135
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100136 // Audio quality.
137 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
138 int GetBaseMinimumPlayoutDelayMs() const override;
139
Niels Möller349ade32018-11-16 09:50:42 +0100140 // Produces the transport-related timestamps; current_delay_ms is left unset.
141 absl::optional<Syncable::Info> GetSyncInfo() const override;
142
143 // RTP+RTCP
144 void SetLocalSSRC(unsigned int ssrc) override;
145
146 void RegisterReceiverCongestionControlObjects(
147 PacketRouter* packet_router) override;
148 void ResetReceiverCongestionControlObjects() override;
149
150 CallReceiveStatistics GetRTCPStatistics() const override;
151 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
152
153 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
154 int sample_rate_hz,
155 AudioFrame* audio_frame) override;
156
157 int PreferredSampleRate() const override;
158
159 // Associate to a send channel.
160 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100161 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100162
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700163 // TODO(sukhanov): Return const pointer. It requires making media transport
164 // getters like GetLatestTargetTransferRate to be also const.
165 MediaTransportInterface* media_transport() const {
166 return media_transport_config_.media_transport;
167 }
168
Niels Möller349ade32018-11-16 09:50:42 +0100169 private:
Niels Möller349ade32018-11-16 09:50:42 +0100170 bool ReceivePacket(const uint8_t* packet,
171 size_t packet_length,
172 const RTPHeader& header);
173 int ResendPackets(const uint16_t* sequence_numbers, int length);
174 void UpdatePlayoutTimestamp(bool rtcp);
175
176 int GetRtpTimestampRateHz() const;
177 int64_t GetRTT() const;
178
179 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000180 void OnData(uint64_t channel_id,
181 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100182
183 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
184 size_t payloadSize,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100185 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100186
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100187 bool Playing() const {
188 rtc::CritScope lock(&playing_lock_);
189 return playing_;
190 }
191
Niels Möller349ade32018-11-16 09:50:42 +0100192 // Thread checkers document and lock usage of some methods to specific threads
193 // we know about. The goal is to eventually split up voe::ChannelReceive into
194 // parts with single-threaded semantics, and thereby reduce the need for
195 // locks.
196 rtc::ThreadChecker worker_thread_checker_;
197 rtc::ThreadChecker module_process_thread_checker_;
198 // Methods accessed from audio and video threads are checked for sequential-
199 // only access. We don't necessarily own and control these threads, so thread
200 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
201 // audio thread to another, but access is still sequential.
202 rtc::RaceChecker audio_thread_race_checker_;
203 rtc::RaceChecker video_capture_thread_race_checker_;
204 rtc::CriticalSection _callbackCritSect;
205 rtc::CriticalSection volume_settings_critsect_;
206
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100207 rtc::CriticalSection playing_lock_;
208 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100209
210 RtcEventLog* const event_log_;
211
212 // Indexed by payload type.
213 std::map<uint8_t, int> payload_type_frequencies_;
214
215 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
216 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
217 const uint32_t remote_ssrc_;
218
Chen Xing054e3bb2019-08-02 10:29:26 +0000219 // Info for GetSyncInfo is updated on network or worker thread, and queried on
220 // the worker thread.
221 rtc::CriticalSection sync_info_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100222 absl::optional<uint32_t> last_received_rtp_timestamp_
Chen Xing054e3bb2019-08-02 10:29:26 +0000223 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100224 absl::optional<int64_t> last_received_rtp_system_time_ms_
Chen Xing054e3bb2019-08-02 10:29:26 +0000225 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100226
227 std::unique_ptr<AudioCodingModule> audio_coding_;
228 AudioSinkInterface* audio_sink_ = nullptr;
229 AudioLevel _outputAudioLevel;
230
231 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
232
233 // Timestamp of the audio pulled from NetEq.
234 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
235
236 rtc::CriticalSection video_sync_lock_;
237 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
238 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
239
240 rtc::CriticalSection ts_stats_lock_;
241
242 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
243 // The rtp timestamp of the first played out audio frame.
244 int64_t capture_start_rtp_time_stamp_;
245 // The capture ntp time (in local timebase) of the first played out audio
246 // frame.
247 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
248
249 // uses
250 ProcessThread* _moduleProcessThreadPtr;
251 AudioDeviceModule* _audioDeviceModulePtr;
252 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
253
254 // An associated send channel.
255 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100256 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100257 RTC_GUARDED_BY(assoc_send_channel_lock_);
258
259 PacketRouter* packet_router_ = nullptr;
260
261 rtc::ThreadChecker construction_thread_;
262
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700263 MediaTransportConfig media_transport_config_;
Niels Möller349ade32018-11-16 09:50:42 +0100264
265 // E2EE Audio Frame Decryption
266 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
267 webrtc::CryptoOptions crypto_options_;
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700268
269 const bool use_standard_bytes_stats_;
Niels Möller349ade32018-11-16 09:50:42 +0100270};
Niels Möller530ead42018-10-04 14:28:39 +0200271
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100272int32_t ChannelReceive::OnReceivedPayloadData(const uint8_t* payloadData,
273 size_t payloadSize,
274 const RTPHeader& rtp_header) {
Niels Möller7d76a312018-10-26 12:57:07 +0200275 // We should not be receiving any RTP packets if media_transport is set.
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700276 RTC_CHECK(!media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200277
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100278 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200279 // Avoid inserting into NetEQ when we are not playing. Count the
280 // packet as discarded.
281 return 0;
282 }
283
284 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100285 if (audio_coding_->IncomingPacket(payloadData, payloadSize, rtp_header) !=
Niels Möller530ead42018-10-04 14:28:39 +0200286 0) {
287 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
288 "push data to the ACM";
289 return -1;
290 }
291
292 int64_t round_trip_time = 0;
293 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
294
295 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
296 if (!nack_list.empty()) {
297 // Can't use nack_list.data() since it's not supported by all
298 // compilers.
299 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
300 }
301 return 0;
302}
303
Niels Möller7d76a312018-10-26 12:57:07 +0200304// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000305void ChannelReceive::OnData(uint64_t channel_id,
306 MediaTransportEncodedAudioFrame frame) {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700307 RTC_CHECK(media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200308
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100309 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200310 // Avoid inserting into NetEQ when we are not playing. Count the
311 // packet as discarded.
312 return;
313 }
314
315 // Send encoded audio frame to Decoder / NetEq.
316 if (audio_coding_->IncomingPacket(
317 frame.encoded_data().data(), frame.encoded_data().size(),
Sergey Silkine049eba2019-02-18 09:52:26 +0000318 CreateRTPHeaderForMediaTransportFrame(frame, channel_id)) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200319 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
320 "push data to the ACM";
321 }
322}
323
Niels Möller530ead42018-10-04 14:28:39 +0200324AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
325 int sample_rate_hz,
326 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100327 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200328 audio_frame->sample_rate_hz_ = sample_rate_hz;
329
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100330 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
331
Niels Möller530ead42018-10-04 14:28:39 +0200332 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
333 bool muted;
334 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
335 &muted) == -1) {
336 RTC_DLOG(LS_ERROR)
337 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
338 // In all likelihood, the audio in this frame is garbage. We return an
339 // error so that the audio mixer module doesn't add it to the mix. As
340 // a result, it won't be played out and the actions skipped here are
341 // irrelevant.
342 return AudioMixer::Source::AudioFrameInfo::kError;
343 }
344
345 if (muted) {
346 // TODO(henrik.lundin): We should be able to do better than this. But we
347 // will have to go through all the cases below where the audio samples may
348 // be used, and handle the muted case in some way.
349 AudioFrameOperations::Mute(audio_frame);
350 }
351
352 {
353 // Pass the audio buffers to an optional sink callback, before applying
354 // scaling/panning, as that applies to the mix operation.
355 // External recipients of the audio (e.g. via AudioTrack), will do their
356 // own mixing/dynamic processing.
357 rtc::CritScope cs(&_callbackCritSect);
358 if (audio_sink_) {
359 AudioSinkInterface::Data data(
360 audio_frame->data(), audio_frame->samples_per_channel_,
361 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
362 audio_frame->timestamp_);
363 audio_sink_->OnData(data);
364 }
365 }
366
367 float output_gain = 1.0f;
368 {
369 rtc::CritScope cs(&volume_settings_critsect_);
370 output_gain = _outputGain;
371 }
372
373 // Output volume scaling
374 if (output_gain < 0.99f || output_gain > 1.01f) {
375 // TODO(solenberg): Combine with mute state - this can cause clicks!
376 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
377 }
378
379 // Measure audio level (0-9)
380 // TODO(henrik.lundin) Use the |muted| information here too.
381 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
382 // https://crbug.com/webrtc/7517).
383 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
384
385 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
386 // The first frame with a valid rtp timestamp.
387 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
388 }
389
390 if (capture_start_rtp_time_stamp_ >= 0) {
391 // audio_frame.timestamp_ should be valid from now on.
392
393 // Compute elapsed time.
394 int64_t unwrap_timestamp =
395 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
396 audio_frame->elapsed_time_ms_ =
397 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
398 (GetRtpTimestampRateHz() / 1000);
399
400 {
401 rtc::CritScope lock(&ts_stats_lock_);
402 // Compute ntp time.
403 audio_frame->ntp_time_ms_ =
404 ntp_estimator_.Estimate(audio_frame->timestamp_);
405 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
406 if (audio_frame->ntp_time_ms_ > 0) {
407 // Compute |capture_start_ntp_time_ms_| so that
408 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
409 capture_start_ntp_time_ms_ =
410 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
411 }
412 }
413 }
414
415 {
416 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
417 audio_coding_->TargetDelayMs());
418 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
419 rtc::CritScope lock(&video_sync_lock_);
420 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
421 jitter_buffer_delay + playout_delay_ms_);
422 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
423 jitter_buffer_delay);
424 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
425 playout_delay_ms_);
426 }
427
428 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
429 : AudioMixer::Source::AudioFrameInfo::kNormal;
430}
431
432int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100433 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200434 // Return the bigger of playout and receive frequency in the ACM.
435 return std::max(audio_coding_->ReceiveFrequency(),
436 audio_coding_->PlayoutFrequency());
437}
438
439ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100440 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200441 ProcessThread* module_process_thread,
442 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700443 const MediaTransportConfig& media_transport_config,
Niels Möllerae4237e2018-10-05 11:28:38 +0200444 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200445 RtcEventLog* rtc_event_log,
446 uint32_t remote_ssrc,
447 size_t jitter_buffer_max_packets,
448 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100449 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100450 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200451 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700452 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700453 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700454 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200455 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100456 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200457 remote_ssrc_(remote_ssrc),
458 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100459 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200460 playout_timestamp_rtp_(0),
461 playout_delay_ms_(0),
462 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
463 capture_start_rtp_time_stamp_(-1),
464 capture_start_ntp_time_ms_(-1),
465 _moduleProcessThreadPtr(module_process_thread),
466 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200467 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700468 associated_send_channel_(nullptr),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700469 media_transport_config_(media_transport_config),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700470 frame_decryptor_(frame_decryptor),
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700471 crypto_options_(crypto_options),
472 use_standard_bytes_stats_(
473 webrtc::field_trial::IsEnabled(kUseStandardBytesStats)) {
Niels Möller349ade32018-11-16 09:50:42 +0100474 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200475 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100476
Niels Möller530ead42018-10-04 14:28:39 +0200477 RTC_DCHECK(module_process_thread);
478 RTC_DCHECK(audio_device_module);
479 AudioCodingModule::Config acm_config;
480 acm_config.decoder_factory = decoder_factory;
481 acm_config.neteq_config.codec_pair_id = codec_pair_id;
482 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
483 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100484 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200485 acm_config.neteq_config.enable_muted_state = true;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100486 acm_config.neteq_config.enable_rtx_handling =
487 jitter_buffer_enable_rtx_handling;
Niels Möller530ead42018-10-04 14:28:39 +0200488 audio_coding_.reset(AudioCodingModule::Create(acm_config));
489
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200490 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200491
492 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
493 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100494 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200495 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100496 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200497 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200498 configuration.receive_statistics = rtp_receive_statistics_.get();
499
500 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200501
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100502 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200503 _rtpRtcpModule->SetSendingMediaStatus(false);
504 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200505
Niels Möller530ead42018-10-04 14:28:39 +0200506 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
507
Niels Möller530ead42018-10-04 14:28:39 +0200508 // Ensure that RTCP is enabled by default for the created channel.
509 // Note that, the module will keep generating RTCP until it is explicitly
510 // disabled by the user.
511 // After StopListen (when no sockets exists), RTCP packets will no longer
512 // be transmitted since the Transport object will then be invalid.
513 // RTCP is enabled by default.
514 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200515
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700516 if (media_transport()) {
517 media_transport()->SetReceiveAudioSink(this);
Niels Möller7d76a312018-10-26 12:57:07 +0200518 }
Niels Möller530ead42018-10-04 14:28:39 +0200519}
520
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100521ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200522 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200523
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700524 if (media_transport()) {
525 media_transport()->SetReceiveAudioSink(nullptr);
Niels Möller7d76a312018-10-26 12:57:07 +0200526 }
527
Niels Möller530ead42018-10-04 14:28:39 +0200528 StopPlayout();
529
Niels Möller530ead42018-10-04 14:28:39 +0200530 int error = audio_coding_->RegisterTransportCallback(NULL);
531 RTC_DCHECK_EQ(0, error);
532
Niels Möller530ead42018-10-04 14:28:39 +0200533 if (_moduleProcessThreadPtr)
534 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200535}
536
537void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200538 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200539 rtc::CritScope cs(&_callbackCritSect);
540 audio_sink_ = sink;
541}
542
Niels Möller80c67622018-11-12 13:22:47 +0100543void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200544 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100545 rtc::CritScope lock(&playing_lock_);
546 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200547}
548
Niels Möller80c67622018-11-12 13:22:47 +0100549void ChannelReceive::StopPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200550 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100551 rtc::CritScope lock(&playing_lock_);
552 playing_ = false;
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200553 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200554}
555
Jonas Olssona4d87372019-07-05 19:08:33 +0200556absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
557 const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200558 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100559 return audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200560}
561
Niels Möller530ead42018-10-04 14:28:39 +0200562void ChannelReceive::SetReceiveCodecs(
563 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200564 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200565 for (const auto& kv : codecs) {
566 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
567 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
568 }
569 audio_coding_->SetReceiveCodecs(codecs);
570}
571
Niels Möller349ade32018-11-16 09:50:42 +0100572// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200573void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
574 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200575
576 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000577 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200578 last_received_rtp_timestamp_ = packet.Timestamp();
579 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200580 }
581
582 // Store playout timestamp for the received RTP packet
583 UpdatePlayoutTimestamp(false);
584
585 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
586 if (it == payload_type_frequencies_.end())
587 return;
588 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
589 RtpPacketReceived packet_copy(packet);
590 packet_copy.set_payload_type_frequency(it->second);
591
592 rtp_receive_statistics_->OnRtpPacket(packet_copy);
593
594 RTPHeader header;
595 packet_copy.GetHeader(&header);
596
597 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
598}
599
600bool ChannelReceive::ReceivePacket(const uint8_t* packet,
601 size_t packet_length,
602 const RTPHeader& header) {
603 const uint8_t* payload = packet + header.headerLength;
604 assert(packet_length >= header.headerLength);
605 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200606
Benjamin Wright84583f62018-10-04 14:22:34 -0700607 size_t payload_data_length = payload_length - header.paddingLength;
608
609 // E2EE Custom Audio Frame Decryption (This is optional).
610 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
611 rtc::Buffer decrypted_audio_payload;
612 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000613 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700614 cricket::MEDIA_TYPE_AUDIO, payload_length);
615 decrypted_audio_payload.SetSize(max_plaintext_size);
616
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000617 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
618 header.arrOfCSRCs + header.numCSRCs);
619 const FrameDecryptorInterface::Result decrypt_result =
620 frame_decryptor_->Decrypt(
621 cricket::MEDIA_TYPE_AUDIO, csrcs,
622 /*additional_data=*/nullptr,
623 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
624 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700625
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000626 if (decrypt_result.IsOk()) {
627 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
628 } else {
629 // Interpret failures as a silent frame.
630 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700631 }
632
Benjamin Wright84583f62018-10-04 14:22:34 -0700633 payload = decrypted_audio_payload.data();
634 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700635 } else if (crypto_options_.sframe.require_frame_encryption) {
636 RTC_DLOG(LS_ERROR)
637 << "FrameDecryptor required but not set, dropping packet";
638 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700639 }
640
Niels Möller530ead42018-10-04 14:28:39 +0200641 if (payload_data_length == 0) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100642 return OnReceivedPayloadData(nullptr, 0, header);
Niels Möller530ead42018-10-04 14:28:39 +0200643 }
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100644 return OnReceivedPayloadData(payload, payload_data_length, header);
Niels Möller530ead42018-10-04 14:28:39 +0200645}
646
Niels Möller349ade32018-11-16 09:50:42 +0100647// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100648void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200649 // Store playout timestamp for the received RTCP packet
650 UpdatePlayoutTimestamp(true);
651
652 // Deliver RTCP packet to RTP/RTCP module for parsing
653 _rtpRtcpModule->IncomingRtcpPacket(data, length);
654
655 int64_t rtt = GetRTT();
656 if (rtt == 0) {
657 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100658 return;
Niels Möller530ead42018-10-04 14:28:39 +0200659 }
660
Niels Möller530ead42018-10-04 14:28:39 +0200661 uint32_t ntp_secs = 0;
662 uint32_t ntp_frac = 0;
663 uint32_t rtp_timestamp = 0;
664 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
665 &rtp_timestamp)) {
666 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100667 return;
Niels Möller530ead42018-10-04 14:28:39 +0200668 }
669
670 {
671 rtc::CritScope lock(&ts_stats_lock_);
672 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
673 }
Niels Möller530ead42018-10-04 14:28:39 +0200674}
675
676int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200677 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200678 return _outputAudioLevel.LevelFullRange();
679}
680
681double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200682 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200683 return _outputAudioLevel.TotalEnergy();
684}
685
686double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200687 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200688 return _outputAudioLevel.TotalDuration();
689}
690
691void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200692 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200693 rtc::CritScope cs(&volume_settings_critsect_);
694 _outputGain = scaling;
695}
696
Niels Möller349ade32018-11-16 09:50:42 +0100697void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200698 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200699 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200700}
701
Niels Möller530ead42018-10-04 14:28:39 +0200702void ChannelReceive::RegisterReceiverCongestionControlObjects(
703 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200704 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200705 RTC_DCHECK(packet_router);
706 RTC_DCHECK(!packet_router_);
707 constexpr bool remb_candidate = false;
708 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
709 packet_router_ = packet_router;
710}
711
712void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200713 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200714 RTC_DCHECK(packet_router_);
715 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
716 packet_router_ = nullptr;
717}
718
Niels Möller349ade32018-11-16 09:50:42 +0100719CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200720 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200721 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100722 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200723
724 // The jitter statistics is updated for each received RTP packet and is
725 // based on received packets.
726 RtcpStatistics statistics;
727 StreamStatistician* statistician =
728 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
729 if (statistician) {
730 statistician->GetStatistics(&statistics,
731 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
732 }
733
Niels Möller530ead42018-10-04 14:28:39 +0200734 stats.cumulativeLost = statistics.packets_lost;
735 stats.extendedMax = statistics.extended_highest_sequence_number;
736 stats.jitterSamples = statistics.jitter;
737
738 // --- RTT
739 stats.rttMs = GetRTT();
740
741 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200742 if (statistician) {
Henrik Boström01738c62019-04-15 17:32:00 +0200743 StreamDataCounters data_counters;
744 statistician->GetReceiveStreamDataCounters(&data_counters);
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700745 if (use_standard_bytes_stats_) {
746 stats.bytesReceived = data_counters.transmitted.payload_bytes;
747 } else {
748 stats.bytesReceived = data_counters.transmitted.payload_bytes +
749 data_counters.transmitted.header_bytes +
750 data_counters.transmitted.padding_bytes;
751 }
Henrik Boström01738c62019-04-15 17:32:00 +0200752 stats.packetsReceived = data_counters.transmitted.packets;
753 stats.last_packet_received_timestamp_ms =
754 data_counters.last_packet_received_timestamp_ms;
755 } else {
756 stats.bytesReceived = 0;
757 stats.packetsReceived = 0;
758 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200759 }
760
Niels Möller530ead42018-10-04 14:28:39 +0200761 // --- Timestamps
762 {
763 rtc::CritScope lock(&ts_stats_lock_);
764 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
765 }
Niels Möller80c67622018-11-12 13:22:47 +0100766 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200767}
768
Niels Möller349ade32018-11-16 09:50:42 +0100769void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200770 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200771 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100772 if (enable) {
Niels Möller87da1092019-05-24 14:04:28 +0200773 rtp_receive_statistics_->SetMaxReorderingThreshold(remote_ssrc_,
774 max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100775 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100776 } else {
777 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möller87da1092019-05-24 14:04:28 +0200778 remote_ssrc_, kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200779 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100780 }
Niels Möller530ead42018-10-04 14:28:39 +0200781}
782
783// Called when we are missing one or more packets.
784int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
785 int length) {
786 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
787}
788
Niels Möllerdced9f62018-11-19 10:27:07 +0100789void ChannelReceive::SetAssociatedSendChannel(
790 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200791 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200792 rtc::CritScope lock(&assoc_send_channel_lock_);
793 associated_send_channel_ = channel;
794}
795
Niels Möller80c67622018-11-12 13:22:47 +0100796NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200797 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100798 NetworkStatistics stats;
799 int error = audio_coding_->GetNetworkStatistics(&stats);
800 RTC_DCHECK_EQ(0, error);
801 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200802}
803
Niels Möller80c67622018-11-12 13:22:47 +0100804AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200805 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100806 AudioDecodingCallStats stats;
807 audio_coding_->GetDecodingCallStatistics(&stats);
808 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200809}
810
811uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200812 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
813 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200814 rtc::CritScope lock(&video_sync_lock_);
815 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
816}
817
Niels Möller349ade32018-11-16 09:50:42 +0100818void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200819 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100820 // Limit to range accepted by both VoE and ACM, so we're at least getting as
821 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100822 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
823 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möller349ade32018-11-16 09:50:42 +0100824 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200825 RTC_DLOG(LS_ERROR)
826 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200827 }
Niels Möller530ead42018-10-04 14:28:39 +0200828}
829
Niels Möller349ade32018-11-16 09:50:42 +0100830uint32_t ChannelReceive::GetPlayoutTimestamp() const {
831 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200832 {
833 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100834 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200835 }
Niels Möller530ead42018-10-04 14:28:39 +0200836}
837
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100838bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
839 return audio_coding_->SetBaseMinimumPlayoutDelayMs(delay_ms);
840}
841
842int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
843 return audio_coding_->GetBaseMinimumPlayoutDelayMs();
844}
845
Niels Möller530ead42018-10-04 14:28:39 +0200846absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200847 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200848 Syncable::Info info;
849 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
850 &info.capture_time_ntp_frac, nullptr, nullptr,
851 &info.capture_time_source_clock) != 0) {
852 return absl::nullopt;
853 }
854 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000855 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200856 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
857 return absl::nullopt;
858 }
859 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
860 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
861 }
862 return info;
863}
864
865void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
866 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
867
868 if (!jitter_buffer_playout_timestamp_) {
869 // This can happen if this channel has not received any RTP packets. In
870 // this case, NetEq is not capable of computing a playout timestamp.
871 return;
872 }
873
874 uint16_t delay_ms = 0;
875 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
876 RTC_DLOG(LS_WARNING)
877 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
878 << " playout delay from the ADM";
879 return;
880 }
881
882 RTC_DCHECK(jitter_buffer_playout_timestamp_);
883 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
884
885 // Remove the playout delay.
886 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
887
888 {
889 rtc::CritScope lock(&video_sync_lock_);
890 if (!rtcp) {
891 playout_timestamp_rtp_ = playout_timestamp;
892 }
893 playout_delay_ms_ = delay_ms;
894 }
895}
896
897int ChannelReceive::GetRtpTimestampRateHz() const {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100898 const auto decoder = audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200899 // Default to the playout frequency if we've not gotten any packets yet.
900 // TODO(ossu): Zero clockrate can only happen if we've added an external
901 // decoder for a format we don't support internally. Remove once that way of
902 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100903 return (decoder && decoder->second.clockrate_hz != 0)
904 ? decoder->second.clockrate_hz
Niels Möller530ead42018-10-04 14:28:39 +0200905 : audio_coding_->PlayoutFrequency();
906}
907
908int64_t ChannelReceive::GetRTT() const {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700909 if (media_transport()) {
910 auto target_rate = media_transport()->GetLatestTargetTransferRate();
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800911 if (target_rate.has_value()) {
912 return target_rate->network_estimate.round_trip_time.ms();
913 }
914
915 return 0;
916 }
Niels Möller530ead42018-10-04 14:28:39 +0200917 RtcpMode method = _rtpRtcpModule->RTCP();
918 if (method == RtcpMode::kOff) {
919 return 0;
920 }
921 std::vector<RTCPReportBlock> report_blocks;
922 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
923
924 // TODO(nisse): Could we check the return value from the ->RTT() call below,
925 // instead of checking if we have any report blocks?
926 if (report_blocks.empty()) {
927 rtc::CritScope lock(&assoc_send_channel_lock_);
928 // Tries to get RTT from an associated channel.
929 if (!associated_send_channel_) {
930 return 0;
931 }
932 return associated_send_channel_->GetRTT();
933 }
934
935 int64_t rtt = 0;
936 int64_t avg_rtt = 0;
937 int64_t max_rtt = 0;
938 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100939 // TODO(nisse): This method computes RTT based on sender reports, even though
940 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200941 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
942 0) {
943 return 0;
944 }
945 return rtt;
946}
947
Niels Möller349ade32018-11-16 09:50:42 +0100948} // namespace
949
950std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100951 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100952 ProcessThread* module_process_thread,
953 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700954 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100955 Transport* rtcp_send_transport,
956 RtcEventLog* rtc_event_log,
957 uint32_t remote_ssrc,
958 size_t jitter_buffer_max_packets,
959 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100960 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100961 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100962 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
963 absl::optional<AudioCodecPairId> codec_pair_id,
964 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
965 const webrtc::CryptoOptions& crypto_options) {
966 return absl::make_unique<ChannelReceive>(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700967 clock, module_process_thread, audio_device_module, media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100968 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100969 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100970 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
971 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100972}
973
Niels Möller530ead42018-10-04 14:28:39 +0200974} // namespace voe
975} // namespace webrtc