blob: fbd92f6a3e754159590465b54b3c71c8d4b5f77d [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öller7d76a312018-10-26 12:57:07 +020060webrtc::FrameType WebrtcFrameTypeForMediaTransportFrameType(
61 MediaTransportEncodedAudioFrame::FrameType frame_type) {
62 switch (frame_type) {
63 case MediaTransportEncodedAudioFrame::FrameType::kSpeech:
64 return kAudioFrameSpeech;
65 break;
66
67 case MediaTransportEncodedAudioFrame::FrameType::
68 kDiscountinuousTransmission:
69 return kAudioFrameCN;
70 break;
71 }
72}
73
74WebRtcRTPHeader CreateWebrtcRTPHeaderForMediaTransportFrame(
75 const MediaTransportEncodedAudioFrame& frame,
76 uint64_t channel_id) {
77 webrtc::WebRtcRTPHeader webrtc_header = {};
78 webrtc_header.header.payloadType = frame.payload_type();
79 webrtc_header.header.payload_type_frequency = frame.sampling_rate_hz();
80 webrtc_header.header.timestamp = frame.starting_sample_index();
81 webrtc_header.header.sequenceNumber = frame.sequence_number();
82
83 webrtc_header.frameType =
84 WebrtcFrameTypeForMediaTransportFrameType(frame.frame_type());
85
86 webrtc_header.header.ssrc = static_cast<uint32_t>(channel_id);
87
88 // The rest are initialized by the RTPHeader constructor.
89 return webrtc_header;
90}
91
Niels Möller349ade32018-11-16 09:50:42 +010092class ChannelReceive : public ChannelReceiveInterface,
93 public MediaTransportAudioSinkInterface {
94 public:
95 // Used for receive streams.
96 ChannelReceive(ProcessThread* module_process_thread,
97 AudioDeviceModule* audio_device_module,
98 MediaTransportInterface* media_transport,
99 Transport* rtcp_send_transport,
100 RtcEventLog* rtc_event_log,
101 uint32_t remote_ssrc,
102 size_t jitter_buffer_max_packets,
103 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100104 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100105 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100106 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
107 absl::optional<AudioCodecPairId> codec_pair_id,
108 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
109 const webrtc::CryptoOptions& crypto_options);
110 ~ChannelReceive() override;
111
112 void SetSink(AudioSinkInterface* sink) override;
113
114 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
115
116 // API methods
117
118 void StartPlayout() override;
119 void StopPlayout() override;
120
121 // Codecs
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100122 absl::optional<std::pair<int, SdpAudioFormat>>
123 GetReceiveCodec() const override;
Niels Möller349ade32018-11-16 09:50:42 +0100124
125 bool ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
126
127 // RtpPacketSinkInterface.
128 void OnRtpPacket(const RtpPacketReceived& packet) override;
129
130 // Muting, Volume and Level.
131 void SetChannelOutputVolumeScaling(float scaling) override;
132 int GetSpeechOutputLevelFullRange() const override;
133 // See description of "totalAudioEnergy" in the WebRTC stats spec:
134 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
135 double GetTotalOutputEnergy() const override;
136 double GetTotalOutputDuration() const override;
137
138 // Stats.
139 NetworkStatistics GetNetworkStatistics() const override;
140 AudioDecodingCallStats GetDecodingCallStatistics() const override;
141
142 // Audio+Video Sync.
143 uint32_t GetDelayEstimate() const override;
144 void SetMinimumPlayoutDelay(int delayMs) override;
145 uint32_t GetPlayoutTimestamp() const override;
146
147 // Produces the transport-related timestamps; current_delay_ms is left unset.
148 absl::optional<Syncable::Info> GetSyncInfo() const override;
149
150 // RTP+RTCP
151 void SetLocalSSRC(unsigned int ssrc) override;
152
153 void RegisterReceiverCongestionControlObjects(
154 PacketRouter* packet_router) override;
155 void ResetReceiverCongestionControlObjects() override;
156
157 CallReceiveStatistics GetRTCPStatistics() const override;
158 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
159
160 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
161 int sample_rate_hz,
162 AudioFrame* audio_frame) override;
163
164 int PreferredSampleRate() const override;
165
166 // Associate to a send channel.
167 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100168 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100169
170 std::vector<RtpSource> GetSources() const override;
171
172 private:
Niels Möller349ade32018-11-16 09:50:42 +0100173 bool ReceivePacket(const uint8_t* packet,
174 size_t packet_length,
175 const RTPHeader& header);
176 int ResendPackets(const uint16_t* sequence_numbers, int length);
177 void UpdatePlayoutTimestamp(bool rtcp);
178
179 int GetRtpTimestampRateHz() const;
180 int64_t GetRTT() const;
181
182 // MediaTransportAudioSinkInterface override;
183 void OnData(uint64_t channel_id,
184 MediaTransportEncodedAudioFrame frame) override;
185
186 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
187 size_t payloadSize,
188 const WebRtcRTPHeader* rtpHeader);
189
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100190 bool Playing() const {
191 rtc::CritScope lock(&playing_lock_);
192 return playing_;
193 }
194
Niels Möller349ade32018-11-16 09:50:42 +0100195 // Thread checkers document and lock usage of some methods to specific threads
196 // we know about. The goal is to eventually split up voe::ChannelReceive into
197 // parts with single-threaded semantics, and thereby reduce the need for
198 // locks.
199 rtc::ThreadChecker worker_thread_checker_;
200 rtc::ThreadChecker module_process_thread_checker_;
201 // Methods accessed from audio and video threads are checked for sequential-
202 // only access. We don't necessarily own and control these threads, so thread
203 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
204 // audio thread to another, but access is still sequential.
205 rtc::RaceChecker audio_thread_race_checker_;
206 rtc::RaceChecker video_capture_thread_race_checker_;
207 rtc::CriticalSection _callbackCritSect;
208 rtc::CriticalSection volume_settings_critsect_;
209
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100210 rtc::CriticalSection playing_lock_;
211 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100212
213 RtcEventLog* const event_log_;
214
215 // Indexed by payload type.
216 std::map<uint8_t, int> payload_type_frequencies_;
217
218 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
219 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
220 const uint32_t remote_ssrc_;
221
222 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
223 // queried on the worker thread.
224 rtc::CriticalSection rtp_sources_lock_;
225 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
226 absl::optional<uint32_t> last_received_rtp_timestamp_
227 RTC_GUARDED_BY(&rtp_sources_lock_);
228 absl::optional<int64_t> last_received_rtp_system_time_ms_
229 RTC_GUARDED_BY(&rtp_sources_lock_);
230 absl::optional<uint8_t> last_received_rtp_audio_level_
231 RTC_GUARDED_BY(&rtp_sources_lock_);
232
233 std::unique_ptr<AudioCodingModule> audio_coding_;
234 AudioSinkInterface* audio_sink_ = nullptr;
235 AudioLevel _outputAudioLevel;
236
237 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
238
239 // Timestamp of the audio pulled from NetEq.
240 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
241
242 rtc::CriticalSection video_sync_lock_;
243 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
244 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
245
246 rtc::CriticalSection ts_stats_lock_;
247
248 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
249 // The rtp timestamp of the first played out audio frame.
250 int64_t capture_start_rtp_time_stamp_;
251 // The capture ntp time (in local timebase) of the first played out audio
252 // frame.
253 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
254
255 // uses
256 ProcessThread* _moduleProcessThreadPtr;
257 AudioDeviceModule* _audioDeviceModulePtr;
258 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
259
260 // An associated send channel.
261 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100262 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100263 RTC_GUARDED_BY(assoc_send_channel_lock_);
264
265 PacketRouter* packet_router_ = nullptr;
266
267 rtc::ThreadChecker construction_thread_;
268
269 MediaTransportInterface* const media_transport_;
270
271 // E2EE Audio Frame Decryption
272 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
273 webrtc::CryptoOptions crypto_options_;
274};
Niels Möller530ead42018-10-04 14:28:39 +0200275
Niels Möller530ead42018-10-04 14:28:39 +0200276int32_t ChannelReceive::OnReceivedPayloadData(
277 const uint8_t* payloadData,
278 size_t payloadSize,
279 const WebRtcRTPHeader* rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200280 // We should not be receiving any RTP packets if media_transport is set.
281 RTC_CHECK(!media_transport_);
282
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100283 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200284 // Avoid inserting into NetEQ when we are not playing. Count the
285 // packet as discarded.
286 return 0;
287 }
288
289 // Push the incoming payload (parsed and ready for decoding) into the ACM
290 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
291 0) {
292 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
293 "push data to the ACM";
294 return -1;
295 }
296
297 int64_t round_trip_time = 0;
298 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
299
300 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
301 if (!nack_list.empty()) {
302 // Can't use nack_list.data() since it's not supported by all
303 // compilers.
304 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
305 }
306 return 0;
307}
308
Niels Möller7d76a312018-10-26 12:57:07 +0200309// MediaTransportAudioSinkInterface override.
310void ChannelReceive::OnData(uint64_t channel_id,
311 MediaTransportEncodedAudioFrame frame) {
312 RTC_CHECK(media_transport_);
313
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100314 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200315 // Avoid inserting into NetEQ when we are not playing. Count the
316 // packet as discarded.
317 return;
318 }
319
320 // Send encoded audio frame to Decoder / NetEq.
321 if (audio_coding_->IncomingPacket(
322 frame.encoded_data().data(), frame.encoded_data().size(),
323 CreateWebrtcRTPHeaderForMediaTransportFrame(frame, channel_id)) !=
324 0) {
325 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
326 "push data to the ACM";
327 }
328}
329
Niels Möller530ead42018-10-04 14:28:39 +0200330AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
331 int sample_rate_hz,
332 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100333 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200334 audio_frame->sample_rate_hz_ = sample_rate_hz;
335
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100336 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
337
Niels Möller530ead42018-10-04 14:28:39 +0200338 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
339 bool muted;
340 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
341 &muted) == -1) {
342 RTC_DLOG(LS_ERROR)
343 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
344 // In all likelihood, the audio in this frame is garbage. We return an
345 // error so that the audio mixer module doesn't add it to the mix. As
346 // a result, it won't be played out and the actions skipped here are
347 // irrelevant.
348 return AudioMixer::Source::AudioFrameInfo::kError;
349 }
350
351 if (muted) {
352 // TODO(henrik.lundin): We should be able to do better than this. But we
353 // will have to go through all the cases below where the audio samples may
354 // be used, and handle the muted case in some way.
355 AudioFrameOperations::Mute(audio_frame);
356 }
357
358 {
359 // Pass the audio buffers to an optional sink callback, before applying
360 // scaling/panning, as that applies to the mix operation.
361 // External recipients of the audio (e.g. via AudioTrack), will do their
362 // own mixing/dynamic processing.
363 rtc::CritScope cs(&_callbackCritSect);
364 if (audio_sink_) {
365 AudioSinkInterface::Data data(
366 audio_frame->data(), audio_frame->samples_per_channel_,
367 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
368 audio_frame->timestamp_);
369 audio_sink_->OnData(data);
370 }
371 }
372
373 float output_gain = 1.0f;
374 {
375 rtc::CritScope cs(&volume_settings_critsect_);
376 output_gain = _outputGain;
377 }
378
379 // Output volume scaling
380 if (output_gain < 0.99f || output_gain > 1.01f) {
381 // TODO(solenberg): Combine with mute state - this can cause clicks!
382 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
383 }
384
385 // Measure audio level (0-9)
386 // TODO(henrik.lundin) Use the |muted| information here too.
387 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
388 // https://crbug.com/webrtc/7517).
389 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
390
391 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
392 // The first frame with a valid rtp timestamp.
393 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
394 }
395
396 if (capture_start_rtp_time_stamp_ >= 0) {
397 // audio_frame.timestamp_ should be valid from now on.
398
399 // Compute elapsed time.
400 int64_t unwrap_timestamp =
401 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
402 audio_frame->elapsed_time_ms_ =
403 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
404 (GetRtpTimestampRateHz() / 1000);
405
406 {
407 rtc::CritScope lock(&ts_stats_lock_);
408 // Compute ntp time.
409 audio_frame->ntp_time_ms_ =
410 ntp_estimator_.Estimate(audio_frame->timestamp_);
411 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
412 if (audio_frame->ntp_time_ms_ > 0) {
413 // Compute |capture_start_ntp_time_ms_| so that
414 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
415 capture_start_ntp_time_ms_ =
416 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
417 }
418 }
419 }
420
421 {
422 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
423 audio_coding_->TargetDelayMs());
424 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
425 rtc::CritScope lock(&video_sync_lock_);
426 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
427 jitter_buffer_delay + playout_delay_ms_);
428 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
429 jitter_buffer_delay);
430 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
431 playout_delay_ms_);
432 }
433
434 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
435 : AudioMixer::Source::AudioFrameInfo::kNormal;
436}
437
438int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100439 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200440 // Return the bigger of playout and receive frequency in the ACM.
441 return std::max(audio_coding_->ReceiveFrequency(),
442 audio_coding_->PlayoutFrequency());
443}
444
445ChannelReceive::ChannelReceive(
446 ProcessThread* module_process_thread,
447 AudioDeviceModule* audio_device_module,
Niels Möller7d76a312018-10-26 12:57:07 +0200448 MediaTransportInterface* media_transport,
Niels Möllerae4237e2018-10-05 11:28:38 +0200449 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200450 RtcEventLog* rtc_event_log,
451 uint32_t remote_ssrc,
452 size_t jitter_buffer_max_packets,
453 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100454 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100455 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200456 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700457 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700458 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700459 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200460 : event_log_(rtc_event_log),
461 rtp_receive_statistics_(
462 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
463 remote_ssrc_(remote_ssrc),
464 _outputAudioLevel(),
465 ntp_estimator_(Clock::GetRealTimeClock()),
466 playout_timestamp_rtp_(0),
467 playout_delay_ms_(0),
468 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
469 capture_start_rtp_time_stamp_(-1),
470 capture_start_ntp_time_ms_(-1),
471 _moduleProcessThreadPtr(module_process_thread),
472 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200473 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700474 associated_send_channel_(nullptr),
Niels Möller7d76a312018-10-26 12:57:07 +0200475 media_transport_(media_transport),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700476 frame_decryptor_(frame_decryptor),
477 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100478 // TODO(nisse): Use _moduleProcessThreadPtr instead?
479 module_process_thread_checker_.DetachFromThread();
480
Niels Möller530ead42018-10-04 14:28:39 +0200481 RTC_DCHECK(module_process_thread);
482 RTC_DCHECK(audio_device_module);
483 AudioCodingModule::Config acm_config;
484 acm_config.decoder_factory = decoder_factory;
485 acm_config.neteq_config.codec_pair_id = codec_pair_id;
486 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
487 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100488 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200489 acm_config.neteq_config.enable_muted_state = true;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100490 acm_config.neteq_config.enable_rtx_handling =
491 jitter_buffer_enable_rtx_handling;
Niels Möller530ead42018-10-04 14:28:39 +0200492 audio_coding_.reset(AudioCodingModule::Create(acm_config));
493
494 _outputAudioLevel.Clear();
495
496 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
497 RtpRtcp::Configuration configuration;
498 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100499 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200500 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200501 configuration.receive_statistics = rtp_receive_statistics_.get();
502
503 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200504
505 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
506 _rtpRtcpModule->SetSendingMediaStatus(false);
507 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200508
Niels Möller530ead42018-10-04 14:28:39 +0200509 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
510
Niels Möller530ead42018-10-04 14:28:39 +0200511 // Ensure that RTCP is enabled by default for the created channel.
512 // Note that, the module will keep generating RTCP until it is explicitly
513 // disabled by the user.
514 // After StopListen (when no sockets exists), RTCP packets will no longer
515 // be transmitted since the Transport object will then be invalid.
516 // RTCP is enabled by default.
517 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200518
519 if (media_transport_) {
520 media_transport_->SetReceiveAudioSink(this);
521 }
Niels Möller530ead42018-10-04 14:28:39 +0200522}
523
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100524ChannelReceive::~ChannelReceive() {
Niels Möller530ead42018-10-04 14:28:39 +0200525 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200526
527 if (media_transport_) {
528 media_transport_->SetReceiveAudioSink(nullptr);
529 }
530
Niels Möller530ead42018-10-04 14:28:39 +0200531 StopPlayout();
532
Niels Möller530ead42018-10-04 14:28:39 +0200533 int error = audio_coding_->RegisterTransportCallback(NULL);
534 RTC_DCHECK_EQ(0, error);
535
Niels Möller530ead42018-10-04 14:28:39 +0200536 if (_moduleProcessThreadPtr)
537 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200538}
539
540void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Niels Möller349ade32018-11-16 09:50:42 +0100541 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200542 rtc::CritScope cs(&_callbackCritSect);
543 audio_sink_ = sink;
544}
545
Niels Möller80c67622018-11-12 13:22:47 +0100546void ChannelReceive::StartPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100547 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100548 rtc::CritScope lock(&playing_lock_);
549 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200550}
551
Niels Möller80c67622018-11-12 13:22:47 +0100552void ChannelReceive::StopPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100553 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100554 rtc::CritScope lock(&playing_lock_);
555 playing_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200556 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200557}
558
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100559absl::optional<std::pair<int, SdpAudioFormat>>
560 ChannelReceive::GetReceiveCodec() const {
Niels Möller349ade32018-11-16 09:50:42 +0100561 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100562 return audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200563}
564
565std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Niels Möller349ade32018-11-16 09:50:42 +0100566 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200567 int64_t now_ms = rtc::TimeMillis();
568 std::vector<RtpSource> sources;
569 {
570 rtc::CritScope cs(&rtp_sources_lock_);
571 sources = contributing_sources_.GetSources(now_ms);
572 if (last_received_rtp_system_time_ms_ >=
573 now_ms - ContributingSources::kHistoryMs) {
574 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
575 RtpSourceType::SSRC);
576 sources.back().set_audio_level(last_received_rtp_audio_level_);
577 }
578 }
579 return sources;
580}
581
582void ChannelReceive::SetReceiveCodecs(
583 const std::map<int, SdpAudioFormat>& codecs) {
Niels Möller349ade32018-11-16 09:50:42 +0100584 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200585 for (const auto& kv : codecs) {
586 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
587 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
588 }
589 audio_coding_->SetReceiveCodecs(codecs);
590}
591
Niels Möller349ade32018-11-16 09:50:42 +0100592// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200593void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
594 int64_t now_ms = rtc::TimeMillis();
595 uint8_t audio_level;
596 bool voice_activity;
597 bool has_audio_level =
598 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
599
600 {
601 rtc::CritScope cs(&rtp_sources_lock_);
602 last_received_rtp_timestamp_ = packet.Timestamp();
603 last_received_rtp_system_time_ms_ = now_ms;
604 if (has_audio_level)
605 last_received_rtp_audio_level_ = audio_level;
606 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100607 contributing_sources_.Update(
608 now_ms, csrcs,
609 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200610 }
611
612 // Store playout timestamp for the received RTP packet
613 UpdatePlayoutTimestamp(false);
614
615 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
616 if (it == payload_type_frequencies_.end())
617 return;
618 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
619 RtpPacketReceived packet_copy(packet);
620 packet_copy.set_payload_type_frequency(it->second);
621
622 rtp_receive_statistics_->OnRtpPacket(packet_copy);
623
624 RTPHeader header;
625 packet_copy.GetHeader(&header);
626
627 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
628}
629
630bool ChannelReceive::ReceivePacket(const uint8_t* packet,
631 size_t packet_length,
632 const RTPHeader& header) {
633 const uint8_t* payload = packet + header.headerLength;
634 assert(packet_length >= header.headerLength);
635 size_t payload_length = packet_length - header.headerLength;
636 WebRtcRTPHeader webrtc_rtp_header = {};
637 webrtc_rtp_header.header = header;
638
Benjamin Wright84583f62018-10-04 14:22:34 -0700639 size_t payload_data_length = payload_length - header.paddingLength;
640
641 // E2EE Custom Audio Frame Decryption (This is optional).
642 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
643 rtc::Buffer decrypted_audio_payload;
644 if (frame_decryptor_ != nullptr) {
645 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
646 cricket::MEDIA_TYPE_AUDIO, payload_length);
647 decrypted_audio_payload.SetSize(max_plaintext_size);
648
649 size_t bytes_written = 0;
650 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
651 header.arrOfCSRCs + header.numCSRCs);
652 int decrypt_status = frame_decryptor_->Decrypt(
653 cricket::MEDIA_TYPE_AUDIO, csrcs,
654 /*additional_data=*/nullptr,
655 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
656 decrypted_audio_payload, &bytes_written);
657
658 // In this case just interpret the failure as a silent frame.
659 if (decrypt_status != 0) {
660 bytes_written = 0;
661 }
662
663 // Resize the decrypted audio payload to the number of bytes actually
664 // written.
665 decrypted_audio_payload.SetSize(bytes_written);
666 // Update the final payload.
667 payload = decrypted_audio_payload.data();
668 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700669 } else if (crypto_options_.sframe.require_frame_encryption) {
670 RTC_DLOG(LS_ERROR)
671 << "FrameDecryptor required but not set, dropping packet";
672 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700673 }
674
Niels Möller530ead42018-10-04 14:28:39 +0200675 if (payload_data_length == 0) {
676 webrtc_rtp_header.frameType = kEmptyFrame;
677 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
678 }
679 return OnReceivedPayloadData(payload, payload_data_length,
680 &webrtc_rtp_header);
681}
682
Niels Möller349ade32018-11-16 09:50:42 +0100683// May be called on either worker thread or network thread.
Niels Möller80c67622018-11-12 13:22:47 +0100684// TODO(nisse): Drop always-true return value.
685bool ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200686 // Store playout timestamp for the received RTCP packet
687 UpdatePlayoutTimestamp(true);
688
689 // Deliver RTCP packet to RTP/RTCP module for parsing
690 _rtpRtcpModule->IncomingRtcpPacket(data, length);
691
692 int64_t rtt = GetRTT();
693 if (rtt == 0) {
694 // Waiting for valid RTT.
Niels Möller80c67622018-11-12 13:22:47 +0100695 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200696 }
697
Niels Möller530ead42018-10-04 14:28:39 +0200698 uint32_t ntp_secs = 0;
699 uint32_t ntp_frac = 0;
700 uint32_t rtp_timestamp = 0;
701 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
702 &rtp_timestamp)) {
703 // Waiting for RTCP.
Niels Möller80c67622018-11-12 13:22:47 +0100704 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200705 }
706
707 {
708 rtc::CritScope lock(&ts_stats_lock_);
709 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
710 }
Niels Möller80c67622018-11-12 13:22:47 +0100711 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200712}
713
714int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Niels Möller349ade32018-11-16 09:50:42 +0100715 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200716 return _outputAudioLevel.LevelFullRange();
717}
718
719double ChannelReceive::GetTotalOutputEnergy() const {
Niels Möller349ade32018-11-16 09:50:42 +0100720 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200721 return _outputAudioLevel.TotalEnergy();
722}
723
724double ChannelReceive::GetTotalOutputDuration() const {
Niels Möller349ade32018-11-16 09:50:42 +0100725 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200726 return _outputAudioLevel.TotalDuration();
727}
728
729void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Niels Möller349ade32018-11-16 09:50:42 +0100730 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200731 rtc::CritScope cs(&volume_settings_critsect_);
732 _outputGain = scaling;
733}
734
Niels Möller349ade32018-11-16 09:50:42 +0100735void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
736 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200737 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200738}
739
Niels Möller530ead42018-10-04 14:28:39 +0200740void ChannelReceive::RegisterReceiverCongestionControlObjects(
741 PacketRouter* packet_router) {
Niels Möller349ade32018-11-16 09:50:42 +0100742 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200743 RTC_DCHECK(packet_router);
744 RTC_DCHECK(!packet_router_);
745 constexpr bool remb_candidate = false;
746 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
747 packet_router_ = packet_router;
748}
749
750void ChannelReceive::ResetReceiverCongestionControlObjects() {
Niels Möller349ade32018-11-16 09:50:42 +0100751 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200752 RTC_DCHECK(packet_router_);
753 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
754 packet_router_ = nullptr;
755}
756
Niels Möller349ade32018-11-16 09:50:42 +0100757CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
758 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200759 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100760 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200761
762 // The jitter statistics is updated for each received RTP packet and is
763 // based on received packets.
764 RtcpStatistics statistics;
765 StreamStatistician* statistician =
766 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
767 if (statistician) {
768 statistician->GetStatistics(&statistics,
769 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
770 }
771
772 stats.fractionLost = statistics.fraction_lost;
773 stats.cumulativeLost = statistics.packets_lost;
774 stats.extendedMax = statistics.extended_highest_sequence_number;
775 stats.jitterSamples = statistics.jitter;
776
777 // --- RTT
778 stats.rttMs = GetRTT();
779
780 // --- Data counters
781
782 size_t bytesReceived(0);
783 uint32_t packetsReceived(0);
784
785 if (statistician) {
786 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
787 }
788
789 stats.bytesReceived = bytesReceived;
790 stats.packetsReceived = packetsReceived;
791
792 // --- Timestamps
793 {
794 rtc::CritScope lock(&ts_stats_lock_);
795 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
796 }
Niels Möller80c67622018-11-12 13:22:47 +0100797 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200798}
799
Niels Möller349ade32018-11-16 09:50:42 +0100800void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
801 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200802 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100803 if (enable) {
804 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100805 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100806 } else {
807 rtp_receive_statistics_->SetMaxReorderingThreshold(
808 kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200809 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100810 }
Niels Möller530ead42018-10-04 14:28:39 +0200811}
812
813// Called when we are missing one or more packets.
814int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
815 int length) {
816 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
817}
818
Niels Möllerdced9f62018-11-19 10:27:07 +0100819void ChannelReceive::SetAssociatedSendChannel(
820 const ChannelSendInterface* channel) {
Niels Möller349ade32018-11-16 09:50:42 +0100821 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200822 rtc::CritScope lock(&assoc_send_channel_lock_);
823 associated_send_channel_ = channel;
824}
825
Niels Möller80c67622018-11-12 13:22:47 +0100826NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100827 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100828 NetworkStatistics stats;
829 int error = audio_coding_->GetNetworkStatistics(&stats);
830 RTC_DCHECK_EQ(0, error);
831 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200832}
833
Niels Möller80c67622018-11-12 13:22:47 +0100834AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100835 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100836 AudioDecodingCallStats stats;
837 audio_coding_->GetDecodingCallStatistics(&stats);
838 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200839}
840
841uint32_t ChannelReceive::GetDelayEstimate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100842 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() ||
843 module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200844 rtc::CritScope lock(&video_sync_lock_);
845 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
846}
847
Niels Möller349ade32018-11-16 09:50:42 +0100848void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
849 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
850 // Limit to range accepted by both VoE and ACM, so we're at least getting as
851 // close as possible, instead of failing.
852 delay_ms = rtc::SafeClamp(delay_ms, 0, 10000);
853 if ((delay_ms < kVoiceEngineMinMinPlayoutDelayMs) ||
854 (delay_ms > kVoiceEngineMaxMinPlayoutDelayMs)) {
Niels Möller530ead42018-10-04 14:28:39 +0200855 RTC_DLOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
Niels Möller80c67622018-11-12 13:22:47 +0100856 return;
Niels Möller530ead42018-10-04 14:28:39 +0200857 }
Niels Möller349ade32018-11-16 09:50:42 +0100858 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200859 RTC_DLOG(LS_ERROR)
860 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200861 }
Niels Möller530ead42018-10-04 14:28:39 +0200862}
863
Niels Möller349ade32018-11-16 09:50:42 +0100864uint32_t ChannelReceive::GetPlayoutTimestamp() const {
865 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200866 {
867 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100868 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200869 }
Niels Möller530ead42018-10-04 14:28:39 +0200870}
871
872absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Niels Möller349ade32018-11-16 09:50:42 +0100873 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200874 Syncable::Info info;
875 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
876 &info.capture_time_ntp_frac, nullptr, nullptr,
877 &info.capture_time_source_clock) != 0) {
878 return absl::nullopt;
879 }
880 {
881 rtc::CritScope cs(&rtp_sources_lock_);
882 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
883 return absl::nullopt;
884 }
885 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
886 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
887 }
888 return info;
889}
890
891void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
892 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
893
894 if (!jitter_buffer_playout_timestamp_) {
895 // This can happen if this channel has not received any RTP packets. In
896 // this case, NetEq is not capable of computing a playout timestamp.
897 return;
898 }
899
900 uint16_t delay_ms = 0;
901 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
902 RTC_DLOG(LS_WARNING)
903 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
904 << " playout delay from the ADM";
905 return;
906 }
907
908 RTC_DCHECK(jitter_buffer_playout_timestamp_);
909 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
910
911 // Remove the playout delay.
912 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
913
914 {
915 rtc::CritScope lock(&video_sync_lock_);
916 if (!rtcp) {
917 playout_timestamp_rtp_ = playout_timestamp;
918 }
919 playout_delay_ms_ = delay_ms;
920 }
921}
922
923int ChannelReceive::GetRtpTimestampRateHz() const {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100924 const auto decoder = audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200925 // Default to the playout frequency if we've not gotten any packets yet.
926 // TODO(ossu): Zero clockrate can only happen if we've added an external
927 // decoder for a format we don't support internally. Remove once that way of
928 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100929 return (decoder && decoder->second.clockrate_hz != 0)
930 ? decoder->second.clockrate_hz
Niels Möller530ead42018-10-04 14:28:39 +0200931 : audio_coding_->PlayoutFrequency();
932}
933
934int64_t ChannelReceive::GetRTT() const {
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800935 if (media_transport_) {
936 auto target_rate = media_transport_->GetLatestTargetTransferRate();
937 if (target_rate.has_value()) {
938 return target_rate->network_estimate.round_trip_time.ms();
939 }
940
941 return 0;
942 }
Niels Möller530ead42018-10-04 14:28:39 +0200943 RtcpMode method = _rtpRtcpModule->RTCP();
944 if (method == RtcpMode::kOff) {
945 return 0;
946 }
947 std::vector<RTCPReportBlock> report_blocks;
948 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
949
950 // TODO(nisse): Could we check the return value from the ->RTT() call below,
951 // instead of checking if we have any report blocks?
952 if (report_blocks.empty()) {
953 rtc::CritScope lock(&assoc_send_channel_lock_);
954 // Tries to get RTT from an associated channel.
955 if (!associated_send_channel_) {
956 return 0;
957 }
958 return associated_send_channel_->GetRTT();
959 }
960
961 int64_t rtt = 0;
962 int64_t avg_rtt = 0;
963 int64_t max_rtt = 0;
964 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100965 // TODO(nisse): This method computes RTT based on sender reports, even though
966 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200967 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
968 0) {
969 return 0;
970 }
971 return rtt;
972}
973
Niels Möller349ade32018-11-16 09:50:42 +0100974} // namespace
975
976std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
977 ProcessThread* module_process_thread,
978 AudioDeviceModule* audio_device_module,
979 MediaTransportInterface* media_transport,
980 Transport* rtcp_send_transport,
981 RtcEventLog* rtc_event_log,
982 uint32_t remote_ssrc,
983 size_t jitter_buffer_max_packets,
984 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100985 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100986 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100987 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
988 absl::optional<AudioCodecPairId> codec_pair_id,
989 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
990 const webrtc::CryptoOptions& crypto_options) {
991 return absl::make_unique<ChannelReceive>(
992 module_process_thread, audio_device_module, media_transport,
993 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100994 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100995 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
996 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100997}
998
Niels Möller530ead42018-10-04 14:28:39 +0200999} // namespace voe
1000} // namespace webrtc