blob: 5f592750271c89bd63b4db609f2003a3e5e6d5af [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"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010036#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möller530ead42018-10-04 14:28:39 +020037#include "modules/utility/include/process_thread.h"
38#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/critical_section.h"
Niels Möller530ead42018-10-04 14:28:39 +020040#include "rtc_base/format_macros.h"
41#include "rtc_base/location.h"
42#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010043#include "rtc_base/numerics/safe_minmax.h"
44#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020045#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "rtc_base/time_utils.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
Niels Möllerafb5dbb2019-02-15 15:21:47 +010060RTPHeader CreateRTPHeaderForMediaTransportFrame(
Sergey Silkine049eba2019-02-18 09:52:26 +000061 const MediaTransportEncodedAudioFrame& frame,
62 uint64_t channel_id) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +010063 webrtc::RTPHeader rtp_header;
64 rtp_header.payloadType = frame.payload_type();
65 rtp_header.payload_type_frequency = frame.sampling_rate_hz();
66 rtp_header.timestamp = frame.starting_sample_index();
67 rtp_header.sequenceNumber = frame.sequence_number();
Niels Möller7d76a312018-10-26 12:57:07 +020068
Sergey Silkine049eba2019-02-18 09:52:26 +000069 rtp_header.ssrc = static_cast<uint32_t>(channel_id);
Niels Möller7d76a312018-10-26 12:57:07 +020070
71 // The rest are initialized by the RTPHeader constructor.
Niels Möllerafb5dbb2019-02-15 15:21:47 +010072 return rtp_header;
Niels Möller7d76a312018-10-26 12:57:07 +020073}
74
Niels Möller349ade32018-11-16 09:50:42 +010075class ChannelReceive : public ChannelReceiveInterface,
76 public MediaTransportAudioSinkInterface {
77 public:
78 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +010079 ChannelReceive(Clock* clock,
80 ProcessThread* module_process_thread,
Niels Möller349ade32018-11-16 09:50:42 +010081 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -070082 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +010083 Transport* rtcp_send_transport,
84 RtcEventLog* rtc_event_log,
85 uint32_t remote_ssrc,
86 size_t jitter_buffer_max_packets,
87 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010088 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +010089 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +010090 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
91 absl::optional<AudioCodecPairId> codec_pair_id,
92 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
93 const webrtc::CryptoOptions& crypto_options);
94 ~ChannelReceive() override;
95
96 void SetSink(AudioSinkInterface* sink) override;
97
98 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
99
100 // API methods
101
102 void StartPlayout() override;
103 void StopPlayout() override;
104
105 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000106 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
107 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100108
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100109 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100110
111 // RtpPacketSinkInterface.
112 void OnRtpPacket(const RtpPacketReceived& packet) override;
113
114 // Muting, Volume and Level.
115 void SetChannelOutputVolumeScaling(float scaling) override;
116 int GetSpeechOutputLevelFullRange() const override;
117 // See description of "totalAudioEnergy" in the WebRTC stats spec:
118 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
119 double GetTotalOutputEnergy() const override;
120 double GetTotalOutputDuration() const override;
121
122 // Stats.
123 NetworkStatistics GetNetworkStatistics() const override;
124 AudioDecodingCallStats GetDecodingCallStatistics() const override;
125
126 // Audio+Video Sync.
127 uint32_t GetDelayEstimate() const override;
128 void SetMinimumPlayoutDelay(int delayMs) override;
129 uint32_t GetPlayoutTimestamp() const override;
130
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100131 // Audio quality.
132 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
133 int GetBaseMinimumPlayoutDelayMs() const override;
134
Niels Möller349ade32018-11-16 09:50:42 +0100135 // Produces the transport-related timestamps; current_delay_ms is left unset.
136 absl::optional<Syncable::Info> GetSyncInfo() const override;
137
138 // RTP+RTCP
139 void SetLocalSSRC(unsigned int ssrc) override;
140
141 void RegisterReceiverCongestionControlObjects(
142 PacketRouter* packet_router) override;
143 void ResetReceiverCongestionControlObjects() override;
144
145 CallReceiveStatistics GetRTCPStatistics() const override;
146 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
147
148 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
149 int sample_rate_hz,
150 AudioFrame* audio_frame) override;
151
152 int PreferredSampleRate() const override;
153
154 // Associate to a send channel.
155 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100156 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100157
158 std::vector<RtpSource> GetSources() const override;
159
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700160 // TODO(sukhanov): Return const pointer. It requires making media transport
161 // getters like GetLatestTargetTransferRate to be also const.
162 MediaTransportInterface* media_transport() const {
163 return media_transport_config_.media_transport;
164 }
165
Niels Möller349ade32018-11-16 09:50:42 +0100166 private:
Niels Möller349ade32018-11-16 09:50:42 +0100167 bool ReceivePacket(const uint8_t* packet,
168 size_t packet_length,
169 const RTPHeader& header);
170 int ResendPackets(const uint16_t* sequence_numbers, int length);
171 void UpdatePlayoutTimestamp(bool rtcp);
172
173 int GetRtpTimestampRateHz() const;
174 int64_t GetRTT() const;
175
176 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000177 void OnData(uint64_t channel_id,
178 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100179
180 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
181 size_t payloadSize,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100182 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100183
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100184 bool Playing() const {
185 rtc::CritScope lock(&playing_lock_);
186 return playing_;
187 }
188
Niels Möller349ade32018-11-16 09:50:42 +0100189 // Thread checkers document and lock usage of some methods to specific threads
190 // we know about. The goal is to eventually split up voe::ChannelReceive into
191 // parts with single-threaded semantics, and thereby reduce the need for
192 // locks.
193 rtc::ThreadChecker worker_thread_checker_;
194 rtc::ThreadChecker module_process_thread_checker_;
195 // Methods accessed from audio and video threads are checked for sequential-
196 // only access. We don't necessarily own and control these threads, so thread
197 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
198 // audio thread to another, but access is still sequential.
199 rtc::RaceChecker audio_thread_race_checker_;
200 rtc::RaceChecker video_capture_thread_race_checker_;
201 rtc::CriticalSection _callbackCritSect;
202 rtc::CriticalSection volume_settings_critsect_;
203
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100204 rtc::CriticalSection playing_lock_;
205 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100206
207 RtcEventLog* const event_log_;
208
209 // Indexed by payload type.
210 std::map<uint8_t, int> payload_type_frequencies_;
211
212 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
213 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
214 const uint32_t remote_ssrc_;
215
216 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
217 // queried on the worker thread.
218 rtc::CriticalSection rtp_sources_lock_;
219 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
220 absl::optional<uint32_t> last_received_rtp_timestamp_
221 RTC_GUARDED_BY(&rtp_sources_lock_);
222 absl::optional<int64_t> last_received_rtp_system_time_ms_
223 RTC_GUARDED_BY(&rtp_sources_lock_);
224 absl::optional<uint8_t> last_received_rtp_audio_level_
225 RTC_GUARDED_BY(&rtp_sources_lock_);
226
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_;
268};
Niels Möller530ead42018-10-04 14:28:39 +0200269
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100270int32_t ChannelReceive::OnReceivedPayloadData(const uint8_t* payloadData,
271 size_t payloadSize,
272 const RTPHeader& rtp_header) {
Niels Möller7d76a312018-10-26 12:57:07 +0200273 // We should not be receiving any RTP packets if media_transport is set.
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700274 RTC_CHECK(!media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200275
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100276 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200277 // Avoid inserting into NetEQ when we are not playing. Count the
278 // packet as discarded.
279 return 0;
280 }
281
282 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100283 if (audio_coding_->IncomingPacket(payloadData, payloadSize, rtp_header) !=
Niels Möller530ead42018-10-04 14:28:39 +0200284 0) {
285 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
286 "push data to the ACM";
287 return -1;
288 }
289
290 int64_t round_trip_time = 0;
291 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
292
293 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
294 if (!nack_list.empty()) {
295 // Can't use nack_list.data() since it's not supported by all
296 // compilers.
297 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
298 }
299 return 0;
300}
301
Niels Möller7d76a312018-10-26 12:57:07 +0200302// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000303void ChannelReceive::OnData(uint64_t channel_id,
304 MediaTransportEncodedAudioFrame frame) {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700305 RTC_CHECK(media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200306
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100307 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200308 // Avoid inserting into NetEQ when we are not playing. Count the
309 // packet as discarded.
310 return;
311 }
312
313 // Send encoded audio frame to Decoder / NetEq.
314 if (audio_coding_->IncomingPacket(
315 frame.encoded_data().data(), frame.encoded_data().size(),
Sergey Silkine049eba2019-02-18 09:52:26 +0000316 CreateRTPHeaderForMediaTransportFrame(frame, channel_id)) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200317 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
318 "push data to the ACM";
319 }
320}
321
Niels Möller530ead42018-10-04 14:28:39 +0200322AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
323 int sample_rate_hz,
324 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100325 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200326 audio_frame->sample_rate_hz_ = sample_rate_hz;
327
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100328 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
329
Niels Möller530ead42018-10-04 14:28:39 +0200330 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
331 bool muted;
332 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
333 &muted) == -1) {
334 RTC_DLOG(LS_ERROR)
335 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
336 // In all likelihood, the audio in this frame is garbage. We return an
337 // error so that the audio mixer module doesn't add it to the mix. As
338 // a result, it won't be played out and the actions skipped here are
339 // irrelevant.
340 return AudioMixer::Source::AudioFrameInfo::kError;
341 }
342
343 if (muted) {
344 // TODO(henrik.lundin): We should be able to do better than this. But we
345 // will have to go through all the cases below where the audio samples may
346 // be used, and handle the muted case in some way.
347 AudioFrameOperations::Mute(audio_frame);
348 }
349
350 {
351 // Pass the audio buffers to an optional sink callback, before applying
352 // scaling/panning, as that applies to the mix operation.
353 // External recipients of the audio (e.g. via AudioTrack), will do their
354 // own mixing/dynamic processing.
355 rtc::CritScope cs(&_callbackCritSect);
356 if (audio_sink_) {
357 AudioSinkInterface::Data data(
358 audio_frame->data(), audio_frame->samples_per_channel_,
359 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
360 audio_frame->timestamp_);
361 audio_sink_->OnData(data);
362 }
363 }
364
365 float output_gain = 1.0f;
366 {
367 rtc::CritScope cs(&volume_settings_critsect_);
368 output_gain = _outputGain;
369 }
370
371 // Output volume scaling
372 if (output_gain < 0.99f || output_gain > 1.01f) {
373 // TODO(solenberg): Combine with mute state - this can cause clicks!
374 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
375 }
376
377 // Measure audio level (0-9)
378 // TODO(henrik.lundin) Use the |muted| information here too.
379 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
380 // https://crbug.com/webrtc/7517).
381 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
382
383 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
384 // The first frame with a valid rtp timestamp.
385 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
386 }
387
388 if (capture_start_rtp_time_stamp_ >= 0) {
389 // audio_frame.timestamp_ should be valid from now on.
390
391 // Compute elapsed time.
392 int64_t unwrap_timestamp =
393 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
394 audio_frame->elapsed_time_ms_ =
395 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
396 (GetRtpTimestampRateHz() / 1000);
397
398 {
399 rtc::CritScope lock(&ts_stats_lock_);
400 // Compute ntp time.
401 audio_frame->ntp_time_ms_ =
402 ntp_estimator_.Estimate(audio_frame->timestamp_);
403 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
404 if (audio_frame->ntp_time_ms_ > 0) {
405 // Compute |capture_start_ntp_time_ms_| so that
406 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
407 capture_start_ntp_time_ms_ =
408 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
409 }
410 }
411 }
412
413 {
414 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
415 audio_coding_->TargetDelayMs());
416 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
417 rtc::CritScope lock(&video_sync_lock_);
418 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
419 jitter_buffer_delay + playout_delay_ms_);
420 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
421 jitter_buffer_delay);
422 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
423 playout_delay_ms_);
424 }
425
426 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
427 : AudioMixer::Source::AudioFrameInfo::kNormal;
428}
429
430int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100431 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200432 // Return the bigger of playout and receive frequency in the ACM.
433 return std::max(audio_coding_->ReceiveFrequency(),
434 audio_coding_->PlayoutFrequency());
435}
436
437ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100438 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200439 ProcessThread* module_process_thread,
440 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700441 const MediaTransportConfig& media_transport_config,
Niels Möllerae4237e2018-10-05 11:28:38 +0200442 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200443 RtcEventLog* rtc_event_log,
444 uint32_t remote_ssrc,
445 size_t jitter_buffer_max_packets,
446 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100447 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100448 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200449 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700450 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700451 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700452 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200453 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100454 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200455 remote_ssrc_(remote_ssrc),
456 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100457 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200458 playout_timestamp_rtp_(0),
459 playout_delay_ms_(0),
460 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
461 capture_start_rtp_time_stamp_(-1),
462 capture_start_ntp_time_ms_(-1),
463 _moduleProcessThreadPtr(module_process_thread),
464 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200465 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700466 associated_send_channel_(nullptr),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700467 media_transport_config_(media_transport_config),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700468 frame_decryptor_(frame_decryptor),
469 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100470 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200471 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100472
Niels Möller530ead42018-10-04 14:28:39 +0200473 RTC_DCHECK(module_process_thread);
474 RTC_DCHECK(audio_device_module);
475 AudioCodingModule::Config acm_config;
476 acm_config.decoder_factory = decoder_factory;
477 acm_config.neteq_config.codec_pair_id = codec_pair_id;
478 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
479 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100480 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200481 acm_config.neteq_config.enable_muted_state = true;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100482 acm_config.neteq_config.enable_rtx_handling =
483 jitter_buffer_enable_rtx_handling;
Niels Möller530ead42018-10-04 14:28:39 +0200484 audio_coding_.reset(AudioCodingModule::Create(acm_config));
485
486 _outputAudioLevel.Clear();
487
488 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
489 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100490 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200491 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100492 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200493 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200494 configuration.receive_statistics = rtp_receive_statistics_.get();
495
496 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200497
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100498 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200499 _rtpRtcpModule->SetSendingMediaStatus(false);
500 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200501
Niels Möller530ead42018-10-04 14:28:39 +0200502 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
503
Niels Möller530ead42018-10-04 14:28:39 +0200504 // Ensure that RTCP is enabled by default for the created channel.
505 // Note that, the module will keep generating RTCP until it is explicitly
506 // disabled by the user.
507 // After StopListen (when no sockets exists), RTCP packets will no longer
508 // be transmitted since the Transport object will then be invalid.
509 // RTCP is enabled by default.
510 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200511
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700512 if (media_transport()) {
513 media_transport()->SetReceiveAudioSink(this);
Niels Möller7d76a312018-10-26 12:57:07 +0200514 }
Niels Möller530ead42018-10-04 14:28:39 +0200515}
516
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100517ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200518 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200519
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700520 if (media_transport()) {
521 media_transport()->SetReceiveAudioSink(nullptr);
Niels Möller7d76a312018-10-26 12:57:07 +0200522 }
523
Niels Möller530ead42018-10-04 14:28:39 +0200524 StopPlayout();
525
Niels Möller530ead42018-10-04 14:28:39 +0200526 int error = audio_coding_->RegisterTransportCallback(NULL);
527 RTC_DCHECK_EQ(0, error);
528
Niels Möller530ead42018-10-04 14:28:39 +0200529 if (_moduleProcessThreadPtr)
530 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200531}
532
533void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200534 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200535 rtc::CritScope cs(&_callbackCritSect);
536 audio_sink_ = sink;
537}
538
Niels Möller80c67622018-11-12 13:22:47 +0100539void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200540 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100541 rtc::CritScope lock(&playing_lock_);
542 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200543}
544
Niels Möller80c67622018-11-12 13:22:47 +0100545void ChannelReceive::StopPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200546 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100547 rtc::CritScope lock(&playing_lock_);
548 playing_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200549 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200550}
551
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100552absl::optional<std::pair<int, SdpAudioFormat>>
553 ChannelReceive::GetReceiveCodec() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200554 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100555 return audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200556}
557
558std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200559 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200560 int64_t now_ms = rtc::TimeMillis();
561 std::vector<RtpSource> sources;
562 {
563 rtc::CritScope cs(&rtp_sources_lock_);
564 sources = contributing_sources_.GetSources(now_ms);
565 if (last_received_rtp_system_time_ms_ >=
566 now_ms - ContributingSources::kHistoryMs) {
Johannes Kronb5d91832019-05-21 13:19:22 +0200567 RTC_DCHECK(last_received_rtp_timestamp_.has_value());
Niels Möller530ead42018-10-04 14:28:39 +0200568 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
Johannes Kronb5d91832019-05-21 13:19:22 +0200569 RtpSourceType::SSRC, last_received_rtp_audio_level_,
570 *last_received_rtp_timestamp_);
Niels Möller530ead42018-10-04 14:28:39 +0200571 }
572 }
573 return sources;
574}
575
576void ChannelReceive::SetReceiveCodecs(
577 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200578 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200579 for (const auto& kv : codecs) {
580 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
581 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
582 }
583 audio_coding_->SetReceiveCodecs(codecs);
584}
585
Niels Möller349ade32018-11-16 09:50:42 +0100586// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200587void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
588 int64_t now_ms = rtc::TimeMillis();
589 uint8_t audio_level;
590 bool voice_activity;
591 bool has_audio_level =
592 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
593
594 {
595 rtc::CritScope cs(&rtp_sources_lock_);
596 last_received_rtp_timestamp_ = packet.Timestamp();
597 last_received_rtp_system_time_ms_ = now_ms;
598 if (has_audio_level)
599 last_received_rtp_audio_level_ = audio_level;
600 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100601 contributing_sources_.Update(
602 now_ms, csrcs,
Johannes Kronb5d91832019-05-21 13:19:22 +0200603 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt,
604 packet.Timestamp());
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;
Niels Möller530ead42018-10-04 14:28:39 +0200631
Benjamin Wright84583f62018-10-04 14:22:34 -0700632 size_t payload_data_length = payload_length - header.paddingLength;
633
634 // E2EE Custom Audio Frame Decryption (This is optional).
635 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
636 rtc::Buffer decrypted_audio_payload;
637 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000638 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700639 cricket::MEDIA_TYPE_AUDIO, payload_length);
640 decrypted_audio_payload.SetSize(max_plaintext_size);
641
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000642 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
643 header.arrOfCSRCs + header.numCSRCs);
644 const FrameDecryptorInterface::Result decrypt_result =
645 frame_decryptor_->Decrypt(
646 cricket::MEDIA_TYPE_AUDIO, csrcs,
647 /*additional_data=*/nullptr,
648 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
649 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700650
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000651 if (decrypt_result.IsOk()) {
652 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
653 } else {
654 // Interpret failures as a silent frame.
655 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700656 }
657
Benjamin Wright84583f62018-10-04 14:22:34 -0700658 payload = decrypted_audio_payload.data();
659 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700660 } else if (crypto_options_.sframe.require_frame_encryption) {
661 RTC_DLOG(LS_ERROR)
662 << "FrameDecryptor required but not set, dropping packet";
663 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700664 }
665
Niels Möller530ead42018-10-04 14:28:39 +0200666 if (payload_data_length == 0) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100667 return OnReceivedPayloadData(nullptr, 0, header);
Niels Möller530ead42018-10-04 14:28:39 +0200668 }
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100669 return OnReceivedPayloadData(payload, payload_data_length, header);
Niels Möller530ead42018-10-04 14:28:39 +0200670}
671
Niels Möller349ade32018-11-16 09:50:42 +0100672// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100673void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200674 // Store playout timestamp for the received RTCP packet
675 UpdatePlayoutTimestamp(true);
676
677 // Deliver RTCP packet to RTP/RTCP module for parsing
678 _rtpRtcpModule->IncomingRtcpPacket(data, length);
679
680 int64_t rtt = GetRTT();
681 if (rtt == 0) {
682 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100683 return;
Niels Möller530ead42018-10-04 14:28:39 +0200684 }
685
Niels Möller530ead42018-10-04 14:28:39 +0200686 uint32_t ntp_secs = 0;
687 uint32_t ntp_frac = 0;
688 uint32_t rtp_timestamp = 0;
689 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
690 &rtp_timestamp)) {
691 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100692 return;
Niels Möller530ead42018-10-04 14:28:39 +0200693 }
694
695 {
696 rtc::CritScope lock(&ts_stats_lock_);
697 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
698 }
Niels Möller530ead42018-10-04 14:28:39 +0200699}
700
701int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200702 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200703 return _outputAudioLevel.LevelFullRange();
704}
705
706double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200707 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200708 return _outputAudioLevel.TotalEnergy();
709}
710
711double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200712 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200713 return _outputAudioLevel.TotalDuration();
714}
715
716void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200717 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200718 rtc::CritScope cs(&volume_settings_critsect_);
719 _outputGain = scaling;
720}
721
Niels Möller349ade32018-11-16 09:50:42 +0100722void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200723 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200724 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200725}
726
Niels Möller530ead42018-10-04 14:28:39 +0200727void ChannelReceive::RegisterReceiverCongestionControlObjects(
728 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200729 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200730 RTC_DCHECK(packet_router);
731 RTC_DCHECK(!packet_router_);
732 constexpr bool remb_candidate = false;
733 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
734 packet_router_ = packet_router;
735}
736
737void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200738 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200739 RTC_DCHECK(packet_router_);
740 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
741 packet_router_ = nullptr;
742}
743
Niels Möller349ade32018-11-16 09:50:42 +0100744CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200745 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200746 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100747 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200748
749 // The jitter statistics is updated for each received RTP packet and is
750 // based on received packets.
751 RtcpStatistics statistics;
752 StreamStatistician* statistician =
753 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
754 if (statistician) {
755 statistician->GetStatistics(&statistics,
756 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
757 }
758
759 stats.fractionLost = statistics.fraction_lost;
760 stats.cumulativeLost = statistics.packets_lost;
761 stats.extendedMax = statistics.extended_highest_sequence_number;
762 stats.jitterSamples = statistics.jitter;
763
764 // --- RTT
765 stats.rttMs = GetRTT();
766
767 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200768 if (statistician) {
Henrik Boström01738c62019-04-15 17:32:00 +0200769 StreamDataCounters data_counters;
770 statistician->GetReceiveStreamDataCounters(&data_counters);
771 // TODO(http://crbug.com/webrtc/10525): Bytes received should only include
772 // payload bytes, not header and padding bytes.
773 stats.bytesReceived = data_counters.transmitted.payload_bytes +
774 data_counters.transmitted.header_bytes +
775 data_counters.transmitted.padding_bytes;
776 stats.packetsReceived = data_counters.transmitted.packets;
777 stats.last_packet_received_timestamp_ms =
778 data_counters.last_packet_received_timestamp_ms;
779 } else {
780 stats.bytesReceived = 0;
781 stats.packetsReceived = 0;
782 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200783 }
784
Niels Möller530ead42018-10-04 14:28:39 +0200785 // --- Timestamps
786 {
787 rtc::CritScope lock(&ts_stats_lock_);
788 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
789 }
Niels Möller80c67622018-11-12 13:22:47 +0100790 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200791}
792
Niels Möller349ade32018-11-16 09:50:42 +0100793void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200794 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200795 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100796 if (enable) {
797 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100798 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100799 } else {
800 rtp_receive_statistics_->SetMaxReorderingThreshold(
801 kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200802 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100803 }
Niels Möller530ead42018-10-04 14:28:39 +0200804}
805
806// Called when we are missing one or more packets.
807int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
808 int length) {
809 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
810}
811
Niels Möllerdced9f62018-11-19 10:27:07 +0100812void ChannelReceive::SetAssociatedSendChannel(
813 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200814 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200815 rtc::CritScope lock(&assoc_send_channel_lock_);
816 associated_send_channel_ = channel;
817}
818
Niels Möller80c67622018-11-12 13:22:47 +0100819NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200820 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100821 NetworkStatistics stats;
822 int error = audio_coding_->GetNetworkStatistics(&stats);
823 RTC_DCHECK_EQ(0, error);
824 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200825}
826
Niels Möller80c67622018-11-12 13:22:47 +0100827AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200828 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100829 AudioDecodingCallStats stats;
830 audio_coding_->GetDecodingCallStatistics(&stats);
831 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200832}
833
834uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200835 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
836 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200837 rtc::CritScope lock(&video_sync_lock_);
838 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
839}
840
Niels Möller349ade32018-11-16 09:50:42 +0100841void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200842 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100843 // Limit to range accepted by both VoE and ACM, so we're at least getting as
844 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100845 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
846 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möller349ade32018-11-16 09:50:42 +0100847 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200848 RTC_DLOG(LS_ERROR)
849 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200850 }
Niels Möller530ead42018-10-04 14:28:39 +0200851}
852
Niels Möller349ade32018-11-16 09:50:42 +0100853uint32_t ChannelReceive::GetPlayoutTimestamp() const {
854 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200855 {
856 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100857 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200858 }
Niels Möller530ead42018-10-04 14:28:39 +0200859}
860
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100861bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
862 return audio_coding_->SetBaseMinimumPlayoutDelayMs(delay_ms);
863}
864
865int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
866 return audio_coding_->GetBaseMinimumPlayoutDelayMs();
867}
868
Niels Möller530ead42018-10-04 14:28:39 +0200869absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200870 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200871 Syncable::Info info;
872 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
873 &info.capture_time_ntp_frac, nullptr, nullptr,
874 &info.capture_time_source_clock) != 0) {
875 return absl::nullopt;
876 }
877 {
878 rtc::CritScope cs(&rtp_sources_lock_);
879 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
880 return absl::nullopt;
881 }
882 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
883 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
884 }
885 return info;
886}
887
888void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
889 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
890
891 if (!jitter_buffer_playout_timestamp_) {
892 // This can happen if this channel has not received any RTP packets. In
893 // this case, NetEq is not capable of computing a playout timestamp.
894 return;
895 }
896
897 uint16_t delay_ms = 0;
898 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
899 RTC_DLOG(LS_WARNING)
900 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
901 << " playout delay from the ADM";
902 return;
903 }
904
905 RTC_DCHECK(jitter_buffer_playout_timestamp_);
906 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
907
908 // Remove the playout delay.
909 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
910
911 {
912 rtc::CritScope lock(&video_sync_lock_);
913 if (!rtcp) {
914 playout_timestamp_rtp_ = playout_timestamp;
915 }
916 playout_delay_ms_ = delay_ms;
917 }
918}
919
920int ChannelReceive::GetRtpTimestampRateHz() const {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100921 const auto decoder = audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200922 // Default to the playout frequency if we've not gotten any packets yet.
923 // TODO(ossu): Zero clockrate can only happen if we've added an external
924 // decoder for a format we don't support internally. Remove once that way of
925 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100926 return (decoder && decoder->second.clockrate_hz != 0)
927 ? decoder->second.clockrate_hz
Niels Möller530ead42018-10-04 14:28:39 +0200928 : audio_coding_->PlayoutFrequency();
929}
930
931int64_t ChannelReceive::GetRTT() const {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700932 if (media_transport()) {
933 auto target_rate = media_transport()->GetLatestTargetTransferRate();
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800934 if (target_rate.has_value()) {
935 return target_rate->network_estimate.round_trip_time.ms();
936 }
937
938 return 0;
939 }
Niels Möller530ead42018-10-04 14:28:39 +0200940 RtcpMode method = _rtpRtcpModule->RTCP();
941 if (method == RtcpMode::kOff) {
942 return 0;
943 }
944 std::vector<RTCPReportBlock> report_blocks;
945 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
946
947 // TODO(nisse): Could we check the return value from the ->RTT() call below,
948 // instead of checking if we have any report blocks?
949 if (report_blocks.empty()) {
950 rtc::CritScope lock(&assoc_send_channel_lock_);
951 // Tries to get RTT from an associated channel.
952 if (!associated_send_channel_) {
953 return 0;
954 }
955 return associated_send_channel_->GetRTT();
956 }
957
958 int64_t rtt = 0;
959 int64_t avg_rtt = 0;
960 int64_t max_rtt = 0;
961 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100962 // TODO(nisse): This method computes RTT based on sender reports, even though
963 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200964 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
965 0) {
966 return 0;
967 }
968 return rtt;
969}
970
Niels Möller349ade32018-11-16 09:50:42 +0100971} // namespace
972
973std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100974 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100975 ProcessThread* module_process_thread,
976 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700977 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100978 Transport* rtcp_send_transport,
979 RtcEventLog* rtc_event_log,
980 uint32_t remote_ssrc,
981 size_t jitter_buffer_max_packets,
982 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100983 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100984 bool jitter_buffer_enable_rtx_handling,
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>(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700990 clock, module_process_thread, audio_device_module, media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100991 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100992 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100993 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
994 decoder_factory, codec_pair_id, 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