blob: bd8dbf46b597705a9eb00e9a2f046d173eb5ddcd [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "voice_engine/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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000050
andrew@webrtc.org50419b02012-11-14 19:07:54 +000051namespace webrtc {
52namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000053
kwibergc8d071e2016-04-06 12:22:38 -070054namespace {
55
zsteine76bd3a2017-07-14 12:17:49 -070056constexpr double kAudioSampleDurationSeconds = 0.01;
Erik Språng737336d2016-07-29 12:59:36 +020057constexpr int64_t kMaxRetransmissionWindowMs = 1000;
58constexpr int64_t kMinRetransmissionWindowMs = 30;
59
Fredrik Solenberg55900fd2017-11-23 20:22:55 +010060// Video Sync.
61constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
62constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
63
kwibergc8d071e2016-04-06 12:22:38 -070064} // namespace
65
solenberg8842c3e2016-03-11 03:06:41 -080066const int kTelephoneEventAttenuationdB = 10;
67
ivoc14d5dbe2016-07-04 07:06:55 -070068class RtcEventLogProxy final : public webrtc::RtcEventLog {
69 public:
70 RtcEventLogProxy() : event_log_(nullptr) {}
71
Bjorn Tereliusde939432017-11-20 17:38:14 +010072 bool StartLogging(std::unique_ptr<RtcEventLogOutput> output,
73 int64_t output_period_ms) override {
Elad Alon83ccca12017-10-04 13:18:26 +020074 RTC_NOTREACHED();
75 return false;
76 }
77
ivoc14d5dbe2016-07-04 07:06:55 -070078 void StopLogging() override { RTC_NOTREACHED(); }
79
Elad Alon4a87e1c2017-10-03 16:11:34 +020080 void Log(std::unique_ptr<RtcEvent> event) override {
81 rtc::CritScope lock(&crit_);
82 if (event_log_) {
83 event_log_->Log(std::move(event));
84 }
85 }
86
ivoc14d5dbe2016-07-04 07:06:55 -070087 void SetEventLog(RtcEventLog* event_log) {
88 rtc::CritScope lock(&crit_);
89 event_log_ = event_log;
90 }
91
92 private:
93 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -070094 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -070095 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
96};
97
michaelt9332b7d2016-11-30 07:51:13 -080098class RtcpRttStatsProxy final : public RtcpRttStats {
99 public:
100 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
101
102 void OnRttUpdate(int64_t rtt) override {
103 rtc::CritScope lock(&crit_);
104 if (rtcp_rtt_stats_)
105 rtcp_rtt_stats_->OnRttUpdate(rtt);
106 }
107
108 int64_t LastProcessedRtt() const override {
109 rtc::CritScope lock(&crit_);
110 if (!rtcp_rtt_stats_)
111 return 0;
112 return rtcp_rtt_stats_->LastProcessedRtt();
113 }
114
115 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
116 rtc::CritScope lock(&crit_);
117 rtcp_rtt_stats_ = rtcp_rtt_stats;
118 }
119
120 private:
121 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700122 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800123 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
124};
125
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100126class TransportFeedbackProxy : public TransportFeedbackObserver {
127 public:
128 TransportFeedbackProxy() : feedback_observer_(nullptr) {
129 pacer_thread_.DetachFromThread();
130 network_thread_.DetachFromThread();
131 }
132
133 void SetTransportFeedbackObserver(
134 TransportFeedbackObserver* feedback_observer) {
135 RTC_DCHECK(thread_checker_.CalledOnValidThread());
136 rtc::CritScope lock(&crit_);
137 feedback_observer_ = feedback_observer;
138 }
139
140 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700141 void AddPacket(uint32_t ssrc,
142 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100143 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800144 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100145 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
146 rtc::CritScope lock(&crit_);
147 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700148 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100149 }
philipel8aadd502017-02-23 02:56:13 -0800150
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100151 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
152 RTC_DCHECK(network_thread_.CalledOnValidThread());
153 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700154 if (feedback_observer_)
155 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200156 }
elad.alonf9490002017-03-06 05:32:21 -0800157 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200158 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800159 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100160 }
161
162 private:
163 rtc::CriticalSection crit_;
164 rtc::ThreadChecker thread_checker_;
165 rtc::ThreadChecker pacer_thread_;
166 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700167 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100168};
169
170class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
171 public:
172 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
173 pacer_thread_.DetachFromThread();
174 }
175
176 void SetSequenceNumberAllocator(
177 TransportSequenceNumberAllocator* seq_num_allocator) {
178 RTC_DCHECK(thread_checker_.CalledOnValidThread());
179 rtc::CritScope lock(&crit_);
180 seq_num_allocator_ = seq_num_allocator;
181 }
182
183 // Implements TransportSequenceNumberAllocator.
184 uint16_t AllocateSequenceNumber() override {
185 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
186 rtc::CritScope lock(&crit_);
187 if (!seq_num_allocator_)
188 return 0;
189 return seq_num_allocator_->AllocateSequenceNumber();
190 }
191
192 private:
193 rtc::CriticalSection crit_;
194 rtc::ThreadChecker thread_checker_;
195 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700196 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100197};
198
199class RtpPacketSenderProxy : public RtpPacketSender {
200 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800201 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100202
203 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
204 RTC_DCHECK(thread_checker_.CalledOnValidThread());
205 rtc::CritScope lock(&crit_);
206 rtp_packet_sender_ = rtp_packet_sender;
207 }
208
209 // Implements RtpPacketSender.
210 void InsertPacket(Priority priority,
211 uint32_t ssrc,
212 uint16_t sequence_number,
213 int64_t capture_time_ms,
214 size_t bytes,
215 bool retransmission) override {
216 rtc::CritScope lock(&crit_);
217 if (rtp_packet_sender_) {
218 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
219 capture_time_ms, bytes, retransmission);
220 }
221 }
222
Alex Narest78609d52017-10-20 10:37:47 +0200223 void SetAccountForAudioPackets(bool account_for_audio) override {
224 RTC_NOTREACHED();
225 }
226
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100227 private:
228 rtc::ThreadChecker thread_checker_;
229 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700230 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100231};
232
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000233class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000234 public:
stefan7de8d642017-02-07 07:14:08 -0800235 explicit VoERtcpObserver(Channel* owner)
236 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000237 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000238
stefan7de8d642017-02-07 07:14:08 -0800239 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
240 rtc::CritScope lock(&crit_);
241 bandwidth_observer_ = bandwidth_observer;
242 }
243
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000244 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800245 rtc::CritScope lock(&crit_);
246 if (bandwidth_observer_) {
247 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
248 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000249 }
250
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000251 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
252 int64_t rtt,
253 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800254 {
255 rtc::CritScope lock(&crit_);
256 if (bandwidth_observer_) {
257 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
258 now_ms);
259 }
260 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000261 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
262 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
263 // report for VoiceEngine?
264 if (report_blocks.empty())
265 return;
266
267 int fraction_lost_aggregate = 0;
268 int total_number_of_packets = 0;
269
270 // If receiving multiple report blocks, calculate the weighted average based
271 // on the number of packets a report refers to.
272 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
273 block_it != report_blocks.end(); ++block_it) {
274 // Find the previous extended high sequence number for this remote SSRC,
275 // to calculate the number of RTP packets this report refers to. Ignore if
276 // we haven't seen this SSRC before.
277 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700278 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000279 int number_of_packets = 0;
280 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700281 number_of_packets =
282 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000283 }
srte3e69e5c2017-08-09 06:13:45 -0700284 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000285 total_number_of_packets += number_of_packets;
286
srte3e69e5c2017-08-09 06:13:45 -0700287 extended_max_sequence_number_[block_it->source_ssrc] =
288 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000289 }
290 int weighted_fraction_lost = 0;
291 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800292 weighted_fraction_lost =
293 (fraction_lost_aggregate + total_number_of_packets / 2) /
294 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000295 }
elad.alond12a8e12017-03-23 11:04:48 -0700296 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000297 }
298
299 private:
300 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000301 // Maps remote side ssrc to extended highest sequence number received.
302 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800303 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700304 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000305};
306
henrikaec6fbd22017-03-31 05:43:36 -0700307class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
308 public:
309 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
310 Channel* channel)
311 : audio_frame_(std::move(audio_frame)), channel_(channel) {
312 RTC_DCHECK(channel_);
313 }
314
315 private:
316 bool Run() override {
317 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
318 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
319 return true;
320 }
321
322 std::unique_ptr<AudioFrame> audio_frame_;
323 Channel* const channel_;
324};
325
kwiberg55b97fe2016-01-28 05:22:45 -0800326int32_t Channel::SendData(FrameType frameType,
327 uint8_t payloadType,
328 uint32_t timeStamp,
329 const uint8_t* payloadData,
330 size_t payloadSize,
331 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700332 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800333 if (_includeAudioLevelIndication) {
334 // Store current audio level in the RTP/RTCP module.
335 // The level will be used in combination with voice-activity state
336 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800337 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800338 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000339
kwiberg55b97fe2016-01-28 05:22:45 -0800340 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
341 // packetization.
342 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700343 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800344 (FrameType&)frameType, payloadType, timeStamp,
345 // Leaving the time when this frame was
346 // received from the capture device as
347 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700348 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100349 RTC_LOG(LS_ERROR)
350 << "Channel::SendData() failed to send data to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800351 return -1;
352 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000353
kwiberg55b97fe2016-01-28 05:22:45 -0800354 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000355}
356
stefan1d8a5062015-10-02 03:39:33 -0700357bool Channel::SendRtp(const uint8_t* data,
358 size_t len,
359 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800360 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000361
kwiberg55b97fe2016-01-28 05:22:45 -0800362 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100363 RTC_LOG(LS_ERROR)
364 << "Channel::SendPacket() failed to send RTP packet due to"
365 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800366 return false;
367 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000368
kwiberg55b97fe2016-01-28 05:22:45 -0800369 uint8_t* bufferToSendPtr = (uint8_t*)data;
370 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000371
kwiberg55b97fe2016-01-28 05:22:45 -0800372 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100373 RTC_LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800374 return false;
375 }
376 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000377}
378
kwiberg55b97fe2016-01-28 05:22:45 -0800379bool Channel::SendRtcp(const uint8_t* data, size_t len) {
kwiberg55b97fe2016-01-28 05:22:45 -0800380 rtc::CritScope cs(&_callbackCritSect);
381 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100382 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() failed to send RTCP packet due to"
383 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800384 return false;
385 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000386
kwiberg55b97fe2016-01-28 05:22:45 -0800387 uint8_t* bufferToSendPtr = (uint8_t*)data;
388 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000389
kwiberg55b97fe2016-01-28 05:22:45 -0800390 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
391 if (n < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100392 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800393 return false;
394 }
395 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000396}
397
kwiberg55b97fe2016-01-28 05:22:45 -0800398void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -0800399 // Update ssrc so that NTP for AV sync can be updated.
400 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000401}
402
Peter Boströmac547a62015-09-17 23:03:57 +0200403void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200404 // TODO(saza): remove.
niklase@google.com470e71d2011-07-07 08:21:25 +0000405}
406
Karl Wibergc62f6c72017-10-04 12:38:53 +0200407int32_t Channel::OnInitializeDecoder(int payload_type,
408 const SdpAudioFormat& audio_format,
409 uint32_t rate) {
410 if (!audio_coding_->RegisterReceiveCodec(payload_type, audio_format)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100411 RTC_LOG(LS_WARNING) << "Channel::OnInitializeDecoder() invalid codec (pt="
412 << payload_type << ", " << audio_format
413 << ") received -1";
kwiberg55b97fe2016-01-28 05:22:45 -0800414 return -1;
415 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000416
kwiberg55b97fe2016-01-28 05:22:45 -0800417 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000418}
419
kwiberg55b97fe2016-01-28 05:22:45 -0800420int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
421 size_t payloadSize,
422 const WebRtcRTPHeader* rtpHeader) {
kwiberg55b97fe2016-01-28 05:22:45 -0800423 if (!channel_state_.Get().playing) {
424 // Avoid inserting into NetEQ when we are not playing. Count the
425 // packet as discarded.
niklase@google.com470e71d2011-07-07 08:21:25 +0000426 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800427 }
428
429 // Push the incoming payload (parsed and ready for decoding) into the ACM
430 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
431 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100432 RTC_LOG(LS_ERROR)
433 << "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800434 return -1;
435 }
436
kwiberg55b97fe2016-01-28 05:22:45 -0800437 int64_t round_trip_time = 0;
438 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
439 NULL);
440
441 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
442 if (!nack_list.empty()) {
443 // Can't use nack_list.data() since it's not supported by all
444 // compilers.
445 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
446 }
447 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000448}
449
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000450bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000451 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000452 RTPHeader header;
453 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100454 RTC_LOG(LS_WARNING) << "IncomingPacket invalid RTP header";
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000455 return false;
456 }
457 header.payload_type_frequency =
458 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
459 if (header.payload_type_frequency < 0)
460 return false;
Niels Möller22ec9522017-10-05 08:39:15 +0200461 // TODO(nisse): Pass RtpPacketReceived with |recovered()| true.
462 return ReceivePacket(rtp_packet, rtp_packet_length, header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000463}
464
solenberg2397b9a2017-09-22 06:48:10 -0700465AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
466 int sample_rate_hz,
467 AudioFrame* audio_frame) {
468 audio_frame->sample_rate_hz_ = sample_rate_hz;
469
ivoc14d5dbe2016-07-04 07:06:55 -0700470 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800471 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
Elad Alon4a87e1c2017-10-03 16:11:34 +0200472 event_log_proxy_->Log(rtc::MakeUnique<RtcEventAudioPlayout>(ssrc));
kwiberg55b97fe2016-01-28 05:22:45 -0800473 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700474 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700475 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700476 &muted) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100477 RTC_LOG(LS_ERROR) << "Channel::GetAudioFrame() PlayoutData10Ms() failed!";
kwiberg55b97fe2016-01-28 05:22:45 -0800478 // In all likelihood, the audio in this frame is garbage. We return an
479 // error so that the audio mixer module doesn't add it to the mix. As
480 // a result, it won't be played out and the actions skipped here are
481 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700482 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800483 }
henrik.lundina89ab962016-05-18 08:52:45 -0700484
485 if (muted) {
486 // TODO(henrik.lundin): We should be able to do better than this. But we
487 // will have to go through all the cases below where the audio samples may
488 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700489 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700490 }
kwiberg55b97fe2016-01-28 05:22:45 -0800491
kwiberg55b97fe2016-01-28 05:22:45 -0800492 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700493 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800494
kwiberg55b97fe2016-01-28 05:22:45 -0800495 {
496 // Pass the audio buffers to an optional sink callback, before applying
497 // scaling/panning, as that applies to the mix operation.
498 // External recipients of the audio (e.g. via AudioTrack), will do their
499 // own mixing/dynamic processing.
500 rtc::CritScope cs(&_callbackCritSect);
501 if (audio_sink_) {
502 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700503 audio_frame->data(), audio_frame->samples_per_channel_,
504 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
505 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800506 audio_sink_->OnData(data);
507 }
508 }
509
510 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800511 {
512 rtc::CritScope cs(&volume_settings_critsect_);
513 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800514 }
515
516 // Output volume scaling
517 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800518 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700519 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800520 }
521
kwiberg55b97fe2016-01-28 05:22:45 -0800522 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700523 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700524 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700525 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700526 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800527
solenberg2397b9a2017-09-22 06:48:10 -0700528 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800529 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700530 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800531 }
532
533 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700534 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800535
536 // Compute elapsed time.
537 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700538 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
539 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800540 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700541 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800542
niklase@google.com470e71d2011-07-07 08:21:25 +0000543 {
kwiberg55b97fe2016-01-28 05:22:45 -0800544 rtc::CritScope lock(&ts_stats_lock_);
545 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700546 audio_frame->ntp_time_ms_ =
547 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800548 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700549 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800550 // Compute |capture_start_ntp_time_ms_| so that
551 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
552 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700553 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000554 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000555 }
kwiberg55b97fe2016-01-28 05:22:45 -0800556 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000557
Henrik Lundin9bde6b72017-11-02 15:01:56 +0100558 {
559 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
560 rtc::CritScope lock(&video_sync_lock_);
561 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
562 jitter_buffer_delay + playout_delay_ms_);
563 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
564 jitter_buffer_delay);
565 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
566 playout_delay_ms_);
567 }
568
solenberg2397b9a2017-09-22 06:48:10 -0700569 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
570 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000571}
572
solenberg2397b9a2017-09-22 06:48:10 -0700573int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800574 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700575 return std::max(audio_coding_->ReceiveFrequency(),
576 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000577}
578
henrikaec6fbd22017-03-31 05:43:36 -0700579int32_t Channel::CreateChannel(Channel*& channel,
580 int32_t channelId,
581 uint32_t instanceId,
582 const VoEBase::ChannelConfig& config) {
solenberg88499ec2016-09-07 07:34:41 -0700583 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800584 if (channel == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_ERROR) << "unable to allocate memory for new channel";
kwiberg55b97fe2016-01-28 05:22:45 -0800586 return -1;
587 }
588 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000589}
590
pbos@webrtc.org92135212013-05-14 08:31:39 +0000591Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000592 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700593 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800594 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100595 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700596 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800597 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100598 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800599 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100600 rtp_receive_statistics_(
601 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
602 rtp_receiver_(
603 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100604 this,
605 this,
606 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700607 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100608 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100609 _timeStamp(0), // This is just an offset, RTP module will add it's own
610 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100611 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100612 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100613 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100614 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100615 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
616 capture_start_rtp_time_stamp_(-1),
617 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100618 _moduleProcessThreadPtr(NULL),
619 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100620 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700621 input_mute_(false),
622 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100623 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100624 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800625 transport_overhead_per_packet_(0),
626 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100627 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100628 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100629 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700630 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800631 feedback_observer_proxy_(new TransportFeedbackProxy()),
632 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700633 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200634 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
635 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700636 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700637 use_twcc_plr_for_ana_(
638 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
solenberg88499ec2016-09-07 07:34:41 -0700639 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700640 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800641 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200642
kwiberg55b97fe2016-01-28 05:22:45 -0800643 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000644
kwiberg55b97fe2016-01-28 05:22:45 -0800645 RtpRtcp::Configuration configuration;
646 configuration.audio = true;
647 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800648 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800649 configuration.receive_statistics = rtp_receive_statistics_.get();
650 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800651 if (pacing_enabled_) {
652 configuration.paced_sender = rtp_packet_sender_proxy_.get();
653 configuration.transport_sequence_number_allocator =
654 seq_num_allocator_proxy_.get();
655 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
656 }
ivoc14d5dbe2016-07-04 07:06:55 -0700657 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800658 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200659 configuration.retransmission_rate_limiter =
660 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000661
kwiberg55b97fe2016-01-28 05:22:45 -0800662 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100663 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000664}
665
kwiberg55b97fe2016-01-28 05:22:45 -0800666Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700667 RTC_DCHECK(!channel_state_.Get().sending);
668 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000669}
670
kwiberg55b97fe2016-01-28 05:22:45 -0800671int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700672 RTC_DCHECK(construction_thread_.CalledOnValidThread());
niklase@google.com470e71d2011-07-07 08:21:25 +0000673
kwiberg55b97fe2016-01-28 05:22:45 -0800674 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000675
kwiberg55b97fe2016-01-28 05:22:45 -0800676 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000677
solenberg1c239d42017-09-29 06:00:28 -0700678 if (_moduleProcessThreadPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100679 RTC_LOG(LS_ERROR)
680 << "Channel::Init() must call SetEngineInformation() first";
kwiberg55b97fe2016-01-28 05:22:45 -0800681 return -1;
682 }
683
684 // --- Add modules to process thread (for periodic schedulation)
685
tommidea489f2017-03-03 03:20:24 -0800686 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800687
688 // --- ACM initialization
689
690 if (audio_coding_->InitializeReceiver() == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100691 RTC_LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800692 return -1;
693 }
694
695 // --- RTP/RTCP module initialization
696
697 // Ensure that RTCP is enabled by default for the created channel.
698 // Note that, the module will keep generating RTCP until it is explicitly
699 // disabled by the user.
700 // After StopListen (when no sockets exists), RTCP packets will no longer
701 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700702 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800703 // RTCP is enabled by default.
704 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
705 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800706 if (audio_coding_->RegisterTransportCallback(this) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100707 RTC_LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800708 return -1;
709 }
710
kwiberg1c07c702017-03-27 07:15:49 -0700711 return 0;
712}
713
tommi0a2391f2017-03-21 02:31:51 -0700714void Channel::Terminate() {
715 RTC_DCHECK(construction_thread_.CalledOnValidThread());
716 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700717 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
718
719 StopSend();
720 StopPlayout();
721
tommi0a2391f2017-03-21 02:31:51 -0700722 // The order to safely shutdown modules in a channel is:
723 // 1. De-register callbacks in modules
724 // 2. De-register modules in process thread
725 // 3. Destroy modules
726 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100727 RTC_LOG(LS_WARNING)
728 << "Terminate() failed to de-register transport callback"
729 << " (Audio coding module)";
tommi0a2391f2017-03-21 02:31:51 -0700730 }
731
tommi0a2391f2017-03-21 02:31:51 -0700732 // De-register modules in process thread
733 if (_moduleProcessThreadPtr)
734 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
735
736 // End of modules shutdown
737}
738
solenberg1c239d42017-09-29 06:00:28 -0700739int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800740 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700741 rtc::TaskQueue* encoder_queue) {
742 RTC_DCHECK(encoder_queue);
743 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800744 _moduleProcessThreadPtr = &moduleProcessThread;
745 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700746 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800747 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000748}
749
kwibergb7f89d62016-02-17 10:04:18 -0800750void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800751 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800752 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100753}
754
ossu29b1a8d2016-06-13 07:34:51 -0700755const rtc::scoped_refptr<AudioDecoderFactory>&
756Channel::GetAudioDecoderFactory() const {
757 return decoder_factory_;
758}
759
kwiberg55b97fe2016-01-28 05:22:45 -0800760int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800761 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000762 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800763 }
764
kwiberg55b97fe2016-01-28 05:22:45 -0800765 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800766
767 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000768}
769
kwiberg55b97fe2016-01-28 05:22:45 -0800770int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800771 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000772 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800773 }
774
kwiberg55b97fe2016-01-28 05:22:45 -0800775 channel_state_.SetPlaying(false);
776 _outputAudioLevel.Clear();
777
778 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000779}
780
kwiberg55b97fe2016-01-28 05:22:45 -0800781int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800782 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000783 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800784 }
785 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700786 {
787 // It is now OK to start posting tasks to the encoder task queue.
788 rtc::CritScope cs(&encoder_queue_lock_);
789 encoder_queue_is_active_ = true;
790 }
solenberg08b19df2017-02-15 00:42:31 -0800791 // Resume the previous sequence number which was reset by StopSend(). This
792 // needs to be done before |sending| is set to true on the RTP/RTCP module.
793 if (send_sequence_number_) {
794 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
795 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100796 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800797 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100798 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100799 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800800 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000801 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800802 return -1;
803 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000804
kwiberg55b97fe2016-01-28 05:22:45 -0800805 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000806}
807
henrikaec6fbd22017-03-31 05:43:36 -0700808void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800809 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700810 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800811 }
812 channel_state_.SetSending(false);
813
henrikaec6fbd22017-03-31 05:43:36 -0700814 // Post a task to the encoder thread which sets an event when the task is
815 // executed. We know that no more encoding tasks will be added to the task
816 // queue for this channel since sending is now deactivated. It means that,
817 // if we wait for the event to bet set, we know that no more pending tasks
818 // exists and it is therfore guaranteed that the task queue will never try
819 // to acccess and invalid channel object.
820 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700821
henrikaec6fbd22017-03-31 05:43:36 -0700822 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700823 {
824 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
825 // than this final "flush task" to be posted on the queue.
826 rtc::CritScope cs(&encoder_queue_lock_);
827 encoder_queue_is_active_ = false;
828 encoder_queue_->PostTask([&flush]() { flush.Set(); });
829 }
henrikaec6fbd22017-03-31 05:43:36 -0700830 flush.Wait(rtc::Event::kForever);
831
kwiberg55b97fe2016-01-28 05:22:45 -0800832 // Store the sequence number to be able to pick up the same sequence for
833 // the next StartSend(). This is needed for restarting device, otherwise
834 // it might cause libSRTP to complain about packets being replayed.
835 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
836 // CL is landed. See issue
837 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
838 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
839
840 // Reset sending SSRC and sequence number and triggers direct transmission
841 // of RTCP BYE
842 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100843 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800844 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100845 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000846}
847
ossu1ffbd6c2017-04-06 12:05:04 -0700848bool Channel::SetEncoder(int payload_type,
849 std::unique_ptr<AudioEncoder> encoder) {
850 RTC_DCHECK_GE(payload_type, 0);
851 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700852 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
853 // one for for us to keep track of sample rate and number of channels, etc.
854
855 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
856 // as well as some other things, so we collect this info and send it along.
857 CodecInst rtp_codec;
858 rtp_codec.pltype = payload_type;
859 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
860 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700861 // Seems unclear if it should be clock rate or sample rate. CodecInst
862 // supposedly carries the sample rate, but only clock rate seems sensible to
863 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700864 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
865 rtp_codec.pacsize = rtc::CheckedDivExact(
866 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
867 100);
868 rtp_codec.channels = encoder->NumChannels();
869 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700870
Karl Wiberg88182372017-10-17 01:02:46 +0200871 cached_encoder_props_.emplace(
872 EncoderProps{encoder->SampleRateHz(), encoder->NumChannels()});
ossu76d29f92017-06-09 07:30:13 -0700873
874 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700875 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700876 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100877 RTC_LOG(LS_ERROR)
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200878 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700879 return false;
880 }
881 }
882
883 audio_coding_->SetEncoder(std::move(encoder));
884 return true;
885}
886
ossu20a4b3f2017-04-27 02:08:52 -0700887void Channel::ModifyEncoder(
888 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
889 audio_coding_->ModifyEncoder(modifier);
890}
891
Karl Wiberg88182372017-10-17 01:02:46 +0200892rtc::Optional<Channel::EncoderProps> Channel::GetEncoderProps() const {
893 return cached_encoder_props_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000894}
895
kwiberg55b97fe2016-01-28 05:22:45 -0800896int32_t Channel::GetRecCodec(CodecInst& codec) {
897 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +0000898}
899
minyue78b4d562016-11-30 04:47:39 -0800900void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -0700901 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -0800902 if (*encoder) {
903 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -0800904 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -0800905 }
906 });
michaelt566d8202017-01-12 10:17:38 -0800907 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +0200908}
909
elad.alond12a8e12017-03-23 11:04:48 -0700910void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
911 if (!use_twcc_plr_for_ana_)
912 return;
minyue7e304322016-10-12 05:00:55 -0700913 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -0700914 if (*encoder) {
915 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
916 }
917 });
918}
919
elad.alondadb4dc2017-03-23 15:29:50 -0700920void Channel::OnRecoverableUplinkPacketLossRate(
921 float recoverable_packet_loss_rate) {
922 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
923 if (*encoder) {
924 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
925 recoverable_packet_loss_rate);
926 }
927 });
928}
929
elad.alond12a8e12017-03-23 11:04:48 -0700930void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
931 if (use_twcc_plr_for_ana_)
932 return;
933 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
934 if (*encoder) {
935 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
936 }
minyue7e304322016-10-12 05:00:55 -0700937 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000938}
939
kwiberg1c07c702017-03-27 07:15:49 -0700940void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
941 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
942 audio_coding_->SetReceiveCodecs(codecs);
943}
944
minyue7e304322016-10-12 05:00:55 -0700945bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
946 bool success = false;
947 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
948 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -0700949 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
950 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -0700951 }
952 });
953 return success;
954}
955
956void Channel::DisableAudioNetworkAdaptor() {
957 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
958 if (*encoder)
959 (*encoder)->DisableAudioNetworkAdaptor();
960 });
961}
962
963void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
964 int max_frame_length_ms) {
965 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
966 if (*encoder) {
967 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
968 max_frame_length_ms);
969 }
970 });
971}
972
solenberg1c239d42017-09-29 06:00:28 -0700973void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -0800974 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -0700975 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +0000976}
977
nisse657bab22017-02-21 06:28:10 -0800978void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -0800979 RTPHeader header;
980 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -0700981
982 // Store playout timestamp for the received RTP packet
983 UpdatePlayoutTimestamp(false);
984
985 header.payload_type_frequency =
986 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
987 if (header.payload_type_frequency >= 0) {
988 bool in_order = IsPacketInOrder(header);
989 rtp_receive_statistics_->IncomingPacket(
990 header, packet.size(), IsPacketRetransmitted(header, in_order));
991 rtp_payload_registry_->SetIncomingPayloadType(header);
992
Niels Möller22ec9522017-10-05 08:39:15 +0200993 ReceivePacket(packet.data(), packet.size(), header);
solenberg946d8862017-09-21 04:02:53 -0700994 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000995}
996
997bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000998 size_t packet_length,
Niels Möller22ec9522017-10-05 08:39:15 +0200999 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001000 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001001 assert(packet_length >= header.headerLength);
1002 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001003 const auto pl =
1004 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1005 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001006 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001007 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001008 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Niels Möller22ec9522017-10-05 08:39:15 +02001009 pl->typeSpecific);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001010}
1011
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001012bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1013 StreamStatistician* statistician =
1014 rtp_receive_statistics_->GetStatistician(header.ssrc);
1015 if (!statistician)
1016 return false;
1017 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001018}
1019
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001020bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1021 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001022 StreamStatistician* statistician =
1023 rtp_receive_statistics_->GetStatistician(header.ssrc);
1024 if (!statistician)
1025 return false;
1026 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001027 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001028 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001029 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001030}
1031
mflodman3d7db262016-04-29 00:57:13 -07001032int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001033 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001034 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001035
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001036 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001037 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001038
Minyue2013aec2015-05-13 14:14:42 +02001039 int64_t rtt = GetRTT(true);
1040 if (rtt == 0) {
1041 // Waiting for valid RTT.
1042 return 0;
1043 }
Erik Språng737336d2016-07-29 12:59:36 +02001044
1045 int64_t nack_window_ms = rtt;
1046 if (nack_window_ms < kMinRetransmissionWindowMs) {
1047 nack_window_ms = kMinRetransmissionWindowMs;
1048 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1049 nack_window_ms = kMaxRetransmissionWindowMs;
1050 }
1051 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1052
minyue7e304322016-10-12 05:00:55 -07001053 // Invoke audio encoders OnReceivedRtt().
1054 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1055 if (*encoder)
1056 (*encoder)->OnReceivedRtt(rtt);
1057 });
1058
Minyue2013aec2015-05-13 14:14:42 +02001059 uint32_t ntp_secs = 0;
1060 uint32_t ntp_frac = 0;
1061 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001062 if (0 !=
1063 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1064 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001065 // Waiting for RTCP.
1066 return 0;
1067 }
1068
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001069 {
tommi31fc21f2016-01-21 10:37:37 -08001070 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001071 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001072 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001073 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001074}
1075
solenberg8d73f8c2017-03-08 01:52:20 -08001076int Channel::GetSpeechOutputLevel() const {
1077 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001078}
1079
solenberg8d73f8c2017-03-08 01:52:20 -08001080int Channel::GetSpeechOutputLevelFullRange() const {
1081 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001082}
1083
zsteine76bd3a2017-07-14 12:17:49 -07001084double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001085 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001086}
1087
1088double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001089 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001090}
1091
solenberg8d73f8c2017-03-08 01:52:20 -08001092void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001093 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001094 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001095}
1096
solenberg1c2af8e2016-03-24 10:36:00 -07001097bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001098 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001099 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001100}
1101
solenberg8d73f8c2017-03-08 01:52:20 -08001102void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001103 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001104 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001105}
1106
solenberg8842c3e2016-03-11 03:06:41 -08001107int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001108 RTC_DCHECK_LE(0, event);
1109 RTC_DCHECK_GE(255, event);
1110 RTC_DCHECK_LE(0, duration_ms);
1111 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001112 if (!Sending()) {
1113 return -1;
1114 }
solenberg8842c3e2016-03-11 03:06:41 -08001115 if (_rtpRtcpModule->SendTelephoneEventOutband(
1116 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001117 RTC_LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001118 return -1;
1119 }
1120 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001121}
1122
solenbergffbbcac2016-11-17 05:25:37 -08001123int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1124 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001125 RTC_DCHECK_LE(0, payload_type);
1126 RTC_DCHECK_GE(127, payload_type);
1127 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001128 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001129 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001130 memcpy(codec.plname, "telephone-event", 16);
1131 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1132 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1133 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001134 RTC_LOG(LS_ERROR)
1135 << "SetSendTelephoneEventPayloadType() failed to register "
1136 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001137 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001138 }
kwiberg55b97fe2016-01-28 05:22:45 -08001139 }
kwiberg55b97fe2016-01-28 05:22:45 -08001140 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001141}
1142
kwiberg55b97fe2016-01-28 05:22:45 -08001143int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001144 if (channel_state_.Get().sending) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001145 RTC_LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001146 return -1;
1147 }
1148 _rtpRtcpModule->SetSSRC(ssrc);
1149 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001150}
1151
kwiberg55b97fe2016-01-28 05:22:45 -08001152int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1153 ssrc = rtp_receiver_->SSRC();
1154 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001155}
1156
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001157int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001158 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001159 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001160}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001161
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001162int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1163 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001164 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1165 if (enable &&
1166 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1167 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001168 return -1;
1169 }
1170 return 0;
1171}
1172
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001173void Channel::EnableSendTransportSequenceNumber(int id) {
1174 int ret =
1175 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1176 RTC_DCHECK_EQ(0, ret);
1177}
1178
stefan3313ec92016-01-21 06:32:43 -08001179void Channel::EnableReceiveTransportSequenceNumber(int id) {
1180 rtp_header_parser_->DeregisterRtpHeaderExtension(
1181 kRtpExtensionTransportSequenceNumber);
1182 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1183 kRtpExtensionTransportSequenceNumber, id);
1184 RTC_DCHECK(ret);
1185}
1186
stefanbba9dec2016-02-01 04:39:55 -08001187void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001188 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001189 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001190 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1191 TransportFeedbackObserver* transport_feedback_observer =
1192 transport->transport_feedback_observer();
1193 PacketRouter* packet_router = transport->packet_router();
1194
stefanbba9dec2016-02-01 04:39:55 -08001195 RTC_DCHECK(rtp_packet_sender);
1196 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001197 RTC_DCHECK(packet_router);
1198 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001199 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001200 feedback_observer_proxy_->SetTransportFeedbackObserver(
1201 transport_feedback_observer);
1202 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1203 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1204 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001205 constexpr bool remb_candidate = false;
1206 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001207 packet_router_ = packet_router;
1208}
1209
stefanbba9dec2016-02-01 04:39:55 -08001210void Channel::RegisterReceiverCongestionControlObjects(
1211 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001212 RTC_DCHECK(packet_router);
1213 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001214 constexpr bool remb_candidate = false;
1215 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001216 packet_router_ = packet_router;
1217}
1218
nissefdbfdc92017-03-31 05:44:52 -07001219void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001220 RTC_DCHECK(packet_router_);
1221 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001222 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001223 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1224 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001225 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001226 packet_router_ = nullptr;
1227 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1228}
1229
nissefdbfdc92017-03-31 05:44:52 -07001230void Channel::ResetReceiverCongestionControlObjects() {
1231 RTC_DCHECK(packet_router_);
1232 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1233 packet_router_ = nullptr;
1234}
1235
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001236void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001237 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001238}
1239
kwiberg55b97fe2016-01-28 05:22:45 -08001240int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001241 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001242 RTC_LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001243 return -1;
1244 }
1245 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001246}
1247
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001248int Channel::GetRemoteRTCPReportBlocks(
1249 std::vector<ReportBlock>* report_blocks) {
1250 if (report_blocks == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001251 RTC_LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001252 return -1;
1253 }
1254
1255 // Get the report blocks from the latest received RTCP Sender or Receiver
1256 // Report. Each element in the vector contains the sender's SSRC and a
1257 // report block according to RFC 3550.
1258 std::vector<RTCPReportBlock> rtcp_report_blocks;
1259 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001260 return -1;
1261 }
1262
1263 if (rtcp_report_blocks.empty())
1264 return 0;
1265
1266 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1267 for (; it != rtcp_report_blocks.end(); ++it) {
1268 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001269 report_block.sender_SSRC = it->sender_ssrc;
1270 report_block.source_SSRC = it->source_ssrc;
1271 report_block.fraction_lost = it->fraction_lost;
1272 report_block.cumulative_num_packets_lost = it->packets_lost;
1273 report_block.extended_highest_sequence_number =
1274 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001275 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001276 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1277 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001278 report_blocks->push_back(report_block);
1279 }
1280 return 0;
1281}
1282
kwiberg55b97fe2016-01-28 05:22:45 -08001283int Channel::GetRTPStatistics(CallStatistics& stats) {
1284 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001285
kwiberg55b97fe2016-01-28 05:22:45 -08001286 // The jitter statistics is updated for each received RTP packet and is
1287 // based on received packets.
1288 RtcpStatistics statistics;
1289 StreamStatistician* statistician =
1290 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001291 if (statistician) {
1292 statistician->GetStatistics(&statistics,
1293 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001294 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001295
kwiberg55b97fe2016-01-28 05:22:45 -08001296 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001297 stats.cumulativeLost = statistics.packets_lost;
1298 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001299 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001300
kwiberg55b97fe2016-01-28 05:22:45 -08001301 // --- RTT
1302 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001303
kwiberg55b97fe2016-01-28 05:22:45 -08001304 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001305
kwiberg55b97fe2016-01-28 05:22:45 -08001306 size_t bytesSent(0);
1307 uint32_t packetsSent(0);
1308 size_t bytesReceived(0);
1309 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001310
kwiberg55b97fe2016-01-28 05:22:45 -08001311 if (statistician) {
1312 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1313 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001314
kwiberg55b97fe2016-01-28 05:22:45 -08001315 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001316 RTC_LOG(LS_WARNING)
1317 << "GetRTPStatistics() failed to retrieve RTP datacounters"
1318 << " => output will not be complete";
kwiberg55b97fe2016-01-28 05:22:45 -08001319 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001320
kwiberg55b97fe2016-01-28 05:22:45 -08001321 stats.bytesSent = bytesSent;
1322 stats.packetsSent = packetsSent;
1323 stats.bytesReceived = bytesReceived;
1324 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001325
kwiberg55b97fe2016-01-28 05:22:45 -08001326 // --- Timestamps
1327 {
1328 rtc::CritScope lock(&ts_stats_lock_);
1329 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1330 }
1331 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001332}
1333
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001334void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1335 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001336 // If pacing is enabled we always store packets.
1337 if (!pacing_enabled_)
1338 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001339 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001340 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001341 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001342 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001343 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001344}
1345
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001346// Called when we are missing one or more packets.
1347int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001348 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1349}
1350
henrikaec6fbd22017-03-31 05:43:36 -07001351void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001352 // Avoid posting any new tasks if sending was already stopped in StopSend().
1353 rtc::CritScope cs(&encoder_queue_lock_);
1354 if (!encoder_queue_is_active_) {
1355 return;
1356 }
henrikaec6fbd22017-03-31 05:43:36 -07001357 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1358 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1359 // either into pool of frames or into the task itself.
1360 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001361 // Profile time between when the audio frame is added to the task queue and
1362 // when the task is actually executed.
1363 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001364 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1365 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001366}
1367
henrikaec6fbd22017-03-31 05:43:36 -07001368void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1369 int sample_rate,
1370 size_t number_of_frames,
1371 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001372 // Avoid posting as new task if sending was already stopped in StopSend().
1373 rtc::CritScope cs(&encoder_queue_lock_);
1374 if (!encoder_queue_is_active_) {
1375 return;
1376 }
henrikaec6fbd22017-03-31 05:43:36 -07001377 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
Karl Wiberg88182372017-10-17 01:02:46 +02001378 const auto props = GetEncoderProps();
1379 RTC_CHECK(props);
1380 audio_frame->sample_rate_hz_ = std::min(props->sample_rate_hz, sample_rate);
1381 audio_frame->num_channels_ =
1382 std::min(props->num_channels, number_of_channels);
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001383 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001384 sample_rate, &input_resampler_, audio_frame.get());
1385 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1386 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001387}
1388
henrikaec6fbd22017-03-31 05:43:36 -07001389void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1390 RTC_DCHECK_RUN_ON(encoder_queue_);
1391 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1392 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001393
henrika45802172017-09-28 09:39:34 +02001394 // Measure time between when the audio frame is added to the task queue and
1395 // when the task is actually executed. Goal is to keep track of unwanted
1396 // extra latency added by the task queue.
1397 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1398 audio_input->ElapsedProfileTimeMs());
1399
henrikaec6fbd22017-03-31 05:43:36 -07001400 bool is_muted = InputMute();
1401 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001402
kwiberg55b97fe2016-01-28 05:22:45 -08001403 if (_includeAudioLevelIndication) {
1404 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001405 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001406 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001407 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001408 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001409 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001410 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001411 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001412 }
kwiberg55b97fe2016-01-28 05:22:45 -08001413 }
solenberg1c2af8e2016-03-24 10:36:00 -07001414 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001415
henrikaec6fbd22017-03-31 05:43:36 -07001416 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001417
kwiberg55b97fe2016-01-28 05:22:45 -08001418 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001419 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001420 // This call will trigger AudioPacketizationCallback::SendData if encoding
1421 // is done and payload is ready for packetization and transmission.
1422 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001423 if (audio_coding_->Add10MsData(*audio_input) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001424 RTC_LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
henrikaec6fbd22017-03-31 05:43:36 -07001425 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001426 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001427
henrikaec6fbd22017-03-31 05:43:36 -07001428 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001429}
1430
solenberg7602aab2016-11-14 11:30:07 -08001431void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1432 RTC_DCHECK(!channel.channel() ||
1433 channel.channel()->ChannelId() != _channelId);
1434 rtc::CritScope lock(&assoc_send_channel_lock_);
1435 associate_send_channel_ = channel;
1436}
1437
Minyue2013aec2015-05-13 14:14:42 +02001438void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001439 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001440 Channel* channel = associate_send_channel_.channel();
1441 if (channel && channel->ChannelId() == channel_id) {
1442 // If this channel is associated with a send channel of the specified
1443 // Channel ID, disassociate with it.
1444 ChannelOwner ref(NULL);
1445 associate_send_channel_ = ref;
1446 }
1447}
1448
ivoc14d5dbe2016-07-04 07:06:55 -07001449void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1450 event_log_proxy_->SetEventLog(event_log);
1451}
1452
michaelt9332b7d2016-11-30 07:51:13 -08001453void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1454 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1455}
1456
nisse284542b2017-01-10 08:58:32 -08001457void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001458 size_t overhead_per_packet =
1459 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001460 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1461 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001462 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001463 }
1464 });
1465}
1466
1467void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001468 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001469 transport_overhead_per_packet_ = transport_overhead_per_packet;
1470 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001471}
1472
hbos3fd31fe2017-02-28 05:43:16 -08001473// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001474void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001475 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001476 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1477 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001478}
1479
kwiberg55b97fe2016-01-28 05:22:45 -08001480int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1481 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001482}
1483
wu@webrtc.org24301a62013-12-13 19:17:43 +00001484void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1485 audio_coding_->GetDecodingCallStatistics(stats);
1486}
1487
ivoce1198e02017-09-08 08:13:19 -07001488ANAStats Channel::GetANAStatistics() const {
1489 return audio_coding_->GetANAStats();
1490}
1491
solenberg358057b2015-11-27 10:46:42 -08001492uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001493 rtc::CritScope lock(&video_sync_lock_);
1494 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001495}
1496
kwiberg55b97fe2016-01-28 05:22:45 -08001497int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001498 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1499 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001500 RTC_LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001501 return -1;
1502 }
1503 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001504 RTC_LOG(LS_ERROR)
1505 << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001506 return -1;
1507 }
1508 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001509}
1510
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001511int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001512 uint32_t playout_timestamp_rtp = 0;
1513 {
tommi31fc21f2016-01-21 10:37:37 -08001514 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001515 playout_timestamp_rtp = playout_timestamp_rtp_;
1516 }
kwiberg55b97fe2016-01-28 05:22:45 -08001517 if (playout_timestamp_rtp == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001518 RTC_LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001519 return -1;
1520 }
deadbeef74375882015-08-13 12:09:10 -07001521 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001522 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001523}
1524
kwiberg55b97fe2016-01-28 05:22:45 -08001525int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1526 RtpReceiver** rtp_receiver) const {
1527 *rtpRtcpModule = _rtpRtcpModule.get();
1528 *rtp_receiver = rtp_receiver_.get();
1529 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001530}
1531
deadbeef74375882015-08-13 12:09:10 -07001532void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001533 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001534
henrik.lundin96bd5022016-04-06 04:13:56 -07001535 if (!jitter_buffer_playout_timestamp_) {
1536 // This can happen if this channel has not received any RTP packets. In
1537 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001538 return;
1539 }
1540
1541 uint16_t delay_ms = 0;
1542 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001543 RTC_LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1544 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001545 return;
1546 }
1547
henrik.lundin96bd5022016-04-06 04:13:56 -07001548 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1549 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001550
1551 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001552 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001553
deadbeef74375882015-08-13 12:09:10 -07001554 {
tommi31fc21f2016-01-21 10:37:37 -08001555 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001556 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001557 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001558 }
1559 playout_delay_ms_ = delay_ms;
1560 }
1561}
1562
kwiberg55b97fe2016-01-28 05:22:45 -08001563void Channel::RegisterReceiveCodecsToRTPModule() {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001564 // TODO(kwiberg): Iterate over the factory's supported codecs instead?
1565 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001566 for (int idx = 0; idx < nSupportedCodecs; idx++) {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001567 CodecInst codec;
1568 if (audio_coding_->Codec(idx, &codec) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001569 RTC_LOG(LS_WARNING) << "Unable to register codec #" << idx
1570 << " for RTP/RTCP receiver.";
Karl Wibergc62f6c72017-10-04 12:38:53 +02001571 continue;
1572 }
1573 const SdpAudioFormat format = CodecInstToSdp(codec);
1574 if (!decoder_factory_->IsSupportedDecoder(format) ||
1575 rtp_receiver_->RegisterReceivePayload(codec.pltype, format) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001576 RTC_LOG(LS_WARNING) << "Unable to register " << format
1577 << " for RTP/RTCP receiver.";
niklase@google.com470e71d2011-07-07 08:21:25 +00001578 }
kwiberg55b97fe2016-01-28 05:22:45 -08001579 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001580}
1581
kwiberg55b97fe2016-01-28 05:22:45 -08001582int Channel::SetSendRtpHeaderExtension(bool enable,
1583 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001584 unsigned char id) {
1585 int error = 0;
1586 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1587 if (enable) {
1588 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1589 }
1590 return error;
1591}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001592
ossue280cde2016-10-12 11:04:10 -07001593int Channel::GetRtpTimestampRateHz() const {
1594 const auto format = audio_coding_->ReceiveFormat();
1595 // Default to the playout frequency if we've not gotten any packets yet.
1596 // TODO(ossu): Zero clockrate can only happen if we've added an external
1597 // decoder for a format we don't support internally. Remove once that way of
1598 // adding decoders is gone!
1599 return (format && format->clockrate_hz != 0)
1600 ? format->clockrate_hz
1601 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001602}
1603
Minyue2013aec2015-05-13 14:14:42 +02001604int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001605 RtcpMode method = _rtpRtcpModule->RTCP();
1606 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001607 return 0;
1608 }
1609 std::vector<RTCPReportBlock> report_blocks;
1610 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001611
1612 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001613 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001614 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001615 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001616 Channel* channel = associate_send_channel_.channel();
1617 // Tries to get RTT from an associated channel. This is important for
1618 // receive-only channels.
1619 if (channel) {
1620 // To prevent infinite recursion and deadlock, calling GetRTT of
1621 // associate channel should always use "false" for argument:
1622 // |allow_associate_channel|.
1623 rtt = channel->GetRTT(false);
1624 }
1625 }
1626 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001627 }
1628
1629 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1630 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1631 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001632 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001633 break;
1634 }
1635 if (it == report_blocks.end()) {
1636 // We have not received packets with SSRC matching the report blocks.
1637 // To calculate RTT we try with the SSRC of the first report block.
1638 // This is very important for send-only channels where we don't know
1639 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001640 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001641 }
Minyue2013aec2015-05-13 14:14:42 +02001642
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001643 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001644 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001645 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001646 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1647 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001648 return 0;
1649 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001650 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001651}
1652
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001653} // namespace voe
1654} // namespace webrtc