blob: 1799e7aae1b2907548201deb49e5825313e1c81f [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
henrika@webrtc.org2919e952012-01-31 08:45:03 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
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
Fredrik Solenberga8b7c7f2018-01-17 11:18:31 +010011#include "audio/channel.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Henrik Lundin64dad832015-05-11 12:44:23 +020013#include <algorithm>
Bjorn Terelius440216f2017-09-29 21:01:42 +020014#include <map>
Elad Alon604c14d2017-10-05 12:47:06 +000015#include <memory>
Bjorn Terelius440216f2017-09-29 21:01:42 +020016#include <string>
Tommif888bb52015-12-12 01:37:01 +010017#include <utility>
Bjorn Terelius440216f2017-09-29 21:01:42 +020018#include <vector>
Henrik Lundin64dad832015-05-11 12:44:23 +020019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/array_view.h"
21#include "audio/utility/audio_frame_operations.h"
22#include "call/rtp_transport_controller_send_interface.h"
23#include "logging/rtc_event_log/rtc_event_log.h"
Elad Alon4a87e1c2017-10-03 16:11:34 +020024#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
Elad Alon4a87e1c2017-10-03 16:11:34 +020025#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_coding/codecs/audio_format_conversion.h"
27#include "modules/audio_device/include/audio_device.h"
28#include "modules/audio_processing/include/audio_processing.h"
29#include "modules/include/module_common_types.h"
30#include "modules/pacing/packet_router.h"
31#include "modules/rtp_rtcp/include/receive_statistics.h"
32#include "modules/rtp_rtcp/include/rtp_payload_registry.h"
33#include "modules/rtp_rtcp/include/rtp_receiver.h"
34#include "modules/rtp_rtcp/source/rtp_packet_received.h"
35#include "modules/rtp_rtcp/source/rtp_receiver_strategy.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"
Elad Alon4a87e1c2017-10-03 16:11:34 +020042#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "rtc_base/rate_limiter.h"
44#include "rtc_base/task_queue.h"
45#include "rtc_base/thread_checker.h"
46#include "rtc_base/timeutils.h"
47#include "system_wrappers/include/field_trial.h"
henrika45802172017-09-28 09:39:34 +020048#include "system_wrappers/include/metrics.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000049
andrew@webrtc.org50419b02012-11-14 19:07:54 +000050namespace webrtc {
51namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000052
kwibergc8d071e2016-04-06 12:22:38 -070053namespace {
54
zsteine76bd3a2017-07-14 12:17:49 -070055constexpr double kAudioSampleDurationSeconds = 0.01;
Erik Språng737336d2016-07-29 12:59:36 +020056constexpr int64_t kMaxRetransmissionWindowMs = 1000;
57constexpr int64_t kMinRetransmissionWindowMs = 30;
58
Fredrik Solenberg55900fd2017-11-23 20:22:55 +010059// Video Sync.
60constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
61constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
62
kwibergc8d071e2016-04-06 12:22:38 -070063} // namespace
64
solenberg8842c3e2016-03-11 03:06:41 -080065const int kTelephoneEventAttenuationdB = 10;
66
ivoc14d5dbe2016-07-04 07:06:55 -070067class RtcEventLogProxy final : public webrtc::RtcEventLog {
68 public:
69 RtcEventLogProxy() : event_log_(nullptr) {}
70
Bjorn Tereliusde939432017-11-20 17:38:14 +010071 bool StartLogging(std::unique_ptr<RtcEventLogOutput> output,
72 int64_t output_period_ms) override {
Elad Alon83ccca12017-10-04 13:18:26 +020073 RTC_NOTREACHED();
74 return false;
75 }
76
ivoc14d5dbe2016-07-04 07:06:55 -070077 void StopLogging() override { RTC_NOTREACHED(); }
78
Elad Alon4a87e1c2017-10-03 16:11:34 +020079 void Log(std::unique_ptr<RtcEvent> event) override {
80 rtc::CritScope lock(&crit_);
81 if (event_log_) {
82 event_log_->Log(std::move(event));
83 }
84 }
85
ivoc14d5dbe2016-07-04 07:06:55 -070086 void SetEventLog(RtcEventLog* event_log) {
87 rtc::CritScope lock(&crit_);
88 event_log_ = event_log;
89 }
90
91 private:
92 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -070093 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -070094 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
95};
96
michaelt9332b7d2016-11-30 07:51:13 -080097class RtcpRttStatsProxy final : public RtcpRttStats {
98 public:
99 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
100
101 void OnRttUpdate(int64_t rtt) override {
102 rtc::CritScope lock(&crit_);
103 if (rtcp_rtt_stats_)
104 rtcp_rtt_stats_->OnRttUpdate(rtt);
105 }
106
107 int64_t LastProcessedRtt() const override {
108 rtc::CritScope lock(&crit_);
109 if (!rtcp_rtt_stats_)
110 return 0;
111 return rtcp_rtt_stats_->LastProcessedRtt();
112 }
113
114 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
115 rtc::CritScope lock(&crit_);
116 rtcp_rtt_stats_ = rtcp_rtt_stats;
117 }
118
119 private:
120 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700121 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800122 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
123};
124
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100125class TransportFeedbackProxy : public TransportFeedbackObserver {
126 public:
127 TransportFeedbackProxy() : feedback_observer_(nullptr) {
128 pacer_thread_.DetachFromThread();
129 network_thread_.DetachFromThread();
130 }
131
132 void SetTransportFeedbackObserver(
133 TransportFeedbackObserver* feedback_observer) {
134 RTC_DCHECK(thread_checker_.CalledOnValidThread());
135 rtc::CritScope lock(&crit_);
136 feedback_observer_ = feedback_observer;
137 }
138
139 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700140 void AddPacket(uint32_t ssrc,
141 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100142 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800143 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100144 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
145 rtc::CritScope lock(&crit_);
146 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700147 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100148 }
philipel8aadd502017-02-23 02:56:13 -0800149
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100150 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
151 RTC_DCHECK(network_thread_.CalledOnValidThread());
152 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700153 if (feedback_observer_)
154 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200155 }
elad.alonf9490002017-03-06 05:32:21 -0800156 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200157 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800158 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100159 }
160
161 private:
162 rtc::CriticalSection crit_;
163 rtc::ThreadChecker thread_checker_;
164 rtc::ThreadChecker pacer_thread_;
165 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700166 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100167};
168
169class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
170 public:
171 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
172 pacer_thread_.DetachFromThread();
173 }
174
175 void SetSequenceNumberAllocator(
176 TransportSequenceNumberAllocator* seq_num_allocator) {
177 RTC_DCHECK(thread_checker_.CalledOnValidThread());
178 rtc::CritScope lock(&crit_);
179 seq_num_allocator_ = seq_num_allocator;
180 }
181
182 // Implements TransportSequenceNumberAllocator.
183 uint16_t AllocateSequenceNumber() override {
184 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
185 rtc::CritScope lock(&crit_);
186 if (!seq_num_allocator_)
187 return 0;
188 return seq_num_allocator_->AllocateSequenceNumber();
189 }
190
191 private:
192 rtc::CriticalSection crit_;
193 rtc::ThreadChecker thread_checker_;
194 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700195 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100196};
197
198class RtpPacketSenderProxy : public RtpPacketSender {
199 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800200 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100201
202 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
203 RTC_DCHECK(thread_checker_.CalledOnValidThread());
204 rtc::CritScope lock(&crit_);
205 rtp_packet_sender_ = rtp_packet_sender;
206 }
207
208 // Implements RtpPacketSender.
209 void InsertPacket(Priority priority,
210 uint32_t ssrc,
211 uint16_t sequence_number,
212 int64_t capture_time_ms,
213 size_t bytes,
214 bool retransmission) override {
215 rtc::CritScope lock(&crit_);
216 if (rtp_packet_sender_) {
217 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
218 capture_time_ms, bytes, retransmission);
219 }
220 }
221
Alex Narest78609d52017-10-20 10:37:47 +0200222 void SetAccountForAudioPackets(bool account_for_audio) override {
223 RTC_NOTREACHED();
224 }
225
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100226 private:
227 rtc::ThreadChecker thread_checker_;
228 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700229 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100230};
231
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000232class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000233 public:
stefan7de8d642017-02-07 07:14:08 -0800234 explicit VoERtcpObserver(Channel* owner)
235 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000236 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000237
stefan7de8d642017-02-07 07:14:08 -0800238 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
239 rtc::CritScope lock(&crit_);
240 bandwidth_observer_ = bandwidth_observer;
241 }
242
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000243 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800244 rtc::CritScope lock(&crit_);
245 if (bandwidth_observer_) {
246 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
247 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000248 }
249
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000250 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
251 int64_t rtt,
252 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800253 {
254 rtc::CritScope lock(&crit_);
255 if (bandwidth_observer_) {
256 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
257 now_ms);
258 }
259 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000260 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
261 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
262 // report for VoiceEngine?
263 if (report_blocks.empty())
264 return;
265
266 int fraction_lost_aggregate = 0;
267 int total_number_of_packets = 0;
268
269 // If receiving multiple report blocks, calculate the weighted average based
270 // on the number of packets a report refers to.
271 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
272 block_it != report_blocks.end(); ++block_it) {
273 // Find the previous extended high sequence number for this remote SSRC,
274 // to calculate the number of RTP packets this report refers to. Ignore if
275 // we haven't seen this SSRC before.
276 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700277 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000278 int number_of_packets = 0;
279 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700280 number_of_packets =
281 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000282 }
srte3e69e5c2017-08-09 06:13:45 -0700283 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000284 total_number_of_packets += number_of_packets;
285
srte3e69e5c2017-08-09 06:13:45 -0700286 extended_max_sequence_number_[block_it->source_ssrc] =
287 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000288 }
289 int weighted_fraction_lost = 0;
290 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800291 weighted_fraction_lost =
292 (fraction_lost_aggregate + total_number_of_packets / 2) /
293 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000294 }
elad.alond12a8e12017-03-23 11:04:48 -0700295 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000296 }
297
298 private:
299 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000300 // Maps remote side ssrc to extended highest sequence number received.
301 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800302 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700303 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000304};
305
henrikaec6fbd22017-03-31 05:43:36 -0700306class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
307 public:
308 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
309 Channel* channel)
310 : audio_frame_(std::move(audio_frame)), channel_(channel) {
311 RTC_DCHECK(channel_);
312 }
313
314 private:
315 bool Run() override {
316 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
317 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
318 return true;
319 }
320
321 std::unique_ptr<AudioFrame> audio_frame_;
322 Channel* const channel_;
323};
324
kwiberg55b97fe2016-01-28 05:22:45 -0800325int32_t Channel::SendData(FrameType frameType,
326 uint8_t payloadType,
327 uint32_t timeStamp,
328 const uint8_t* payloadData,
329 size_t payloadSize,
330 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700331 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800332 if (_includeAudioLevelIndication) {
333 // Store current audio level in the RTP/RTCP module.
334 // The level will be used in combination with voice-activity state
335 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800336 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800337 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000338
kwiberg55b97fe2016-01-28 05:22:45 -0800339 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
340 // packetization.
341 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700342 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800343 (FrameType&)frameType, payloadType, timeStamp,
344 // Leaving the time when this frame was
345 // received from the capture device as
346 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700347 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100348 RTC_LOG(LS_ERROR)
349 << "Channel::SendData() failed to send data to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800350 return -1;
351 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000352
kwiberg55b97fe2016-01-28 05:22:45 -0800353 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000354}
355
stefan1d8a5062015-10-02 03:39:33 -0700356bool Channel::SendRtp(const uint8_t* data,
357 size_t len,
358 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800359 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000360
kwiberg55b97fe2016-01-28 05:22:45 -0800361 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100362 RTC_LOG(LS_ERROR)
363 << "Channel::SendPacket() failed to send RTP packet due to"
364 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800365 return false;
366 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000367
Fredrik Solenberga8b7c7f2018-01-17 11:18:31 +0100368 if (!_transportPtr->SendRtp(data, len, options)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100369 RTC_LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800370 return false;
371 }
372 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000373}
374
kwiberg55b97fe2016-01-28 05:22:45 -0800375bool Channel::SendRtcp(const uint8_t* data, size_t len) {
kwiberg55b97fe2016-01-28 05:22:45 -0800376 rtc::CritScope cs(&_callbackCritSect);
377 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100378 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() failed to send RTCP packet due to"
379 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800380 return false;
381 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000382
Fredrik Solenberga8b7c7f2018-01-17 11:18:31 +0100383 int n = _transportPtr->SendRtcp(data, len);
kwiberg55b97fe2016-01-28 05:22:45 -0800384 if (n < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100385 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800386 return false;
387 }
388 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000389}
390
kwiberg55b97fe2016-01-28 05:22:45 -0800391void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -0800392 // Update ssrc so that NTP for AV sync can be updated.
393 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000394}
395
Peter Boströmac547a62015-09-17 23:03:57 +0200396void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200397 // TODO(saza): remove.
niklase@google.com470e71d2011-07-07 08:21:25 +0000398}
399
Karl Wibergc62f6c72017-10-04 12:38:53 +0200400int32_t Channel::OnInitializeDecoder(int payload_type,
401 const SdpAudioFormat& audio_format,
402 uint32_t rate) {
403 if (!audio_coding_->RegisterReceiveCodec(payload_type, audio_format)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100404 RTC_LOG(LS_WARNING) << "Channel::OnInitializeDecoder() invalid codec (pt="
405 << payload_type << ", " << audio_format
406 << ") received -1";
kwiberg55b97fe2016-01-28 05:22:45 -0800407 return -1;
408 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000409
kwiberg55b97fe2016-01-28 05:22:45 -0800410 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000411}
412
kwiberg55b97fe2016-01-28 05:22:45 -0800413int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
414 size_t payloadSize,
415 const WebRtcRTPHeader* rtpHeader) {
kwiberg55b97fe2016-01-28 05:22:45 -0800416 if (!channel_state_.Get().playing) {
417 // Avoid inserting into NetEQ when we are not playing. Count the
418 // packet as discarded.
niklase@google.com470e71d2011-07-07 08:21:25 +0000419 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800420 }
421
422 // Push the incoming payload (parsed and ready for decoding) into the ACM
423 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
424 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100425 RTC_LOG(LS_ERROR)
426 << "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800427 return -1;
428 }
429
kwiberg55b97fe2016-01-28 05:22:45 -0800430 int64_t round_trip_time = 0;
431 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
432 NULL);
433
434 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
435 if (!nack_list.empty()) {
436 // Can't use nack_list.data() since it's not supported by all
437 // compilers.
438 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
439 }
440 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000441}
442
solenberg2397b9a2017-09-22 06:48:10 -0700443AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
444 int sample_rate_hz,
445 AudioFrame* audio_frame) {
446 audio_frame->sample_rate_hz_ = sample_rate_hz;
447
ivoc14d5dbe2016-07-04 07:06:55 -0700448 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800449 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
Elad Alon4a87e1c2017-10-03 16:11:34 +0200450 event_log_proxy_->Log(rtc::MakeUnique<RtcEventAudioPlayout>(ssrc));
kwiberg55b97fe2016-01-28 05:22:45 -0800451 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700452 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700453 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700454 &muted) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100455 RTC_LOG(LS_ERROR) << "Channel::GetAudioFrame() PlayoutData10Ms() failed!";
kwiberg55b97fe2016-01-28 05:22:45 -0800456 // In all likelihood, the audio in this frame is garbage. We return an
457 // error so that the audio mixer module doesn't add it to the mix. As
458 // a result, it won't be played out and the actions skipped here are
459 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700460 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800461 }
henrik.lundina89ab962016-05-18 08:52:45 -0700462
463 if (muted) {
464 // TODO(henrik.lundin): We should be able to do better than this. But we
465 // will have to go through all the cases below where the audio samples may
466 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700467 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700468 }
kwiberg55b97fe2016-01-28 05:22:45 -0800469
kwiberg55b97fe2016-01-28 05:22:45 -0800470 {
471 // Pass the audio buffers to an optional sink callback, before applying
472 // scaling/panning, as that applies to the mix operation.
473 // External recipients of the audio (e.g. via AudioTrack), will do their
474 // own mixing/dynamic processing.
475 rtc::CritScope cs(&_callbackCritSect);
476 if (audio_sink_) {
477 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700478 audio_frame->data(), audio_frame->samples_per_channel_,
479 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
480 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800481 audio_sink_->OnData(data);
482 }
483 }
484
485 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800486 {
487 rtc::CritScope cs(&volume_settings_critsect_);
488 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800489 }
490
491 // Output volume scaling
492 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800493 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700494 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800495 }
496
kwiberg55b97fe2016-01-28 05:22:45 -0800497 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700498 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700499 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700500 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700501 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800502
solenberg2397b9a2017-09-22 06:48:10 -0700503 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800504 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700505 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800506 }
507
508 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700509 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800510
511 // Compute elapsed time.
512 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700513 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
514 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800515 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700516 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800517
niklase@google.com470e71d2011-07-07 08:21:25 +0000518 {
kwiberg55b97fe2016-01-28 05:22:45 -0800519 rtc::CritScope lock(&ts_stats_lock_);
520 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700521 audio_frame->ntp_time_ms_ =
522 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800523 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700524 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800525 // Compute |capture_start_ntp_time_ms_| so that
526 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
527 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700528 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000529 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000530 }
kwiberg55b97fe2016-01-28 05:22:45 -0800531 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000532
Henrik Lundin9bde6b72017-11-02 15:01:56 +0100533 {
Henrik Lundinabbff892017-11-29 09:14:04 +0100534 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
535 audio_coding_->TargetDelayMs());
Henrik Lundin9bde6b72017-11-02 15:01:56 +0100536 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
537 rtc::CritScope lock(&video_sync_lock_);
538 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
539 jitter_buffer_delay + playout_delay_ms_);
540 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
541 jitter_buffer_delay);
542 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
543 playout_delay_ms_);
544 }
545
solenberg2397b9a2017-09-22 06:48:10 -0700546 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
547 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000548}
549
solenberg2397b9a2017-09-22 06:48:10 -0700550int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800551 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700552 return std::max(audio_coding_->ReceiveFrequency(),
553 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000554}
555
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100556Channel::Channel(rtc::TaskQueue* encoder_queue,
557 ProcessThread* module_process_thread,
558 AudioDeviceModule* audio_device_module)
559 : Channel(module_process_thread,
560 audio_device_module,
561 0,
562 false,
563 rtc::scoped_refptr<AudioDecoderFactory>()) {
564 RTC_DCHECK(encoder_queue);
565 encoder_queue_ = encoder_queue;
niklase@google.com470e71d2011-07-07 08:21:25 +0000566}
567
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100568Channel::Channel(ProcessThread* module_process_thread,
569 AudioDeviceModule* audio_device_module,
570 size_t jitter_buffer_max_packets,
571 bool jitter_buffer_fast_playout,
572 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
573 : event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800574 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
magjedf3feeff2016-11-25 06:40:25 -0800575 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100576 rtp_receive_statistics_(
577 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
578 rtp_receiver_(
579 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100580 this,
581 this,
582 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700583 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100584 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100585 _timeStamp(0), // This is just an offset, RTP module will add it's own
586 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100587 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100588 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100589 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100590 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100591 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
592 capture_start_rtp_time_stamp_(-1),
593 capture_start_ntp_time_ms_(-1),
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100594 _moduleProcessThreadPtr(module_process_thread),
595 _audioDeviceModulePtr(audio_device_module),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100596 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700597 input_mute_(false),
598 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100599 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100600 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800601 transport_overhead_per_packet_(0),
602 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100603 rtcp_observer_(new VoERtcpObserver(this)),
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100604 associated_send_channel_(nullptr),
stefanbba9dec2016-02-01 04:39:55 -0800605 feedback_observer_proxy_(new TransportFeedbackProxy()),
606 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700607 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200608 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
609 kMaxRetransmissionWindowMs)),
elad.alon28770482017-03-28 05:03:55 -0700610 use_twcc_plr_for_ana_(
611 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100612 RTC_DCHECK(module_process_thread);
613 RTC_DCHECK(audio_device_module);
614 AudioCodingModule::Config acm_config;
615 acm_config.decoder_factory = decoder_factory;
616 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
617 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
henrik.lundina89ab962016-05-18 08:52:45 -0700618 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800619 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200620
kwiberg55b97fe2016-01-28 05:22:45 -0800621 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000622
kwiberg55b97fe2016-01-28 05:22:45 -0800623 RtpRtcp::Configuration configuration;
624 configuration.audio = true;
625 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800626 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800627 configuration.receive_statistics = rtp_receive_statistics_.get();
628 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800629 if (pacing_enabled_) {
630 configuration.paced_sender = rtp_packet_sender_proxy_.get();
631 configuration.transport_sequence_number_allocator =
632 seq_num_allocator_proxy_.get();
633 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
634 }
ivoc14d5dbe2016-07-04 07:06:55 -0700635 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800636 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200637 configuration.retransmission_rate_limiter =
638 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000639
kwiberg55b97fe2016-01-28 05:22:45 -0800640 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100641 _rtpRtcpModule->SetSendingMediaStatus(false);
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100642
643 Init();
niklase@google.com470e71d2011-07-07 08:21:25 +0000644}
645
kwiberg55b97fe2016-01-28 05:22:45 -0800646Channel::~Channel() {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100647 Terminate();
tommi0a2391f2017-03-21 02:31:51 -0700648 RTC_DCHECK(!channel_state_.Get().sending);
649 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000650}
651
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100652void Channel::Init() {
kwiberg55b97fe2016-01-28 05:22:45 -0800653 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000654
kwiberg55b97fe2016-01-28 05:22:45 -0800655 // --- Add modules to process thread (for periodic schedulation)
tommidea489f2017-03-03 03:20:24 -0800656 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800657
658 // --- ACM initialization
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100659 int error = audio_coding_->InitializeReceiver();
660 RTC_DCHECK_EQ(0, error);
kwiberg55b97fe2016-01-28 05:22:45 -0800661
662 // --- RTP/RTCP module initialization
663
664 // Ensure that RTCP is enabled by default for the created channel.
665 // Note that, the module will keep generating RTCP until it is explicitly
666 // disabled by the user.
667 // After StopListen (when no sockets exists), RTCP packets will no longer
668 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700669 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800670 // RTCP is enabled by default.
671 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
kwiberg55b97fe2016-01-28 05:22:45 -0800672
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100673 // --- Register all permanent callbacks
674 error = audio_coding_->RegisterTransportCallback(this);
675 RTC_DCHECK_EQ(0, error);
kwiberg1c07c702017-03-27 07:15:49 -0700676}
677
tommi0a2391f2017-03-21 02:31:51 -0700678void Channel::Terminate() {
679 RTC_DCHECK(construction_thread_.CalledOnValidThread());
680 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700681 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
682
683 StopSend();
684 StopPlayout();
685
tommi0a2391f2017-03-21 02:31:51 -0700686 // The order to safely shutdown modules in a channel is:
687 // 1. De-register callbacks in modules
688 // 2. De-register modules in process thread
689 // 3. Destroy modules
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100690 int error = audio_coding_->RegisterTransportCallback(NULL);
691 RTC_DCHECK_EQ(0, error);
tommi0a2391f2017-03-21 02:31:51 -0700692
tommi0a2391f2017-03-21 02:31:51 -0700693 // De-register modules in process thread
694 if (_moduleProcessThreadPtr)
695 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
696
697 // End of modules shutdown
698}
699
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100700void Channel::SetSink(AudioSinkInterface* sink) {
tommi31fc21f2016-01-21 10:37:37 -0800701 rtc::CritScope cs(&_callbackCritSect);
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100702 audio_sink_ = sink;
ossu29b1a8d2016-06-13 07:34:51 -0700703}
704
kwiberg55b97fe2016-01-28 05:22:45 -0800705int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800706 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000707 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800708 }
709
kwiberg55b97fe2016-01-28 05:22:45 -0800710 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800711
712 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000713}
714
kwiberg55b97fe2016-01-28 05:22:45 -0800715int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800716 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000717 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800718 }
719
kwiberg55b97fe2016-01-28 05:22:45 -0800720 channel_state_.SetPlaying(false);
721 _outputAudioLevel.Clear();
722
723 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000724}
725
kwiberg55b97fe2016-01-28 05:22:45 -0800726int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800727 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000728 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800729 }
730 channel_state_.SetSending(true);
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100731
solenberg08b19df2017-02-15 00:42:31 -0800732 // Resume the previous sequence number which was reset by StopSend(). This
733 // needs to be done before |sending| is set to true on the RTP/RTCP module.
734 if (send_sequence_number_) {
735 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
736 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100737 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800738 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100739 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100740 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800741 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000742 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800743 return -1;
744 }
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100745 {
746 // It is now OK to start posting tasks to the encoder task queue.
747 rtc::CritScope cs(&encoder_queue_lock_);
748 encoder_queue_is_active_ = true;
749 }
kwiberg55b97fe2016-01-28 05:22:45 -0800750 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000751}
752
henrikaec6fbd22017-03-31 05:43:36 -0700753void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800754 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700755 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800756 }
757 channel_state_.SetSending(false);
758
henrikaec6fbd22017-03-31 05:43:36 -0700759 // Post a task to the encoder thread which sets an event when the task is
760 // executed. We know that no more encoding tasks will be added to the task
761 // queue for this channel since sending is now deactivated. It means that,
762 // if we wait for the event to bet set, we know that no more pending tasks
763 // exists and it is therfore guaranteed that the task queue will never try
764 // to acccess and invalid channel object.
765 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700766
henrikaec6fbd22017-03-31 05:43:36 -0700767 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700768 {
769 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
770 // than this final "flush task" to be posted on the queue.
771 rtc::CritScope cs(&encoder_queue_lock_);
772 encoder_queue_is_active_ = false;
773 encoder_queue_->PostTask([&flush]() { flush.Set(); });
774 }
henrikaec6fbd22017-03-31 05:43:36 -0700775 flush.Wait(rtc::Event::kForever);
776
kwiberg55b97fe2016-01-28 05:22:45 -0800777 // Store the sequence number to be able to pick up the same sequence for
778 // the next StartSend(). This is needed for restarting device, otherwise
779 // it might cause libSRTP to complain about packets being replayed.
780 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
781 // CL is landed. See issue
782 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
783 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
784
785 // Reset sending SSRC and sequence number and triggers direct transmission
786 // of RTCP BYE
787 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100788 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800789 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100790 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000791}
792
ossu1ffbd6c2017-04-06 12:05:04 -0700793bool Channel::SetEncoder(int payload_type,
794 std::unique_ptr<AudioEncoder> encoder) {
795 RTC_DCHECK_GE(payload_type, 0);
796 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700797 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
798 // one for for us to keep track of sample rate and number of channels, etc.
799
800 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
801 // as well as some other things, so we collect this info and send it along.
802 CodecInst rtp_codec;
803 rtp_codec.pltype = payload_type;
804 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
805 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700806 // Seems unclear if it should be clock rate or sample rate. CodecInst
807 // supposedly carries the sample rate, but only clock rate seems sensible to
808 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700809 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
810 rtp_codec.pacsize = rtc::CheckedDivExact(
811 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
812 100);
813 rtp_codec.channels = encoder->NumChannels();
814 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700815
ossu76d29f92017-06-09 07:30:13 -0700816 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700817 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700818 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100819 RTC_LOG(LS_ERROR)
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200820 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700821 return false;
822 }
823 }
824
825 audio_coding_->SetEncoder(std::move(encoder));
826 return true;
827}
828
ossu20a4b3f2017-04-27 02:08:52 -0700829void Channel::ModifyEncoder(
830 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
831 audio_coding_->ModifyEncoder(modifier);
832}
833
kwiberg55b97fe2016-01-28 05:22:45 -0800834int32_t Channel::GetRecCodec(CodecInst& codec) {
835 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +0000836}
837
minyue78b4d562016-11-30 04:47:39 -0800838void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -0700839 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -0800840 if (*encoder) {
Oskar Sundbom606c8822017-11-16 10:57:11 +0100841 (*encoder)->OnReceivedUplinkBandwidth(bitrate_bps, probing_interval_ms);
michaelt2fedf9c2016-11-28 02:34:18 -0800842 }
843 });
michaelt566d8202017-01-12 10:17:38 -0800844 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +0200845}
846
elad.alond12a8e12017-03-23 11:04:48 -0700847void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
848 if (!use_twcc_plr_for_ana_)
849 return;
minyue7e304322016-10-12 05:00:55 -0700850 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -0700851 if (*encoder) {
852 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
853 }
854 });
855}
856
elad.alondadb4dc2017-03-23 15:29:50 -0700857void Channel::OnRecoverableUplinkPacketLossRate(
858 float recoverable_packet_loss_rate) {
859 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
860 if (*encoder) {
861 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
862 recoverable_packet_loss_rate);
863 }
864 });
865}
866
elad.alond12a8e12017-03-23 11:04:48 -0700867void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
868 if (use_twcc_plr_for_ana_)
869 return;
870 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
871 if (*encoder) {
872 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
873 }
minyue7e304322016-10-12 05:00:55 -0700874 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000875}
876
kwiberg1c07c702017-03-27 07:15:49 -0700877void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
878 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
879 audio_coding_->SetReceiveCodecs(codecs);
880}
881
minyue7e304322016-10-12 05:00:55 -0700882bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
883 bool success = false;
884 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
885 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -0700886 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
887 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -0700888 }
889 });
890 return success;
891}
892
893void Channel::DisableAudioNetworkAdaptor() {
894 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
895 if (*encoder)
896 (*encoder)->DisableAudioNetworkAdaptor();
897 });
898}
899
900void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
901 int max_frame_length_ms) {
902 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
903 if (*encoder) {
904 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
905 max_frame_length_ms);
906 }
907 });
908}
909
solenberg1c239d42017-09-29 06:00:28 -0700910void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -0800911 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -0700912 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +0000913}
914
nisse657bab22017-02-21 06:28:10 -0800915void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -0800916 RTPHeader header;
917 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -0700918
919 // Store playout timestamp for the received RTP packet
920 UpdatePlayoutTimestamp(false);
921
922 header.payload_type_frequency =
923 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
924 if (header.payload_type_frequency >= 0) {
925 bool in_order = IsPacketInOrder(header);
926 rtp_receive_statistics_->IncomingPacket(
927 header, packet.size(), IsPacketRetransmitted(header, in_order));
928 rtp_payload_registry_->SetIncomingPayloadType(header);
929
Niels Möller22ec9522017-10-05 08:39:15 +0200930 ReceivePacket(packet.data(), packet.size(), header);
solenberg946d8862017-09-21 04:02:53 -0700931 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000932}
933
934bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000935 size_t packet_length,
Niels Möller22ec9522017-10-05 08:39:15 +0200936 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000937 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000938 assert(packet_length >= header.headerLength);
939 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +0200940 const auto pl =
941 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
942 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000943 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +0000944 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000945 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Niels Möller22ec9522017-10-05 08:39:15 +0200946 pl->typeSpecific);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000947}
948
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000949bool Channel::IsPacketInOrder(const RTPHeader& header) const {
950 StreamStatistician* statistician =
951 rtp_receive_statistics_->GetStatistician(header.ssrc);
952 if (!statistician)
953 return false;
954 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +0000955}
956
stefan@webrtc.org48df3812013-11-08 15:18:52 +0000957bool Channel::IsPacketRetransmitted(const RTPHeader& header,
958 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000959 StreamStatistician* statistician =
960 rtp_receive_statistics_->GetStatistician(header.ssrc);
961 if (!statistician)
962 return false;
963 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000964 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000965 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -0800966 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +0000967}
968
mflodman3d7db262016-04-29 00:57:13 -0700969int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +0000970 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +0000971 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +0000972
pwestin@webrtc.org0c459572013-04-03 15:43:57 +0000973 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -0700974 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +0000975
Minyue2013aec2015-05-13 14:14:42 +0200976 int64_t rtt = GetRTT(true);
977 if (rtt == 0) {
978 // Waiting for valid RTT.
979 return 0;
980 }
Erik Språng737336d2016-07-29 12:59:36 +0200981
982 int64_t nack_window_ms = rtt;
983 if (nack_window_ms < kMinRetransmissionWindowMs) {
984 nack_window_ms = kMinRetransmissionWindowMs;
985 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
986 nack_window_ms = kMaxRetransmissionWindowMs;
987 }
988 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
989
minyue7e304322016-10-12 05:00:55 -0700990 // Invoke audio encoders OnReceivedRtt().
991 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
992 if (*encoder)
993 (*encoder)->OnReceivedRtt(rtt);
994 });
995
Minyue2013aec2015-05-13 14:14:42 +0200996 uint32_t ntp_secs = 0;
997 uint32_t ntp_frac = 0;
998 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800999 if (0 !=
1000 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1001 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001002 // Waiting for RTCP.
1003 return 0;
1004 }
1005
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001006 {
tommi31fc21f2016-01-21 10:37:37 -08001007 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001008 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001009 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001010 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001011}
1012
solenberg8d73f8c2017-03-08 01:52:20 -08001013int Channel::GetSpeechOutputLevel() const {
1014 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001015}
1016
solenberg8d73f8c2017-03-08 01:52:20 -08001017int Channel::GetSpeechOutputLevelFullRange() const {
1018 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001019}
1020
zsteine76bd3a2017-07-14 12:17:49 -07001021double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001022 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001023}
1024
1025double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001026 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001027}
1028
solenberg8d73f8c2017-03-08 01:52:20 -08001029void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001030 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001031 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001032}
1033
solenberg1c2af8e2016-03-24 10:36:00 -07001034bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001035 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001036 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001037}
1038
solenberg8d73f8c2017-03-08 01:52:20 -08001039void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001040 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001041 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001042}
1043
solenberg8842c3e2016-03-11 03:06:41 -08001044int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001045 RTC_DCHECK_LE(0, event);
1046 RTC_DCHECK_GE(255, event);
1047 RTC_DCHECK_LE(0, duration_ms);
1048 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001049 if (!Sending()) {
1050 return -1;
1051 }
solenberg8842c3e2016-03-11 03:06:41 -08001052 if (_rtpRtcpModule->SendTelephoneEventOutband(
1053 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001054 RTC_LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001055 return -1;
1056 }
1057 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001058}
1059
solenbergffbbcac2016-11-17 05:25:37 -08001060int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1061 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001062 RTC_DCHECK_LE(0, payload_type);
1063 RTC_DCHECK_GE(127, payload_type);
1064 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001065 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001066 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001067 memcpy(codec.plname, "telephone-event", 16);
1068 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1069 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1070 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001071 RTC_LOG(LS_ERROR)
1072 << "SetSendTelephoneEventPayloadType() failed to register "
1073 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001074 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001075 }
kwiberg55b97fe2016-01-28 05:22:45 -08001076 }
kwiberg55b97fe2016-01-28 05:22:45 -08001077 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001078}
1079
kwiberg55b97fe2016-01-28 05:22:45 -08001080int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001081 if (channel_state_.Get().sending) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001082 RTC_LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001083 return -1;
1084 }
1085 _rtpRtcpModule->SetSSRC(ssrc);
1086 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001087}
1088
kwiberg55b97fe2016-01-28 05:22:45 -08001089int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1090 ssrc = rtp_receiver_->SSRC();
1091 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001092}
1093
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001094int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001095 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001096 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001097}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001098
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001099void Channel::EnableSendTransportSequenceNumber(int id) {
1100 int ret =
1101 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1102 RTC_DCHECK_EQ(0, ret);
1103}
1104
stefanbba9dec2016-02-01 04:39:55 -08001105void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001106 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001107 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001108 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1109 TransportFeedbackObserver* transport_feedback_observer =
1110 transport->transport_feedback_observer();
1111 PacketRouter* packet_router = transport->packet_router();
1112
stefanbba9dec2016-02-01 04:39:55 -08001113 RTC_DCHECK(rtp_packet_sender);
1114 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001115 RTC_DCHECK(packet_router);
1116 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001117 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001118 feedback_observer_proxy_->SetTransportFeedbackObserver(
1119 transport_feedback_observer);
1120 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1121 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1122 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001123 constexpr bool remb_candidate = false;
1124 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001125 packet_router_ = packet_router;
1126}
1127
stefanbba9dec2016-02-01 04:39:55 -08001128void Channel::RegisterReceiverCongestionControlObjects(
1129 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001130 RTC_DCHECK(packet_router);
1131 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001132 constexpr bool remb_candidate = false;
1133 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001134 packet_router_ = packet_router;
1135}
1136
nissefdbfdc92017-03-31 05:44:52 -07001137void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001138 RTC_DCHECK(packet_router_);
1139 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001140 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001141 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1142 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001143 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001144 packet_router_ = nullptr;
1145 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1146}
1147
nissefdbfdc92017-03-31 05:44:52 -07001148void Channel::ResetReceiverCongestionControlObjects() {
1149 RTC_DCHECK(packet_router_);
1150 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1151 packet_router_ = nullptr;
1152}
1153
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001154void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001155 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001156}
1157
kwiberg55b97fe2016-01-28 05:22:45 -08001158int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001159 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001160 RTC_LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001161 return -1;
1162 }
1163 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001164}
1165
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001166int Channel::GetRemoteRTCPReportBlocks(
1167 std::vector<ReportBlock>* report_blocks) {
1168 if (report_blocks == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001169 RTC_LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001170 return -1;
1171 }
1172
1173 // Get the report blocks from the latest received RTCP Sender or Receiver
1174 // Report. Each element in the vector contains the sender's SSRC and a
1175 // report block according to RFC 3550.
1176 std::vector<RTCPReportBlock> rtcp_report_blocks;
1177 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001178 return -1;
1179 }
1180
1181 if (rtcp_report_blocks.empty())
1182 return 0;
1183
1184 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1185 for (; it != rtcp_report_blocks.end(); ++it) {
1186 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001187 report_block.sender_SSRC = it->sender_ssrc;
1188 report_block.source_SSRC = it->source_ssrc;
1189 report_block.fraction_lost = it->fraction_lost;
1190 report_block.cumulative_num_packets_lost = it->packets_lost;
1191 report_block.extended_highest_sequence_number =
1192 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001193 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001194 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1195 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001196 report_blocks->push_back(report_block);
1197 }
1198 return 0;
1199}
1200
kwiberg55b97fe2016-01-28 05:22:45 -08001201int Channel::GetRTPStatistics(CallStatistics& stats) {
1202 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001203
kwiberg55b97fe2016-01-28 05:22:45 -08001204 // The jitter statistics is updated for each received RTP packet and is
1205 // based on received packets.
1206 RtcpStatistics statistics;
1207 StreamStatistician* statistician =
1208 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001209 if (statistician) {
1210 statistician->GetStatistics(&statistics,
1211 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001212 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001213
kwiberg55b97fe2016-01-28 05:22:45 -08001214 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001215 stats.cumulativeLost = statistics.packets_lost;
1216 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001217 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001218
kwiberg55b97fe2016-01-28 05:22:45 -08001219 // --- RTT
1220 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001221
kwiberg55b97fe2016-01-28 05:22:45 -08001222 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001223
kwiberg55b97fe2016-01-28 05:22:45 -08001224 size_t bytesSent(0);
1225 uint32_t packetsSent(0);
1226 size_t bytesReceived(0);
1227 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001228
kwiberg55b97fe2016-01-28 05:22:45 -08001229 if (statistician) {
1230 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1231 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001232
kwiberg55b97fe2016-01-28 05:22:45 -08001233 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001234 RTC_LOG(LS_WARNING)
1235 << "GetRTPStatistics() failed to retrieve RTP datacounters"
1236 << " => output will not be complete";
kwiberg55b97fe2016-01-28 05:22:45 -08001237 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001238
kwiberg55b97fe2016-01-28 05:22:45 -08001239 stats.bytesSent = bytesSent;
1240 stats.packetsSent = packetsSent;
1241 stats.bytesReceived = bytesReceived;
1242 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001243
kwiberg55b97fe2016-01-28 05:22:45 -08001244 // --- Timestamps
1245 {
1246 rtc::CritScope lock(&ts_stats_lock_);
1247 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1248 }
1249 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001250}
1251
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001252void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1253 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001254 // If pacing is enabled we always store packets.
1255 if (!pacing_enabled_)
1256 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001257 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001258 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001259 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001260 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001261 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001262}
1263
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001264// Called when we are missing one or more packets.
1265int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001266 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1267}
1268
Fredrik Solenberg2a877972017-12-15 16:42:15 +01001269void Channel::ProcessAndEncodeAudio(std::unique_ptr<AudioFrame> audio_frame) {
henrika4515fa02017-05-03 08:30:15 -07001270 // Avoid posting any new tasks if sending was already stopped in StopSend().
1271 rtc::CritScope cs(&encoder_queue_lock_);
1272 if (!encoder_queue_is_active_) {
1273 return;
1274 }
henrika45802172017-09-28 09:39:34 +02001275 // Profile time between when the audio frame is added to the task queue and
1276 // when the task is actually executed.
1277 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001278 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1279 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001280}
1281
henrikaec6fbd22017-03-31 05:43:36 -07001282void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1283 RTC_DCHECK_RUN_ON(encoder_queue_);
1284 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1285 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001286
henrika45802172017-09-28 09:39:34 +02001287 // Measure time between when the audio frame is added to the task queue and
1288 // when the task is actually executed. Goal is to keep track of unwanted
1289 // extra latency added by the task queue.
1290 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1291 audio_input->ElapsedProfileTimeMs());
1292
henrikaec6fbd22017-03-31 05:43:36 -07001293 bool is_muted = InputMute();
1294 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001295
kwiberg55b97fe2016-01-28 05:22:45 -08001296 if (_includeAudioLevelIndication) {
1297 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001298 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001299 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001300 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001301 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001302 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001303 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001304 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001305 }
kwiberg55b97fe2016-01-28 05:22:45 -08001306 }
solenberg1c2af8e2016-03-24 10:36:00 -07001307 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001308
henrikaec6fbd22017-03-31 05:43:36 -07001309 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001310
kwiberg55b97fe2016-01-28 05:22:45 -08001311 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001312 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001313 // This call will trigger AudioPacketizationCallback::SendData if encoding
1314 // is done and payload is ready for packetization and transmission.
1315 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001316 if (audio_coding_->Add10MsData(*audio_input) < 0) {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +01001317 RTC_LOG(LS_ERROR) << "ACM::Add10MsData() failed.";
henrikaec6fbd22017-03-31 05:43:36 -07001318 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001319 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001320
henrikaec6fbd22017-03-31 05:43:36 -07001321 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001322}
1323
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +01001324void Channel::SetAssociatedSendChannel(Channel* channel) {
1325 RTC_DCHECK_NE(this, channel);
solenberg7602aab2016-11-14 11:30:07 -08001326 rtc::CritScope lock(&assoc_send_channel_lock_);
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +01001327 associated_send_channel_ = channel;
Minyue2013aec2015-05-13 14:14:42 +02001328}
1329
ivoc14d5dbe2016-07-04 07:06:55 -07001330void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1331 event_log_proxy_->SetEventLog(event_log);
1332}
1333
michaelt9332b7d2016-11-30 07:51:13 -08001334void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1335 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1336}
1337
nisse284542b2017-01-10 08:58:32 -08001338void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001339 size_t overhead_per_packet =
1340 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001341 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1342 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001343 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001344 }
1345 });
1346}
1347
1348void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001349 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001350 transport_overhead_per_packet_ = transport_overhead_per_packet;
1351 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001352}
1353
hbos3fd31fe2017-02-28 05:43:16 -08001354// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001355void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001356 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001357 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1358 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001359}
1360
kwiberg55b97fe2016-01-28 05:22:45 -08001361int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1362 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001363}
1364
wu@webrtc.org24301a62013-12-13 19:17:43 +00001365void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1366 audio_coding_->GetDecodingCallStatistics(stats);
1367}
1368
ivoce1198e02017-09-08 08:13:19 -07001369ANAStats Channel::GetANAStatistics() const {
1370 return audio_coding_->GetANAStats();
1371}
1372
solenberg358057b2015-11-27 10:46:42 -08001373uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001374 rtc::CritScope lock(&video_sync_lock_);
1375 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001376}
1377
kwiberg55b97fe2016-01-28 05:22:45 -08001378int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001379 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1380 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001381 RTC_LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001382 return -1;
1383 }
1384 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001385 RTC_LOG(LS_ERROR)
1386 << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001387 return -1;
1388 }
1389 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001390}
1391
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001392int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001393 uint32_t playout_timestamp_rtp = 0;
1394 {
tommi31fc21f2016-01-21 10:37:37 -08001395 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001396 playout_timestamp_rtp = playout_timestamp_rtp_;
1397 }
kwiberg55b97fe2016-01-28 05:22:45 -08001398 if (playout_timestamp_rtp == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001399 RTC_LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001400 return -1;
1401 }
deadbeef74375882015-08-13 12:09:10 -07001402 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001403 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001404}
1405
kwiberg55b97fe2016-01-28 05:22:45 -08001406int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1407 RtpReceiver** rtp_receiver) const {
1408 *rtpRtcpModule = _rtpRtcpModule.get();
1409 *rtp_receiver = rtp_receiver_.get();
1410 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001411}
1412
deadbeef74375882015-08-13 12:09:10 -07001413void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001414 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001415
henrik.lundin96bd5022016-04-06 04:13:56 -07001416 if (!jitter_buffer_playout_timestamp_) {
1417 // This can happen if this channel has not received any RTP packets. In
1418 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001419 return;
1420 }
1421
1422 uint16_t delay_ms = 0;
1423 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001424 RTC_LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1425 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001426 return;
1427 }
1428
henrik.lundin96bd5022016-04-06 04:13:56 -07001429 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1430 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001431
1432 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001433 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001434
deadbeef74375882015-08-13 12:09:10 -07001435 {
tommi31fc21f2016-01-21 10:37:37 -08001436 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001437 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001438 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001439 }
1440 playout_delay_ms_ = delay_ms;
1441 }
1442}
1443
kwiberg55b97fe2016-01-28 05:22:45 -08001444int Channel::SetSendRtpHeaderExtension(bool enable,
1445 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001446 unsigned char id) {
1447 int error = 0;
1448 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1449 if (enable) {
1450 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1451 }
1452 return error;
1453}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001454
ossue280cde2016-10-12 11:04:10 -07001455int Channel::GetRtpTimestampRateHz() const {
1456 const auto format = audio_coding_->ReceiveFormat();
1457 // Default to the playout frequency if we've not gotten any packets yet.
1458 // TODO(ossu): Zero clockrate can only happen if we've added an external
1459 // decoder for a format we don't support internally. Remove once that way of
1460 // adding decoders is gone!
1461 return (format && format->clockrate_hz != 0)
1462 ? format->clockrate_hz
1463 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001464}
1465
Minyue2013aec2015-05-13 14:14:42 +02001466int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001467 RtcpMode method = _rtpRtcpModule->RTCP();
1468 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001469 return 0;
1470 }
1471 std::vector<RTCPReportBlock> report_blocks;
1472 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001473
1474 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001475 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001476 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001477 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001478 // Tries to get RTT from an associated channel. This is important for
1479 // receive-only channels.
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +01001480 if (associated_send_channel_) {
Minyue2013aec2015-05-13 14:14:42 +02001481 // To prevent infinite recursion and deadlock, calling GetRTT of
1482 // associate channel should always use "false" for argument:
1483 // |allow_associate_channel|.
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +01001484 rtt = associated_send_channel_->GetRTT(false);
Minyue2013aec2015-05-13 14:14:42 +02001485 }
1486 }
1487 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001488 }
1489
1490 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1491 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1492 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001493 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001494 break;
1495 }
1496 if (it == report_blocks.end()) {
1497 // We have not received packets with SSRC matching the report blocks.
1498 // To calculate RTT we try with the SSRC of the first report block.
1499 // This is very important for send-only channels where we don't know
1500 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001501 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001502 }
Minyue2013aec2015-05-13 14:14:42 +02001503
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001504 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001505 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001506 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001507 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1508 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001509 return 0;
1510 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001511 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001512}
1513
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001514} // namespace voe
1515} // namespace webrtc