blob: 9c100fba75661cdbab0ec922d9820bcd937234ec [file] [log] [blame]
Niels Möller530ead42018-10-04 14:28:39 +02001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "audio/channel_receive.h"
12
13#include <algorithm>
14#include <map>
15#include <memory>
16#include <string>
17#include <utility>
18#include <vector>
19
20#include "absl/memory/memory.h"
Niels Möller349ade32018-11-16 09:50:42 +010021#include "audio/audio_level.h"
Niels Möller530ead42018-10-04 14:28:39 +020022#include "audio/channel_send.h"
23#include "audio/utility/audio_frame_operations.h"
24#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
25#include "logging/rtc_event_log/rtc_event_log.h"
26#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
Niels Möller349ade32018-11-16 09:50:42 +010027#include "modules/audio_coding/include/audio_coding_module.h"
Niels Möller530ead42018-10-04 14:28:39 +020028#include "modules/audio_device/include/audio_device.h"
29#include "modules/pacing/packet_router.h"
30#include "modules/rtp_rtcp/include/receive_statistics.h"
Niels Möller349ade32018-11-16 09:50:42 +010031#include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
32#include "modules/rtp_rtcp/include/rtp_rtcp.h"
33#include "modules/rtp_rtcp/source/contributing_sources.h"
Yves Gerey988cc082018-10-23 12:03:01 +020034#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020035#include "modules/rtp_rtcp/source/rtp_packet_received.h"
36#include "modules/utility/include/process_thread.h"
37#include "rtc_base/checks.h"
38#include "rtc_base/criticalsection.h"
39#include "rtc_base/format_macros.h"
40#include "rtc_base/location.h"
41#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010042#include "rtc_base/numerics/safe_minmax.h"
43#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020044#include "rtc_base/thread_checker.h"
45#include "rtc_base/timeutils.h"
46#include "system_wrappers/include/metrics.h"
47
Niels Möller349ade32018-11-16 09:50:42 +010048// TODO(solenberg, nisse): This file contains a few NOLINT marks, to silence
49// warnings about non-const reference arguments.
50// These need cleanup, in a separate cl.
51
Niels Möller530ead42018-10-04 14:28:39 +020052namespace webrtc {
53namespace voe {
54
55namespace {
56
57constexpr double kAudioSampleDurationSeconds = 0.01;
58constexpr int64_t kMaxRetransmissionWindowMs = 1000;
59constexpr int64_t kMinRetransmissionWindowMs = 30;
60
61// Video Sync.
62constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
63constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
64
Niels Möller7d76a312018-10-26 12:57:07 +020065webrtc::FrameType WebrtcFrameTypeForMediaTransportFrameType(
66 MediaTransportEncodedAudioFrame::FrameType frame_type) {
67 switch (frame_type) {
68 case MediaTransportEncodedAudioFrame::FrameType::kSpeech:
69 return kAudioFrameSpeech;
70 break;
71
72 case MediaTransportEncodedAudioFrame::FrameType::
73 kDiscountinuousTransmission:
74 return kAudioFrameCN;
75 break;
76 }
77}
78
79WebRtcRTPHeader CreateWebrtcRTPHeaderForMediaTransportFrame(
80 const MediaTransportEncodedAudioFrame& frame,
81 uint64_t channel_id) {
82 webrtc::WebRtcRTPHeader webrtc_header = {};
83 webrtc_header.header.payloadType = frame.payload_type();
84 webrtc_header.header.payload_type_frequency = frame.sampling_rate_hz();
85 webrtc_header.header.timestamp = frame.starting_sample_index();
86 webrtc_header.header.sequenceNumber = frame.sequence_number();
87
88 webrtc_header.frameType =
89 WebrtcFrameTypeForMediaTransportFrameType(frame.frame_type());
90
91 webrtc_header.header.ssrc = static_cast<uint32_t>(channel_id);
92
93 // The rest are initialized by the RTPHeader constructor.
94 return webrtc_header;
95}
96
Niels Möller349ade32018-11-16 09:50:42 +010097// Helper class to simplify locking scheme for members that are accessed from
98// multiple threads.
99// Example: a member can be set on thread T1 and read by an internal audio
100// thread T2. Accessing the member via this class ensures that we are
101// safe and also avoid TSan v2 warnings.
102class ChannelReceiveState {
103 public:
104 struct State {
105 bool playing = false;
106 };
107
108 ChannelReceiveState() {}
109 virtual ~ChannelReceiveState() {}
110
111 void Reset() {
112 rtc::CritScope lock(&lock_);
113 state_ = State();
114 }
115
116 State Get() const {
117 rtc::CritScope lock(&lock_);
118 return state_;
119 }
120
121 void SetPlaying(bool enable) {
122 rtc::CritScope lock(&lock_);
123 state_.playing = enable;
124 }
125
126 private:
127 rtc::CriticalSection lock_;
128 State state_;
129};
130
131class ChannelReceive : public ChannelReceiveInterface,
132 public MediaTransportAudioSinkInterface {
133 public:
134 // Used for receive streams.
135 ChannelReceive(ProcessThread* module_process_thread,
136 AudioDeviceModule* audio_device_module,
137 MediaTransportInterface* media_transport,
138 Transport* rtcp_send_transport,
139 RtcEventLog* rtc_event_log,
140 uint32_t remote_ssrc,
141 size_t jitter_buffer_max_packets,
142 bool jitter_buffer_fast_playout,
143 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
144 absl::optional<AudioCodecPairId> codec_pair_id,
145 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
146 const webrtc::CryptoOptions& crypto_options);
147 ~ChannelReceive() override;
148
149 void SetSink(AudioSinkInterface* sink) override;
150
151 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
152
153 // API methods
154
155 void StartPlayout() override;
156 void StopPlayout() override;
157
158 // Codecs
159 bool GetRecCodec(CodecInst* codec) const override;
160
161 bool ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
162
163 // RtpPacketSinkInterface.
164 void OnRtpPacket(const RtpPacketReceived& packet) override;
165
166 // Muting, Volume and Level.
167 void SetChannelOutputVolumeScaling(float scaling) override;
168 int GetSpeechOutputLevelFullRange() const override;
169 // See description of "totalAudioEnergy" in the WebRTC stats spec:
170 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
171 double GetTotalOutputEnergy() const override;
172 double GetTotalOutputDuration() const override;
173
174 // Stats.
175 NetworkStatistics GetNetworkStatistics() const override;
176 AudioDecodingCallStats GetDecodingCallStatistics() const override;
177
178 // Audio+Video Sync.
179 uint32_t GetDelayEstimate() const override;
180 void SetMinimumPlayoutDelay(int delayMs) override;
181 uint32_t GetPlayoutTimestamp() const override;
182
183 // Produces the transport-related timestamps; current_delay_ms is left unset.
184 absl::optional<Syncable::Info> GetSyncInfo() const override;
185
186 // RTP+RTCP
187 void SetLocalSSRC(unsigned int ssrc) override;
188
189 void RegisterReceiverCongestionControlObjects(
190 PacketRouter* packet_router) override;
191 void ResetReceiverCongestionControlObjects() override;
192
193 CallReceiveStatistics GetRTCPStatistics() const override;
194 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
195
196 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
197 int sample_rate_hz,
198 AudioFrame* audio_frame) override;
199
200 int PreferredSampleRate() const override;
201
202 // Associate to a send channel.
203 // Used for obtaining RTT for a receive-only channel.
204 void SetAssociatedSendChannel(const ChannelSend* channel) override;
205
206 std::vector<RtpSource> GetSources() const override;
207
208 private:
209 void Init();
210 void Terminate();
211
212 int GetRemoteSSRC(unsigned int& ssrc); // NOLINT
213
214 bool ReceivePacket(const uint8_t* packet,
215 size_t packet_length,
216 const RTPHeader& header);
217 int ResendPackets(const uint16_t* sequence_numbers, int length);
218 void UpdatePlayoutTimestamp(bool rtcp);
219
220 int GetRtpTimestampRateHz() const;
221 int64_t GetRTT() const;
222
223 // MediaTransportAudioSinkInterface override;
224 void OnData(uint64_t channel_id,
225 MediaTransportEncodedAudioFrame frame) override;
226
227 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
228 size_t payloadSize,
229 const WebRtcRTPHeader* rtpHeader);
230
231 // Thread checkers document and lock usage of some methods to specific threads
232 // we know about. The goal is to eventually split up voe::ChannelReceive into
233 // parts with single-threaded semantics, and thereby reduce the need for
234 // locks.
235 rtc::ThreadChecker worker_thread_checker_;
236 rtc::ThreadChecker module_process_thread_checker_;
237 // Methods accessed from audio and video threads are checked for sequential-
238 // only access. We don't necessarily own and control these threads, so thread
239 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
240 // audio thread to another, but access is still sequential.
241 rtc::RaceChecker audio_thread_race_checker_;
242 rtc::RaceChecker video_capture_thread_race_checker_;
243 rtc::CriticalSection _callbackCritSect;
244 rtc::CriticalSection volume_settings_critsect_;
245
246 ChannelReceiveState channel_state_;
247
248 RtcEventLog* const event_log_;
249
250 // Indexed by payload type.
251 std::map<uint8_t, int> payload_type_frequencies_;
252
253 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
254 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
255 const uint32_t remote_ssrc_;
256
257 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
258 // queried on the worker thread.
259 rtc::CriticalSection rtp_sources_lock_;
260 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
261 absl::optional<uint32_t> last_received_rtp_timestamp_
262 RTC_GUARDED_BY(&rtp_sources_lock_);
263 absl::optional<int64_t> last_received_rtp_system_time_ms_
264 RTC_GUARDED_BY(&rtp_sources_lock_);
265 absl::optional<uint8_t> last_received_rtp_audio_level_
266 RTC_GUARDED_BY(&rtp_sources_lock_);
267
268 std::unique_ptr<AudioCodingModule> audio_coding_;
269 AudioSinkInterface* audio_sink_ = nullptr;
270 AudioLevel _outputAudioLevel;
271
272 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
273
274 // Timestamp of the audio pulled from NetEq.
275 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
276
277 rtc::CriticalSection video_sync_lock_;
278 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
279 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
280
281 rtc::CriticalSection ts_stats_lock_;
282
283 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
284 // The rtp timestamp of the first played out audio frame.
285 int64_t capture_start_rtp_time_stamp_;
286 // The capture ntp time (in local timebase) of the first played out audio
287 // frame.
288 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
289
290 // uses
291 ProcessThread* _moduleProcessThreadPtr;
292 AudioDeviceModule* _audioDeviceModulePtr;
293 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
294
295 // An associated send channel.
296 rtc::CriticalSection assoc_send_channel_lock_;
297 const ChannelSend* associated_send_channel_
298 RTC_GUARDED_BY(assoc_send_channel_lock_);
299
300 PacketRouter* packet_router_ = nullptr;
301
302 rtc::ThreadChecker construction_thread_;
303
304 MediaTransportInterface* const media_transport_;
305
306 // E2EE Audio Frame Decryption
307 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
308 webrtc::CryptoOptions crypto_options_;
309};
Niels Möller530ead42018-10-04 14:28:39 +0200310
Niels Möller530ead42018-10-04 14:28:39 +0200311int32_t ChannelReceive::OnReceivedPayloadData(
312 const uint8_t* payloadData,
313 size_t payloadSize,
314 const WebRtcRTPHeader* rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200315 // We should not be receiving any RTP packets if media_transport is set.
316 RTC_CHECK(!media_transport_);
317
Niels Möller530ead42018-10-04 14:28:39 +0200318 if (!channel_state_.Get().playing) {
319 // Avoid inserting into NetEQ when we are not playing. Count the
320 // packet as discarded.
321 return 0;
322 }
323
324 // Push the incoming payload (parsed and ready for decoding) into the ACM
325 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
326 0) {
327 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
328 "push data to the ACM";
329 return -1;
330 }
331
332 int64_t round_trip_time = 0;
333 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
334
335 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
336 if (!nack_list.empty()) {
337 // Can't use nack_list.data() since it's not supported by all
338 // compilers.
339 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
340 }
341 return 0;
342}
343
Niels Möller7d76a312018-10-26 12:57:07 +0200344// MediaTransportAudioSinkInterface override.
345void ChannelReceive::OnData(uint64_t channel_id,
346 MediaTransportEncodedAudioFrame frame) {
347 RTC_CHECK(media_transport_);
348
349 if (!channel_state_.Get().playing) {
350 // Avoid inserting into NetEQ when we are not playing. Count the
351 // packet as discarded.
352 return;
353 }
354
355 // Send encoded audio frame to Decoder / NetEq.
356 if (audio_coding_->IncomingPacket(
357 frame.encoded_data().data(), frame.encoded_data().size(),
358 CreateWebrtcRTPHeaderForMediaTransportFrame(frame, channel_id)) !=
359 0) {
360 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
361 "push data to the ACM";
362 }
363}
364
Niels Möller530ead42018-10-04 14:28:39 +0200365AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
366 int sample_rate_hz,
367 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100368 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200369 audio_frame->sample_rate_hz_ = sample_rate_hz;
370
371 unsigned int ssrc;
372 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
373 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(ssrc));
374 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
375 bool muted;
376 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
377 &muted) == -1) {
378 RTC_DLOG(LS_ERROR)
379 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
380 // In all likelihood, the audio in this frame is garbage. We return an
381 // error so that the audio mixer module doesn't add it to the mix. As
382 // a result, it won't be played out and the actions skipped here are
383 // irrelevant.
384 return AudioMixer::Source::AudioFrameInfo::kError;
385 }
386
387 if (muted) {
388 // TODO(henrik.lundin): We should be able to do better than this. But we
389 // will have to go through all the cases below where the audio samples may
390 // be used, and handle the muted case in some way.
391 AudioFrameOperations::Mute(audio_frame);
392 }
393
394 {
395 // Pass the audio buffers to an optional sink callback, before applying
396 // scaling/panning, as that applies to the mix operation.
397 // External recipients of the audio (e.g. via AudioTrack), will do their
398 // own mixing/dynamic processing.
399 rtc::CritScope cs(&_callbackCritSect);
400 if (audio_sink_) {
401 AudioSinkInterface::Data data(
402 audio_frame->data(), audio_frame->samples_per_channel_,
403 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
404 audio_frame->timestamp_);
405 audio_sink_->OnData(data);
406 }
407 }
408
409 float output_gain = 1.0f;
410 {
411 rtc::CritScope cs(&volume_settings_critsect_);
412 output_gain = _outputGain;
413 }
414
415 // Output volume scaling
416 if (output_gain < 0.99f || output_gain > 1.01f) {
417 // TODO(solenberg): Combine with mute state - this can cause clicks!
418 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
419 }
420
421 // Measure audio level (0-9)
422 // TODO(henrik.lundin) Use the |muted| information here too.
423 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
424 // https://crbug.com/webrtc/7517).
425 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
426
427 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
428 // The first frame with a valid rtp timestamp.
429 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
430 }
431
432 if (capture_start_rtp_time_stamp_ >= 0) {
433 // audio_frame.timestamp_ should be valid from now on.
434
435 // Compute elapsed time.
436 int64_t unwrap_timestamp =
437 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
438 audio_frame->elapsed_time_ms_ =
439 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
440 (GetRtpTimestampRateHz() / 1000);
441
442 {
443 rtc::CritScope lock(&ts_stats_lock_);
444 // Compute ntp time.
445 audio_frame->ntp_time_ms_ =
446 ntp_estimator_.Estimate(audio_frame->timestamp_);
447 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
448 if (audio_frame->ntp_time_ms_ > 0) {
449 // Compute |capture_start_ntp_time_ms_| so that
450 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
451 capture_start_ntp_time_ms_ =
452 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
453 }
454 }
455 }
456
457 {
458 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
459 audio_coding_->TargetDelayMs());
460 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
461 rtc::CritScope lock(&video_sync_lock_);
462 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
463 jitter_buffer_delay + playout_delay_ms_);
464 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
465 jitter_buffer_delay);
466 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
467 playout_delay_ms_);
468 }
469
470 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
471 : AudioMixer::Source::AudioFrameInfo::kNormal;
472}
473
474int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100475 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200476 // Return the bigger of playout and receive frequency in the ACM.
477 return std::max(audio_coding_->ReceiveFrequency(),
478 audio_coding_->PlayoutFrequency());
479}
480
481ChannelReceive::ChannelReceive(
482 ProcessThread* module_process_thread,
483 AudioDeviceModule* audio_device_module,
Niels Möller7d76a312018-10-26 12:57:07 +0200484 MediaTransportInterface* media_transport,
Niels Möllerae4237e2018-10-05 11:28:38 +0200485 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200486 RtcEventLog* rtc_event_log,
487 uint32_t remote_ssrc,
488 size_t jitter_buffer_max_packets,
489 bool jitter_buffer_fast_playout,
490 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700491 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700492 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700493 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200494 : event_log_(rtc_event_log),
495 rtp_receive_statistics_(
496 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
497 remote_ssrc_(remote_ssrc),
498 _outputAudioLevel(),
499 ntp_estimator_(Clock::GetRealTimeClock()),
500 playout_timestamp_rtp_(0),
501 playout_delay_ms_(0),
502 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
503 capture_start_rtp_time_stamp_(-1),
504 capture_start_ntp_time_ms_(-1),
505 _moduleProcessThreadPtr(module_process_thread),
506 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200507 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700508 associated_send_channel_(nullptr),
Niels Möller7d76a312018-10-26 12:57:07 +0200509 media_transport_(media_transport),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700510 frame_decryptor_(frame_decryptor),
511 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100512 // TODO(nisse): Use _moduleProcessThreadPtr instead?
513 module_process_thread_checker_.DetachFromThread();
514
Niels Möller530ead42018-10-04 14:28:39 +0200515 RTC_DCHECK(module_process_thread);
516 RTC_DCHECK(audio_device_module);
517 AudioCodingModule::Config acm_config;
518 acm_config.decoder_factory = decoder_factory;
519 acm_config.neteq_config.codec_pair_id = codec_pair_id;
520 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
521 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
522 acm_config.neteq_config.enable_muted_state = true;
523 audio_coding_.reset(AudioCodingModule::Create(acm_config));
524
525 _outputAudioLevel.Clear();
526
527 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
528 RtpRtcp::Configuration configuration;
529 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100530 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200531 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200532 configuration.receive_statistics = rtp_receive_statistics_.get();
533
534 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200535
536 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
537 _rtpRtcpModule->SetSendingMediaStatus(false);
538 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
539 Init();
540}
541
542ChannelReceive::~ChannelReceive() {
543 Terminate();
544 RTC_DCHECK(!channel_state_.Get().playing);
545}
546
547void ChannelReceive::Init() {
548 channel_state_.Reset();
549
550 // --- Add modules to process thread (for periodic schedulation)
551 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
552
553 // --- ACM initialization
554 int error = audio_coding_->InitializeReceiver();
555 RTC_DCHECK_EQ(0, error);
556
557 // --- RTP/RTCP module initialization
558
559 // Ensure that RTCP is enabled by default for the created channel.
560 // Note that, the module will keep generating RTCP until it is explicitly
561 // disabled by the user.
562 // After StopListen (when no sockets exists), RTCP packets will no longer
563 // be transmitted since the Transport object will then be invalid.
564 // RTCP is enabled by default.
565 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200566
567 if (media_transport_) {
568 media_transport_->SetReceiveAudioSink(this);
569 }
Niels Möller530ead42018-10-04 14:28:39 +0200570}
571
572void ChannelReceive::Terminate() {
573 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200574
575 if (media_transport_) {
576 media_transport_->SetReceiveAudioSink(nullptr);
577 }
578
Niels Möller530ead42018-10-04 14:28:39 +0200579 // Must be called on the same thread as Init().
580 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
581
582 StopPlayout();
583
584 // The order to safely shutdown modules in a channel is:
585 // 1. De-register callbacks in modules
586 // 2. De-register modules in process thread
587 // 3. Destroy modules
588 int error = audio_coding_->RegisterTransportCallback(NULL);
589 RTC_DCHECK_EQ(0, error);
590
591 // De-register modules in process thread
592 if (_moduleProcessThreadPtr)
593 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
594
595 // End of modules shutdown
596}
597
598void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Niels Möller349ade32018-11-16 09:50:42 +0100599 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200600 rtc::CritScope cs(&_callbackCritSect);
601 audio_sink_ = sink;
602}
603
Niels Möller80c67622018-11-12 13:22:47 +0100604void ChannelReceive::StartPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100605 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200606 if (channel_state_.Get().playing) {
Niels Möller80c67622018-11-12 13:22:47 +0100607 return;
Niels Möller530ead42018-10-04 14:28:39 +0200608 }
609
610 channel_state_.SetPlaying(true);
Niels Möller530ead42018-10-04 14:28:39 +0200611}
612
Niels Möller80c67622018-11-12 13:22:47 +0100613void ChannelReceive::StopPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100614 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200615 if (!channel_state_.Get().playing) {
Niels Möller80c67622018-11-12 13:22:47 +0100616 return;
Niels Möller530ead42018-10-04 14:28:39 +0200617 }
618
619 channel_state_.SetPlaying(false);
620 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200621}
622
Niels Möller349ade32018-11-16 09:50:42 +0100623bool ChannelReceive::GetRecCodec(CodecInst* codec) const {
624 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100625 return (audio_coding_->ReceiveCodec(codec) == 0);
Niels Möller530ead42018-10-04 14:28:39 +0200626}
627
628std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Niels Möller349ade32018-11-16 09:50:42 +0100629 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200630 int64_t now_ms = rtc::TimeMillis();
631 std::vector<RtpSource> sources;
632 {
633 rtc::CritScope cs(&rtp_sources_lock_);
634 sources = contributing_sources_.GetSources(now_ms);
635 if (last_received_rtp_system_time_ms_ >=
636 now_ms - ContributingSources::kHistoryMs) {
637 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
638 RtpSourceType::SSRC);
639 sources.back().set_audio_level(last_received_rtp_audio_level_);
640 }
641 }
642 return sources;
643}
644
645void ChannelReceive::SetReceiveCodecs(
646 const std::map<int, SdpAudioFormat>& codecs) {
Niels Möller349ade32018-11-16 09:50:42 +0100647 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200648 for (const auto& kv : codecs) {
649 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
650 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
651 }
652 audio_coding_->SetReceiveCodecs(codecs);
653}
654
Niels Möller349ade32018-11-16 09:50:42 +0100655// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200656void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
657 int64_t now_ms = rtc::TimeMillis();
658 uint8_t audio_level;
659 bool voice_activity;
660 bool has_audio_level =
661 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
662
663 {
664 rtc::CritScope cs(&rtp_sources_lock_);
665 last_received_rtp_timestamp_ = packet.Timestamp();
666 last_received_rtp_system_time_ms_ = now_ms;
667 if (has_audio_level)
668 last_received_rtp_audio_level_ = audio_level;
669 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100670 contributing_sources_.Update(
671 now_ms, csrcs,
672 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200673 }
674
675 // Store playout timestamp for the received RTP packet
676 UpdatePlayoutTimestamp(false);
677
678 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
679 if (it == payload_type_frequencies_.end())
680 return;
681 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
682 RtpPacketReceived packet_copy(packet);
683 packet_copy.set_payload_type_frequency(it->second);
684
685 rtp_receive_statistics_->OnRtpPacket(packet_copy);
686
687 RTPHeader header;
688 packet_copy.GetHeader(&header);
689
690 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
691}
692
693bool ChannelReceive::ReceivePacket(const uint8_t* packet,
694 size_t packet_length,
695 const RTPHeader& header) {
696 const uint8_t* payload = packet + header.headerLength;
697 assert(packet_length >= header.headerLength);
698 size_t payload_length = packet_length - header.headerLength;
699 WebRtcRTPHeader webrtc_rtp_header = {};
700 webrtc_rtp_header.header = header;
701
Benjamin Wright84583f62018-10-04 14:22:34 -0700702 size_t payload_data_length = payload_length - header.paddingLength;
703
704 // E2EE Custom Audio Frame Decryption (This is optional).
705 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
706 rtc::Buffer decrypted_audio_payload;
707 if (frame_decryptor_ != nullptr) {
708 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
709 cricket::MEDIA_TYPE_AUDIO, payload_length);
710 decrypted_audio_payload.SetSize(max_plaintext_size);
711
712 size_t bytes_written = 0;
713 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
714 header.arrOfCSRCs + header.numCSRCs);
715 int decrypt_status = frame_decryptor_->Decrypt(
716 cricket::MEDIA_TYPE_AUDIO, csrcs,
717 /*additional_data=*/nullptr,
718 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
719 decrypted_audio_payload, &bytes_written);
720
721 // In this case just interpret the failure as a silent frame.
722 if (decrypt_status != 0) {
723 bytes_written = 0;
724 }
725
726 // Resize the decrypted audio payload to the number of bytes actually
727 // written.
728 decrypted_audio_payload.SetSize(bytes_written);
729 // Update the final payload.
730 payload = decrypted_audio_payload.data();
731 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700732 } else if (crypto_options_.sframe.require_frame_encryption) {
733 RTC_DLOG(LS_ERROR)
734 << "FrameDecryptor required but not set, dropping packet";
735 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700736 }
737
Niels Möller530ead42018-10-04 14:28:39 +0200738 if (payload_data_length == 0) {
739 webrtc_rtp_header.frameType = kEmptyFrame;
740 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
741 }
742 return OnReceivedPayloadData(payload, payload_data_length,
743 &webrtc_rtp_header);
744}
745
Niels Möller349ade32018-11-16 09:50:42 +0100746// May be called on either worker thread or network thread.
Niels Möller80c67622018-11-12 13:22:47 +0100747// TODO(nisse): Drop always-true return value.
748bool ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200749 // Store playout timestamp for the received RTCP packet
750 UpdatePlayoutTimestamp(true);
751
752 // Deliver RTCP packet to RTP/RTCP module for parsing
753 _rtpRtcpModule->IncomingRtcpPacket(data, length);
754
755 int64_t rtt = GetRTT();
756 if (rtt == 0) {
757 // Waiting for valid RTT.
Niels Möller80c67622018-11-12 13:22:47 +0100758 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200759 }
760
761 int64_t nack_window_ms = rtt;
762 if (nack_window_ms < kMinRetransmissionWindowMs) {
763 nack_window_ms = kMinRetransmissionWindowMs;
764 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
765 nack_window_ms = kMaxRetransmissionWindowMs;
766 }
767
768 uint32_t ntp_secs = 0;
769 uint32_t ntp_frac = 0;
770 uint32_t rtp_timestamp = 0;
771 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
772 &rtp_timestamp)) {
773 // Waiting for RTCP.
Niels Möller80c67622018-11-12 13:22:47 +0100774 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200775 }
776
777 {
778 rtc::CritScope lock(&ts_stats_lock_);
779 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
780 }
Niels Möller80c67622018-11-12 13:22:47 +0100781 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200782}
783
784int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Niels Möller349ade32018-11-16 09:50:42 +0100785 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200786 return _outputAudioLevel.LevelFullRange();
787}
788
789double ChannelReceive::GetTotalOutputEnergy() const {
Niels Möller349ade32018-11-16 09:50:42 +0100790 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200791 return _outputAudioLevel.TotalEnergy();
792}
793
794double ChannelReceive::GetTotalOutputDuration() const {
Niels Möller349ade32018-11-16 09:50:42 +0100795 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200796 return _outputAudioLevel.TotalDuration();
797}
798
799void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Niels Möller349ade32018-11-16 09:50:42 +0100800 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200801 rtc::CritScope cs(&volume_settings_critsect_);
802 _outputGain = scaling;
803}
804
Niels Möller349ade32018-11-16 09:50:42 +0100805void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
806 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200807 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200808}
809
810// TODO(nisse): Pass ssrc in return value instead.
811int ChannelReceive::GetRemoteSSRC(unsigned int& ssrc) {
812 ssrc = remote_ssrc_;
813 return 0;
814}
815
816void ChannelReceive::RegisterReceiverCongestionControlObjects(
817 PacketRouter* packet_router) {
Niels Möller349ade32018-11-16 09:50:42 +0100818 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200819 RTC_DCHECK(packet_router);
820 RTC_DCHECK(!packet_router_);
821 constexpr bool remb_candidate = false;
822 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
823 packet_router_ = packet_router;
824}
825
826void ChannelReceive::ResetReceiverCongestionControlObjects() {
Niels Möller349ade32018-11-16 09:50:42 +0100827 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200828 RTC_DCHECK(packet_router_);
829 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
830 packet_router_ = nullptr;
831}
832
Niels Möller349ade32018-11-16 09:50:42 +0100833CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
834 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200835 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100836 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200837
838 // The jitter statistics is updated for each received RTP packet and is
839 // based on received packets.
840 RtcpStatistics statistics;
841 StreamStatistician* statistician =
842 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
843 if (statistician) {
844 statistician->GetStatistics(&statistics,
845 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
846 }
847
848 stats.fractionLost = statistics.fraction_lost;
849 stats.cumulativeLost = statistics.packets_lost;
850 stats.extendedMax = statistics.extended_highest_sequence_number;
851 stats.jitterSamples = statistics.jitter;
852
853 // --- RTT
854 stats.rttMs = GetRTT();
855
856 // --- Data counters
857
858 size_t bytesReceived(0);
859 uint32_t packetsReceived(0);
860
861 if (statistician) {
862 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
863 }
864
865 stats.bytesReceived = bytesReceived;
866 stats.packetsReceived = packetsReceived;
867
868 // --- Timestamps
869 {
870 rtc::CritScope lock(&ts_stats_lock_);
871 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
872 }
Niels Möller80c67622018-11-12 13:22:47 +0100873 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200874}
875
Niels Möller349ade32018-11-16 09:50:42 +0100876void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
877 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200878 // None of these functions can fail.
Niels Möller349ade32018-11-16 09:50:42 +0100879 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller530ead42018-10-04 14:28:39 +0200880 if (enable)
Niels Möller349ade32018-11-16 09:50:42 +0100881 audio_coding_->EnableNack(max_packets);
Niels Möller530ead42018-10-04 14:28:39 +0200882 else
883 audio_coding_->DisableNack();
884}
885
886// Called when we are missing one or more packets.
887int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
888 int length) {
889 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
890}
891
Niels Möller349ade32018-11-16 09:50:42 +0100892void ChannelReceive::SetAssociatedSendChannel(const ChannelSend* channel) {
893 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200894 rtc::CritScope lock(&assoc_send_channel_lock_);
895 associated_send_channel_ = channel;
896}
897
Niels Möller80c67622018-11-12 13:22:47 +0100898NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100899 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100900 NetworkStatistics stats;
901 int error = audio_coding_->GetNetworkStatistics(&stats);
902 RTC_DCHECK_EQ(0, error);
903 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200904}
905
Niels Möller80c67622018-11-12 13:22:47 +0100906AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100907 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100908 AudioDecodingCallStats stats;
909 audio_coding_->GetDecodingCallStatistics(&stats);
910 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200911}
912
913uint32_t ChannelReceive::GetDelayEstimate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100914 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() ||
915 module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200916 rtc::CritScope lock(&video_sync_lock_);
917 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
918}
919
Niels Möller349ade32018-11-16 09:50:42 +0100920void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
921 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
922 // Limit to range accepted by both VoE and ACM, so we're at least getting as
923 // close as possible, instead of failing.
924 delay_ms = rtc::SafeClamp(delay_ms, 0, 10000);
925 if ((delay_ms < kVoiceEngineMinMinPlayoutDelayMs) ||
926 (delay_ms > kVoiceEngineMaxMinPlayoutDelayMs)) {
Niels Möller530ead42018-10-04 14:28:39 +0200927 RTC_DLOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
Niels Möller80c67622018-11-12 13:22:47 +0100928 return;
Niels Möller530ead42018-10-04 14:28:39 +0200929 }
Niels Möller349ade32018-11-16 09:50:42 +0100930 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200931 RTC_DLOG(LS_ERROR)
932 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200933 }
Niels Möller530ead42018-10-04 14:28:39 +0200934}
935
Niels Möller349ade32018-11-16 09:50:42 +0100936uint32_t ChannelReceive::GetPlayoutTimestamp() const {
937 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200938 {
939 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100940 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200941 }
Niels Möller530ead42018-10-04 14:28:39 +0200942}
943
944absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Niels Möller349ade32018-11-16 09:50:42 +0100945 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200946 Syncable::Info info;
947 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
948 &info.capture_time_ntp_frac, nullptr, nullptr,
949 &info.capture_time_source_clock) != 0) {
950 return absl::nullopt;
951 }
952 {
953 rtc::CritScope cs(&rtp_sources_lock_);
954 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
955 return absl::nullopt;
956 }
957 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
958 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
959 }
960 return info;
961}
962
963void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
964 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
965
966 if (!jitter_buffer_playout_timestamp_) {
967 // This can happen if this channel has not received any RTP packets. In
968 // this case, NetEq is not capable of computing a playout timestamp.
969 return;
970 }
971
972 uint16_t delay_ms = 0;
973 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
974 RTC_DLOG(LS_WARNING)
975 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
976 << " playout delay from the ADM";
977 return;
978 }
979
980 RTC_DCHECK(jitter_buffer_playout_timestamp_);
981 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
982
983 // Remove the playout delay.
984 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
985
986 {
987 rtc::CritScope lock(&video_sync_lock_);
988 if (!rtcp) {
989 playout_timestamp_rtp_ = playout_timestamp;
990 }
991 playout_delay_ms_ = delay_ms;
992 }
993}
994
995int ChannelReceive::GetRtpTimestampRateHz() const {
996 const auto format = audio_coding_->ReceiveFormat();
997 // Default to the playout frequency if we've not gotten any packets yet.
998 // TODO(ossu): Zero clockrate can only happen if we've added an external
999 // decoder for a format we don't support internally. Remove once that way of
1000 // adding decoders is gone!
1001 return (format && format->clockrate_hz != 0)
1002 ? format->clockrate_hz
1003 : audio_coding_->PlayoutFrequency();
1004}
1005
1006int64_t ChannelReceive::GetRTT() const {
1007 RtcpMode method = _rtpRtcpModule->RTCP();
1008 if (method == RtcpMode::kOff) {
1009 return 0;
1010 }
1011 std::vector<RTCPReportBlock> report_blocks;
1012 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
1013
1014 // TODO(nisse): Could we check the return value from the ->RTT() call below,
1015 // instead of checking if we have any report blocks?
1016 if (report_blocks.empty()) {
1017 rtc::CritScope lock(&assoc_send_channel_lock_);
1018 // Tries to get RTT from an associated channel.
1019 if (!associated_send_channel_) {
1020 return 0;
1021 }
1022 return associated_send_channel_->GetRTT();
1023 }
1024
1025 int64_t rtt = 0;
1026 int64_t avg_rtt = 0;
1027 int64_t max_rtt = 0;
1028 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +01001029 // TODO(nisse): This method computes RTT based on sender reports, even though
1030 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +02001031 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1032 0) {
1033 return 0;
1034 }
1035 return rtt;
1036}
1037
Niels Möller349ade32018-11-16 09:50:42 +01001038} // namespace
1039
1040std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
1041 ProcessThread* module_process_thread,
1042 AudioDeviceModule* audio_device_module,
1043 MediaTransportInterface* media_transport,
1044 Transport* rtcp_send_transport,
1045 RtcEventLog* rtc_event_log,
1046 uint32_t remote_ssrc,
1047 size_t jitter_buffer_max_packets,
1048 bool jitter_buffer_fast_playout,
1049 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
1050 absl::optional<AudioCodecPairId> codec_pair_id,
1051 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
1052 const webrtc::CryptoOptions& crypto_options) {
1053 return absl::make_unique<ChannelReceive>(
1054 module_process_thread, audio_device_module, media_transport,
1055 rtcp_send_transport, rtc_event_log, remote_ssrc,
1056 jitter_buffer_max_packets, jitter_buffer_fast_playout, decoder_factory,
1057 codec_pair_id, frame_decryptor, crypto_options);
1058}
1059
Niels Möller530ead42018-10-04 14:28:39 +02001060} // namespace voe
1061} // namespace webrtc