blob: c870ece7fed7a80e91167fabc1940f9f12c2ce4e [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
kwibergc8d071e2016-04-06 12:22:38 -070060} // namespace
61
solenberg8842c3e2016-03-11 03:06:41 -080062const int kTelephoneEventAttenuationdB = 10;
63
ivoc14d5dbe2016-07-04 07:06:55 -070064class RtcEventLogProxy final : public webrtc::RtcEventLog {
65 public:
66 RtcEventLogProxy() : event_log_(nullptr) {}
67
Zhi Huang33c5c7f2017-11-17 20:59:29 +000068 bool StartLogging(std::unique_ptr<RtcEventLogOutput> output) override {
Elad Alon83ccca12017-10-04 13:18:26 +020069 RTC_NOTREACHED();
70 return false;
71 }
72
ivoc14d5dbe2016-07-04 07:06:55 -070073 void StopLogging() override { RTC_NOTREACHED(); }
74
Elad Alon4a87e1c2017-10-03 16:11:34 +020075 void Log(std::unique_ptr<RtcEvent> event) override {
76 rtc::CritScope lock(&crit_);
77 if (event_log_) {
78 event_log_->Log(std::move(event));
79 }
80 }
81
ivoc14d5dbe2016-07-04 07:06:55 -070082 void SetEventLog(RtcEventLog* event_log) {
83 rtc::CritScope lock(&crit_);
84 event_log_ = event_log;
85 }
86
87 private:
88 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -070089 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -070090 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
91};
92
michaelt9332b7d2016-11-30 07:51:13 -080093class RtcpRttStatsProxy final : public RtcpRttStats {
94 public:
95 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
96
97 void OnRttUpdate(int64_t rtt) override {
98 rtc::CritScope lock(&crit_);
99 if (rtcp_rtt_stats_)
100 rtcp_rtt_stats_->OnRttUpdate(rtt);
101 }
102
103 int64_t LastProcessedRtt() const override {
104 rtc::CritScope lock(&crit_);
105 if (!rtcp_rtt_stats_)
106 return 0;
107 return rtcp_rtt_stats_->LastProcessedRtt();
108 }
109
110 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
111 rtc::CritScope lock(&crit_);
112 rtcp_rtt_stats_ = rtcp_rtt_stats;
113 }
114
115 private:
116 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700117 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800118 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
119};
120
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100121class TransportFeedbackProxy : public TransportFeedbackObserver {
122 public:
123 TransportFeedbackProxy() : feedback_observer_(nullptr) {
124 pacer_thread_.DetachFromThread();
125 network_thread_.DetachFromThread();
126 }
127
128 void SetTransportFeedbackObserver(
129 TransportFeedbackObserver* feedback_observer) {
130 RTC_DCHECK(thread_checker_.CalledOnValidThread());
131 rtc::CritScope lock(&crit_);
132 feedback_observer_ = feedback_observer;
133 }
134
135 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700136 void AddPacket(uint32_t ssrc,
137 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100138 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800139 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100140 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
141 rtc::CritScope lock(&crit_);
142 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700143 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100144 }
philipel8aadd502017-02-23 02:56:13 -0800145
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100146 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
147 RTC_DCHECK(network_thread_.CalledOnValidThread());
148 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700149 if (feedback_observer_)
150 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200151 }
elad.alonf9490002017-03-06 05:32:21 -0800152 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200153 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800154 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100155 }
156
157 private:
158 rtc::CriticalSection crit_;
159 rtc::ThreadChecker thread_checker_;
160 rtc::ThreadChecker pacer_thread_;
161 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700162 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100163};
164
165class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
166 public:
167 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
168 pacer_thread_.DetachFromThread();
169 }
170
171 void SetSequenceNumberAllocator(
172 TransportSequenceNumberAllocator* seq_num_allocator) {
173 RTC_DCHECK(thread_checker_.CalledOnValidThread());
174 rtc::CritScope lock(&crit_);
175 seq_num_allocator_ = seq_num_allocator;
176 }
177
178 // Implements TransportSequenceNumberAllocator.
179 uint16_t AllocateSequenceNumber() override {
180 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
181 rtc::CritScope lock(&crit_);
182 if (!seq_num_allocator_)
183 return 0;
184 return seq_num_allocator_->AllocateSequenceNumber();
185 }
186
187 private:
188 rtc::CriticalSection crit_;
189 rtc::ThreadChecker thread_checker_;
190 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700191 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100192};
193
194class RtpPacketSenderProxy : public RtpPacketSender {
195 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800196 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100197
198 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
199 RTC_DCHECK(thread_checker_.CalledOnValidThread());
200 rtc::CritScope lock(&crit_);
201 rtp_packet_sender_ = rtp_packet_sender;
202 }
203
204 // Implements RtpPacketSender.
205 void InsertPacket(Priority priority,
206 uint32_t ssrc,
207 uint16_t sequence_number,
208 int64_t capture_time_ms,
209 size_t bytes,
210 bool retransmission) override {
211 rtc::CritScope lock(&crit_);
212 if (rtp_packet_sender_) {
213 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
214 capture_time_ms, bytes, retransmission);
215 }
216 }
217
Alex Narest78609d52017-10-20 10:37:47 +0200218 void SetAccountForAudioPackets(bool account_for_audio) override {
219 RTC_NOTREACHED();
220 }
221
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100222 private:
223 rtc::ThreadChecker thread_checker_;
224 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700225 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100226};
227
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000228class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000229 public:
stefan7de8d642017-02-07 07:14:08 -0800230 explicit VoERtcpObserver(Channel* owner)
231 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000232 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000233
stefan7de8d642017-02-07 07:14:08 -0800234 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
235 rtc::CritScope lock(&crit_);
236 bandwidth_observer_ = bandwidth_observer;
237 }
238
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000239 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800240 rtc::CritScope lock(&crit_);
241 if (bandwidth_observer_) {
242 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
243 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000244 }
245
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000246 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
247 int64_t rtt,
248 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800249 {
250 rtc::CritScope lock(&crit_);
251 if (bandwidth_observer_) {
252 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
253 now_ms);
254 }
255 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000256 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
257 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
258 // report for VoiceEngine?
259 if (report_blocks.empty())
260 return;
261
262 int fraction_lost_aggregate = 0;
263 int total_number_of_packets = 0;
264
265 // If receiving multiple report blocks, calculate the weighted average based
266 // on the number of packets a report refers to.
267 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
268 block_it != report_blocks.end(); ++block_it) {
269 // Find the previous extended high sequence number for this remote SSRC,
270 // to calculate the number of RTP packets this report refers to. Ignore if
271 // we haven't seen this SSRC before.
272 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700273 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000274 int number_of_packets = 0;
275 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700276 number_of_packets =
277 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000278 }
srte3e69e5c2017-08-09 06:13:45 -0700279 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000280 total_number_of_packets += number_of_packets;
281
srte3e69e5c2017-08-09 06:13:45 -0700282 extended_max_sequence_number_[block_it->source_ssrc] =
283 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000284 }
285 int weighted_fraction_lost = 0;
286 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800287 weighted_fraction_lost =
288 (fraction_lost_aggregate + total_number_of_packets / 2) /
289 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000290 }
elad.alond12a8e12017-03-23 11:04:48 -0700291 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000292 }
293
294 private:
295 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000296 // Maps remote side ssrc to extended highest sequence number received.
297 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800298 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700299 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000300};
301
henrikaec6fbd22017-03-31 05:43:36 -0700302class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
303 public:
304 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
305 Channel* channel)
306 : audio_frame_(std::move(audio_frame)), channel_(channel) {
307 RTC_DCHECK(channel_);
308 }
309
310 private:
311 bool Run() override {
312 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
313 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
314 return true;
315 }
316
317 std::unique_ptr<AudioFrame> audio_frame_;
318 Channel* const channel_;
319};
320
kwiberg55b97fe2016-01-28 05:22:45 -0800321int32_t Channel::SendData(FrameType frameType,
322 uint8_t payloadType,
323 uint32_t timeStamp,
324 const uint8_t* payloadData,
325 size_t payloadSize,
326 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700327 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800328 if (_includeAudioLevelIndication) {
329 // Store current audio level in the RTP/RTCP module.
330 // The level will be used in combination with voice-activity state
331 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800332 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800333 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000334
kwiberg55b97fe2016-01-28 05:22:45 -0800335 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
336 // packetization.
337 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700338 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800339 (FrameType&)frameType, payloadType, timeStamp,
340 // Leaving the time when this frame was
341 // received from the capture device as
342 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700343 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100344 RTC_LOG(LS_ERROR)
345 << "Channel::SendData() failed to send data to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800346 return -1;
347 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000348
kwiberg55b97fe2016-01-28 05:22:45 -0800349 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000350}
351
stefan1d8a5062015-10-02 03:39:33 -0700352bool Channel::SendRtp(const uint8_t* data,
353 size_t len,
354 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800355 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000356
kwiberg55b97fe2016-01-28 05:22:45 -0800357 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100358 RTC_LOG(LS_ERROR)
359 << "Channel::SendPacket() failed to send RTP packet due to"
360 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800361 return false;
362 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000363
kwiberg55b97fe2016-01-28 05:22:45 -0800364 uint8_t* bufferToSendPtr = (uint8_t*)data;
365 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000366
kwiberg55b97fe2016-01-28 05:22:45 -0800367 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100368 RTC_LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800369 return false;
370 }
371 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000372}
373
kwiberg55b97fe2016-01-28 05:22:45 -0800374bool Channel::SendRtcp(const uint8_t* data, size_t len) {
kwiberg55b97fe2016-01-28 05:22:45 -0800375 rtc::CritScope cs(&_callbackCritSect);
376 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100377 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() failed to send RTCP packet due to"
378 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800379 return false;
380 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000381
kwiberg55b97fe2016-01-28 05:22:45 -0800382 uint8_t* bufferToSendPtr = (uint8_t*)data;
383 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000384
kwiberg55b97fe2016-01-28 05:22:45 -0800385 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
386 if (n < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100387 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800388 return false;
389 }
390 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000391}
392
kwiberg55b97fe2016-01-28 05:22:45 -0800393void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -0800394 // Update ssrc so that NTP for AV sync can be updated.
395 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000396}
397
Peter Boströmac547a62015-09-17 23:03:57 +0200398void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200399 // TODO(saza): remove.
niklase@google.com470e71d2011-07-07 08:21:25 +0000400}
401
Karl Wibergc62f6c72017-10-04 12:38:53 +0200402int32_t Channel::OnInitializeDecoder(int payload_type,
403 const SdpAudioFormat& audio_format,
404 uint32_t rate) {
405 if (!audio_coding_->RegisterReceiveCodec(payload_type, audio_format)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100406 RTC_LOG(LS_WARNING) << "Channel::OnInitializeDecoder() invalid codec (pt="
407 << payload_type << ", " << audio_format
408 << ") received -1";
kwiberg55b97fe2016-01-28 05:22:45 -0800409 return -1;
410 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000411
kwiberg55b97fe2016-01-28 05:22:45 -0800412 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000413}
414
kwiberg55b97fe2016-01-28 05:22:45 -0800415int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
416 size_t payloadSize,
417 const WebRtcRTPHeader* rtpHeader) {
kwiberg55b97fe2016-01-28 05:22:45 -0800418 if (!channel_state_.Get().playing) {
419 // Avoid inserting into NetEQ when we are not playing. Count the
420 // packet as discarded.
niklase@google.com470e71d2011-07-07 08:21:25 +0000421 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800422 }
423
424 // Push the incoming payload (parsed and ready for decoding) into the ACM
425 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
426 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100427 RTC_LOG(LS_ERROR)
428 << "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800429 return -1;
430 }
431
kwiberg55b97fe2016-01-28 05:22:45 -0800432 int64_t round_trip_time = 0;
433 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
434 NULL);
435
436 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
437 if (!nack_list.empty()) {
438 // Can't use nack_list.data() since it's not supported by all
439 // compilers.
440 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
441 }
442 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000443}
444
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000445bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000446 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000447 RTPHeader header;
448 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100449 RTC_LOG(LS_WARNING) << "IncomingPacket invalid RTP header";
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000450 return false;
451 }
452 header.payload_type_frequency =
453 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
454 if (header.payload_type_frequency < 0)
455 return false;
Niels Möller22ec9522017-10-05 08:39:15 +0200456 // TODO(nisse): Pass RtpPacketReceived with |recovered()| true.
457 return ReceivePacket(rtp_packet, rtp_packet_length, header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000458}
459
solenberg2397b9a2017-09-22 06:48:10 -0700460AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
461 int sample_rate_hz,
462 AudioFrame* audio_frame) {
463 audio_frame->sample_rate_hz_ = sample_rate_hz;
464
ivoc14d5dbe2016-07-04 07:06:55 -0700465 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800466 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
Elad Alon4a87e1c2017-10-03 16:11:34 +0200467 event_log_proxy_->Log(rtc::MakeUnique<RtcEventAudioPlayout>(ssrc));
kwiberg55b97fe2016-01-28 05:22:45 -0800468 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700469 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700470 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700471 &muted) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100472 RTC_LOG(LS_ERROR) << "Channel::GetAudioFrame() PlayoutData10Ms() failed!";
kwiberg55b97fe2016-01-28 05:22:45 -0800473 // In all likelihood, the audio in this frame is garbage. We return an
474 // error so that the audio mixer module doesn't add it to the mix. As
475 // a result, it won't be played out and the actions skipped here are
476 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700477 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800478 }
henrik.lundina89ab962016-05-18 08:52:45 -0700479
480 if (muted) {
481 // TODO(henrik.lundin): We should be able to do better than this. But we
482 // will have to go through all the cases below where the audio samples may
483 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700484 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700485 }
kwiberg55b97fe2016-01-28 05:22:45 -0800486
kwiberg55b97fe2016-01-28 05:22:45 -0800487 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700488 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800489
kwiberg55b97fe2016-01-28 05:22:45 -0800490 {
491 // Pass the audio buffers to an optional sink callback, before applying
492 // scaling/panning, as that applies to the mix operation.
493 // External recipients of the audio (e.g. via AudioTrack), will do their
494 // own mixing/dynamic processing.
495 rtc::CritScope cs(&_callbackCritSect);
496 if (audio_sink_) {
497 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700498 audio_frame->data(), audio_frame->samples_per_channel_,
499 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
500 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800501 audio_sink_->OnData(data);
502 }
503 }
504
505 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800506 {
507 rtc::CritScope cs(&volume_settings_critsect_);
508 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800509 }
510
511 // Output volume scaling
512 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800513 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700514 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800515 }
516
kwiberg55b97fe2016-01-28 05:22:45 -0800517 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700518 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700519 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700520 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700521 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800522
solenberg2397b9a2017-09-22 06:48:10 -0700523 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800524 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700525 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800526 }
527
528 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700529 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800530
531 // Compute elapsed time.
532 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700533 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
534 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800535 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700536 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800537
niklase@google.com470e71d2011-07-07 08:21:25 +0000538 {
kwiberg55b97fe2016-01-28 05:22:45 -0800539 rtc::CritScope lock(&ts_stats_lock_);
540 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700541 audio_frame->ntp_time_ms_ =
542 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800543 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700544 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800545 // Compute |capture_start_ntp_time_ms_| so that
546 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
547 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700548 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000549 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000550 }
kwiberg55b97fe2016-01-28 05:22:45 -0800551 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000552
Henrik Lundin9bde6b72017-11-02 15:01:56 +0100553 {
554 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
555 rtc::CritScope lock(&video_sync_lock_);
556 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
557 jitter_buffer_delay + playout_delay_ms_);
558 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
559 jitter_buffer_delay);
560 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
561 playout_delay_ms_);
562 }
563
solenberg2397b9a2017-09-22 06:48:10 -0700564 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
565 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000566}
567
solenberg2397b9a2017-09-22 06:48:10 -0700568int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800569 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700570 return std::max(audio_coding_->ReceiveFrequency(),
571 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000572}
573
henrikaec6fbd22017-03-31 05:43:36 -0700574int32_t Channel::CreateChannel(Channel*& channel,
575 int32_t channelId,
576 uint32_t instanceId,
577 const VoEBase::ChannelConfig& config) {
solenberg88499ec2016-09-07 07:34:41 -0700578 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800579 if (channel == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100580 RTC_LOG(LS_ERROR) << "unable to allocate memory for new channel";
kwiberg55b97fe2016-01-28 05:22:45 -0800581 return -1;
582 }
583 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000584}
585
pbos@webrtc.org92135212013-05-14 08:31:39 +0000586Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000587 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700588 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800589 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100590 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700591 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800592 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100593 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800594 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100595 rtp_receive_statistics_(
596 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
597 rtp_receiver_(
598 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100599 this,
600 this,
601 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700602 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100603 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100604 _timeStamp(0), // This is just an offset, RTP module will add it's own
605 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100606 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100607 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100608 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100609 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100610 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
611 capture_start_rtp_time_stamp_(-1),
612 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100613 _moduleProcessThreadPtr(NULL),
614 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100615 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700616 input_mute_(false),
617 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100618 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100619 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800620 transport_overhead_per_packet_(0),
621 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100622 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100623 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100624 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700625 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800626 feedback_observer_proxy_(new TransportFeedbackProxy()),
627 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700628 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200629 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
630 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700631 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700632 use_twcc_plr_for_ana_(
633 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
solenberg88499ec2016-09-07 07:34:41 -0700634 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700635 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800636 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200637
kwiberg55b97fe2016-01-28 05:22:45 -0800638 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000639
kwiberg55b97fe2016-01-28 05:22:45 -0800640 RtpRtcp::Configuration configuration;
641 configuration.audio = true;
642 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800643 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800644 configuration.receive_statistics = rtp_receive_statistics_.get();
645 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800646 if (pacing_enabled_) {
647 configuration.paced_sender = rtp_packet_sender_proxy_.get();
648 configuration.transport_sequence_number_allocator =
649 seq_num_allocator_proxy_.get();
650 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
651 }
ivoc14d5dbe2016-07-04 07:06:55 -0700652 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800653 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200654 configuration.retransmission_rate_limiter =
655 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000656
kwiberg55b97fe2016-01-28 05:22:45 -0800657 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100658 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000659}
660
kwiberg55b97fe2016-01-28 05:22:45 -0800661Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700662 RTC_DCHECK(!channel_state_.Get().sending);
663 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000664}
665
kwiberg55b97fe2016-01-28 05:22:45 -0800666int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700667 RTC_DCHECK(construction_thread_.CalledOnValidThread());
niklase@google.com470e71d2011-07-07 08:21:25 +0000668
kwiberg55b97fe2016-01-28 05:22:45 -0800669 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000670
kwiberg55b97fe2016-01-28 05:22:45 -0800671 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000672
solenberg1c239d42017-09-29 06:00:28 -0700673 if (_moduleProcessThreadPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100674 RTC_LOG(LS_ERROR)
675 << "Channel::Init() must call SetEngineInformation() first";
kwiberg55b97fe2016-01-28 05:22:45 -0800676 return -1;
677 }
678
679 // --- Add modules to process thread (for periodic schedulation)
680
tommidea489f2017-03-03 03:20:24 -0800681 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800682
683 // --- ACM initialization
684
685 if (audio_coding_->InitializeReceiver() == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100686 RTC_LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800687 return -1;
688 }
689
690 // --- RTP/RTCP module initialization
691
692 // Ensure that RTCP is enabled by default for the created channel.
693 // Note that, the module will keep generating RTCP until it is explicitly
694 // disabled by the user.
695 // After StopListen (when no sockets exists), RTCP packets will no longer
696 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700697 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800698 // RTCP is enabled by default.
699 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
700 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800701 if (audio_coding_->RegisterTransportCallback(this) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100702 RTC_LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800703 return -1;
704 }
705
kwiberg1c07c702017-03-27 07:15:49 -0700706 return 0;
707}
708
tommi0a2391f2017-03-21 02:31:51 -0700709void Channel::Terminate() {
710 RTC_DCHECK(construction_thread_.CalledOnValidThread());
711 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700712 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
713
714 StopSend();
715 StopPlayout();
716
tommi0a2391f2017-03-21 02:31:51 -0700717 // The order to safely shutdown modules in a channel is:
718 // 1. De-register callbacks in modules
719 // 2. De-register modules in process thread
720 // 3. Destroy modules
721 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100722 RTC_LOG(LS_WARNING)
723 << "Terminate() failed to de-register transport callback"
724 << " (Audio coding module)";
tommi0a2391f2017-03-21 02:31:51 -0700725 }
726
tommi0a2391f2017-03-21 02:31:51 -0700727 // De-register modules in process thread
728 if (_moduleProcessThreadPtr)
729 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
730
731 // End of modules shutdown
732}
733
solenberg1c239d42017-09-29 06:00:28 -0700734int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800735 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700736 rtc::TaskQueue* encoder_queue) {
737 RTC_DCHECK(encoder_queue);
738 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800739 _moduleProcessThreadPtr = &moduleProcessThread;
740 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700741 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800742 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000743}
744
kwibergb7f89d62016-02-17 10:04:18 -0800745void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800746 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800747 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100748}
749
ossu29b1a8d2016-06-13 07:34:51 -0700750const rtc::scoped_refptr<AudioDecoderFactory>&
751Channel::GetAudioDecoderFactory() const {
752 return decoder_factory_;
753}
754
kwiberg55b97fe2016-01-28 05:22:45 -0800755int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800756 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000757 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800758 }
759
kwiberg55b97fe2016-01-28 05:22:45 -0800760 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800761
762 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000763}
764
kwiberg55b97fe2016-01-28 05:22:45 -0800765int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800766 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000767 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800768 }
769
kwiberg55b97fe2016-01-28 05:22:45 -0800770 channel_state_.SetPlaying(false);
771 _outputAudioLevel.Clear();
772
773 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000774}
775
kwiberg55b97fe2016-01-28 05:22:45 -0800776int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800777 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000778 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800779 }
780 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700781 {
782 // It is now OK to start posting tasks to the encoder task queue.
783 rtc::CritScope cs(&encoder_queue_lock_);
784 encoder_queue_is_active_ = true;
785 }
solenberg08b19df2017-02-15 00:42:31 -0800786 // Resume the previous sequence number which was reset by StopSend(). This
787 // needs to be done before |sending| is set to true on the RTP/RTCP module.
788 if (send_sequence_number_) {
789 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
790 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100791 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800792 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100793 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100794 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800795 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000796 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800797 return -1;
798 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000799
kwiberg55b97fe2016-01-28 05:22:45 -0800800 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000801}
802
henrikaec6fbd22017-03-31 05:43:36 -0700803void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800804 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700805 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800806 }
807 channel_state_.SetSending(false);
808
henrikaec6fbd22017-03-31 05:43:36 -0700809 // Post a task to the encoder thread which sets an event when the task is
810 // executed. We know that no more encoding tasks will be added to the task
811 // queue for this channel since sending is now deactivated. It means that,
812 // if we wait for the event to bet set, we know that no more pending tasks
813 // exists and it is therfore guaranteed that the task queue will never try
814 // to acccess and invalid channel object.
815 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700816
henrikaec6fbd22017-03-31 05:43:36 -0700817 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700818 {
819 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
820 // than this final "flush task" to be posted on the queue.
821 rtc::CritScope cs(&encoder_queue_lock_);
822 encoder_queue_is_active_ = false;
823 encoder_queue_->PostTask([&flush]() { flush.Set(); });
824 }
henrikaec6fbd22017-03-31 05:43:36 -0700825 flush.Wait(rtc::Event::kForever);
826
kwiberg55b97fe2016-01-28 05:22:45 -0800827 // Store the sequence number to be able to pick up the same sequence for
828 // the next StartSend(). This is needed for restarting device, otherwise
829 // it might cause libSRTP to complain about packets being replayed.
830 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
831 // CL is landed. See issue
832 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
833 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
834
835 // Reset sending SSRC and sequence number and triggers direct transmission
836 // of RTCP BYE
837 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100838 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800839 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100840 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000841}
842
ossu1ffbd6c2017-04-06 12:05:04 -0700843bool Channel::SetEncoder(int payload_type,
844 std::unique_ptr<AudioEncoder> encoder) {
845 RTC_DCHECK_GE(payload_type, 0);
846 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700847 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
848 // one for for us to keep track of sample rate and number of channels, etc.
849
850 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
851 // as well as some other things, so we collect this info and send it along.
852 CodecInst rtp_codec;
853 rtp_codec.pltype = payload_type;
854 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
855 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700856 // Seems unclear if it should be clock rate or sample rate. CodecInst
857 // supposedly carries the sample rate, but only clock rate seems sensible to
858 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700859 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
860 rtp_codec.pacsize = rtc::CheckedDivExact(
861 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
862 100);
863 rtp_codec.channels = encoder->NumChannels();
864 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700865
Karl Wiberg88182372017-10-17 01:02:46 +0200866 cached_encoder_props_.emplace(
867 EncoderProps{encoder->SampleRateHz(), encoder->NumChannels()});
ossu76d29f92017-06-09 07:30:13 -0700868
869 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700870 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700871 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100872 RTC_LOG(LS_ERROR)
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200873 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700874 return false;
875 }
876 }
877
878 audio_coding_->SetEncoder(std::move(encoder));
879 return true;
880}
881
ossu20a4b3f2017-04-27 02:08:52 -0700882void Channel::ModifyEncoder(
883 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
884 audio_coding_->ModifyEncoder(modifier);
885}
886
Karl Wiberg88182372017-10-17 01:02:46 +0200887rtc::Optional<Channel::EncoderProps> Channel::GetEncoderProps() const {
888 return cached_encoder_props_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000889}
890
kwiberg55b97fe2016-01-28 05:22:45 -0800891int32_t Channel::GetRecCodec(CodecInst& codec) {
892 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +0000893}
894
minyue78b4d562016-11-30 04:47:39 -0800895void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -0700896 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -0800897 if (*encoder) {
898 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -0800899 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -0800900 }
901 });
michaelt566d8202017-01-12 10:17:38 -0800902 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +0200903}
904
elad.alond12a8e12017-03-23 11:04:48 -0700905void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
906 if (!use_twcc_plr_for_ana_)
907 return;
minyue7e304322016-10-12 05:00:55 -0700908 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -0700909 if (*encoder) {
910 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
911 }
912 });
913}
914
elad.alondadb4dc2017-03-23 15:29:50 -0700915void Channel::OnRecoverableUplinkPacketLossRate(
916 float recoverable_packet_loss_rate) {
917 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
918 if (*encoder) {
919 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
920 recoverable_packet_loss_rate);
921 }
922 });
923}
924
elad.alond12a8e12017-03-23 11:04:48 -0700925void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
926 if (use_twcc_plr_for_ana_)
927 return;
928 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
929 if (*encoder) {
930 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
931 }
minyue7e304322016-10-12 05:00:55 -0700932 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000933}
934
kwiberg1c07c702017-03-27 07:15:49 -0700935void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
936 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
937 audio_coding_->SetReceiveCodecs(codecs);
938}
939
minyue7e304322016-10-12 05:00:55 -0700940bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
941 bool success = false;
942 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
943 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -0700944 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
945 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -0700946 }
947 });
948 return success;
949}
950
951void Channel::DisableAudioNetworkAdaptor() {
952 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
953 if (*encoder)
954 (*encoder)->DisableAudioNetworkAdaptor();
955 });
956}
957
958void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
959 int max_frame_length_ms) {
960 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
961 if (*encoder) {
962 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
963 max_frame_length_ms);
964 }
965 });
966}
967
solenberg1c239d42017-09-29 06:00:28 -0700968void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -0800969 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -0700970 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +0000971}
972
nisse657bab22017-02-21 06:28:10 -0800973void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -0800974 RTPHeader header;
975 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -0700976
977 // Store playout timestamp for the received RTP packet
978 UpdatePlayoutTimestamp(false);
979
980 header.payload_type_frequency =
981 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
982 if (header.payload_type_frequency >= 0) {
983 bool in_order = IsPacketInOrder(header);
984 rtp_receive_statistics_->IncomingPacket(
985 header, packet.size(), IsPacketRetransmitted(header, in_order));
986 rtp_payload_registry_->SetIncomingPayloadType(header);
987
Niels Möller22ec9522017-10-05 08:39:15 +0200988 ReceivePacket(packet.data(), packet.size(), header);
solenberg946d8862017-09-21 04:02:53 -0700989 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000990}
991
992bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000993 size_t packet_length,
Niels Möller22ec9522017-10-05 08:39:15 +0200994 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000995 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000996 assert(packet_length >= header.headerLength);
997 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +0200998 const auto pl =
999 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1000 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001001 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001002 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001003 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Niels Möller22ec9522017-10-05 08:39:15 +02001004 pl->typeSpecific);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001005}
1006
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001007bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1008 StreamStatistician* statistician =
1009 rtp_receive_statistics_->GetStatistician(header.ssrc);
1010 if (!statistician)
1011 return false;
1012 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001013}
1014
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001015bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1016 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001017 StreamStatistician* statistician =
1018 rtp_receive_statistics_->GetStatistician(header.ssrc);
1019 if (!statistician)
1020 return false;
1021 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001022 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001023 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001024 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001025}
1026
mflodman3d7db262016-04-29 00:57:13 -07001027int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001028 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001029 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001030
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001031 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001032 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001033
Minyue2013aec2015-05-13 14:14:42 +02001034 int64_t rtt = GetRTT(true);
1035 if (rtt == 0) {
1036 // Waiting for valid RTT.
1037 return 0;
1038 }
Erik Språng737336d2016-07-29 12:59:36 +02001039
1040 int64_t nack_window_ms = rtt;
1041 if (nack_window_ms < kMinRetransmissionWindowMs) {
1042 nack_window_ms = kMinRetransmissionWindowMs;
1043 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1044 nack_window_ms = kMaxRetransmissionWindowMs;
1045 }
1046 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1047
minyue7e304322016-10-12 05:00:55 -07001048 // Invoke audio encoders OnReceivedRtt().
1049 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1050 if (*encoder)
1051 (*encoder)->OnReceivedRtt(rtt);
1052 });
1053
Minyue2013aec2015-05-13 14:14:42 +02001054 uint32_t ntp_secs = 0;
1055 uint32_t ntp_frac = 0;
1056 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001057 if (0 !=
1058 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1059 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001060 // Waiting for RTCP.
1061 return 0;
1062 }
1063
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001064 {
tommi31fc21f2016-01-21 10:37:37 -08001065 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001066 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001067 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001068 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001069}
1070
solenberg8d73f8c2017-03-08 01:52:20 -08001071int Channel::GetSpeechOutputLevel() const {
1072 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001073}
1074
solenberg8d73f8c2017-03-08 01:52:20 -08001075int Channel::GetSpeechOutputLevelFullRange() const {
1076 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001077}
1078
zsteine76bd3a2017-07-14 12:17:49 -07001079double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001080 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001081}
1082
1083double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001084 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001085}
1086
solenberg8d73f8c2017-03-08 01:52:20 -08001087void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001088 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001089 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001090}
1091
solenberg1c2af8e2016-03-24 10:36:00 -07001092bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001093 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001094 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001095}
1096
solenberg8d73f8c2017-03-08 01:52:20 -08001097void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001098 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001099 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001100}
1101
solenberg8842c3e2016-03-11 03:06:41 -08001102int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001103 RTC_DCHECK_LE(0, event);
1104 RTC_DCHECK_GE(255, event);
1105 RTC_DCHECK_LE(0, duration_ms);
1106 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001107 if (!Sending()) {
1108 return -1;
1109 }
solenberg8842c3e2016-03-11 03:06:41 -08001110 if (_rtpRtcpModule->SendTelephoneEventOutband(
1111 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001112 RTC_LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001113 return -1;
1114 }
1115 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001116}
1117
solenbergffbbcac2016-11-17 05:25:37 -08001118int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1119 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001120 RTC_DCHECK_LE(0, payload_type);
1121 RTC_DCHECK_GE(127, payload_type);
1122 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001123 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001124 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001125 memcpy(codec.plname, "telephone-event", 16);
1126 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1127 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1128 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001129 RTC_LOG(LS_ERROR)
1130 << "SetSendTelephoneEventPayloadType() failed to register "
1131 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001132 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001133 }
kwiberg55b97fe2016-01-28 05:22:45 -08001134 }
kwiberg55b97fe2016-01-28 05:22:45 -08001135 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001136}
1137
kwiberg55b97fe2016-01-28 05:22:45 -08001138int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001139 if (channel_state_.Get().sending) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001140 RTC_LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001141 return -1;
1142 }
1143 _rtpRtcpModule->SetSSRC(ssrc);
1144 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001145}
1146
kwiberg55b97fe2016-01-28 05:22:45 -08001147int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1148 ssrc = rtp_receiver_->SSRC();
1149 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001150}
1151
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001152int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001153 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001154 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001155}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001156
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001157int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1158 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001159 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1160 if (enable &&
1161 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1162 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001163 return -1;
1164 }
1165 return 0;
1166}
1167
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001168void Channel::EnableSendTransportSequenceNumber(int id) {
1169 int ret =
1170 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1171 RTC_DCHECK_EQ(0, ret);
1172}
1173
stefan3313ec92016-01-21 06:32:43 -08001174void Channel::EnableReceiveTransportSequenceNumber(int id) {
1175 rtp_header_parser_->DeregisterRtpHeaderExtension(
1176 kRtpExtensionTransportSequenceNumber);
1177 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1178 kRtpExtensionTransportSequenceNumber, id);
1179 RTC_DCHECK(ret);
1180}
1181
stefanbba9dec2016-02-01 04:39:55 -08001182void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001183 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001184 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001185 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1186 TransportFeedbackObserver* transport_feedback_observer =
1187 transport->transport_feedback_observer();
1188 PacketRouter* packet_router = transport->packet_router();
1189
stefanbba9dec2016-02-01 04:39:55 -08001190 RTC_DCHECK(rtp_packet_sender);
1191 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001192 RTC_DCHECK(packet_router);
1193 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001194 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001195 feedback_observer_proxy_->SetTransportFeedbackObserver(
1196 transport_feedback_observer);
1197 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1198 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1199 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001200 constexpr bool remb_candidate = false;
1201 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001202 packet_router_ = packet_router;
1203}
1204
stefanbba9dec2016-02-01 04:39:55 -08001205void Channel::RegisterReceiverCongestionControlObjects(
1206 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001207 RTC_DCHECK(packet_router);
1208 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001209 constexpr bool remb_candidate = false;
1210 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001211 packet_router_ = packet_router;
1212}
1213
nissefdbfdc92017-03-31 05:44:52 -07001214void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001215 RTC_DCHECK(packet_router_);
1216 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001217 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001218 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1219 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001220 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001221 packet_router_ = nullptr;
1222 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1223}
1224
nissefdbfdc92017-03-31 05:44:52 -07001225void Channel::ResetReceiverCongestionControlObjects() {
1226 RTC_DCHECK(packet_router_);
1227 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1228 packet_router_ = nullptr;
1229}
1230
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001231void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001232 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001233}
1234
kwiberg55b97fe2016-01-28 05:22:45 -08001235int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001236 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001237 RTC_LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001238 return -1;
1239 }
1240 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001241}
1242
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001243int Channel::GetRemoteRTCPReportBlocks(
1244 std::vector<ReportBlock>* report_blocks) {
1245 if (report_blocks == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001246 RTC_LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001247 return -1;
1248 }
1249
1250 // Get the report blocks from the latest received RTCP Sender or Receiver
1251 // Report. Each element in the vector contains the sender's SSRC and a
1252 // report block according to RFC 3550.
1253 std::vector<RTCPReportBlock> rtcp_report_blocks;
1254 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001255 return -1;
1256 }
1257
1258 if (rtcp_report_blocks.empty())
1259 return 0;
1260
1261 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1262 for (; it != rtcp_report_blocks.end(); ++it) {
1263 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001264 report_block.sender_SSRC = it->sender_ssrc;
1265 report_block.source_SSRC = it->source_ssrc;
1266 report_block.fraction_lost = it->fraction_lost;
1267 report_block.cumulative_num_packets_lost = it->packets_lost;
1268 report_block.extended_highest_sequence_number =
1269 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001270 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001271 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1272 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001273 report_blocks->push_back(report_block);
1274 }
1275 return 0;
1276}
1277
kwiberg55b97fe2016-01-28 05:22:45 -08001278int Channel::GetRTPStatistics(CallStatistics& stats) {
1279 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001280
kwiberg55b97fe2016-01-28 05:22:45 -08001281 // The jitter statistics is updated for each received RTP packet and is
1282 // based on received packets.
1283 RtcpStatistics statistics;
1284 StreamStatistician* statistician =
1285 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001286 if (statistician) {
1287 statistician->GetStatistics(&statistics,
1288 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001289 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001290
kwiberg55b97fe2016-01-28 05:22:45 -08001291 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001292 stats.cumulativeLost = statistics.packets_lost;
1293 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001294 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001295
kwiberg55b97fe2016-01-28 05:22:45 -08001296 // --- RTT
1297 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001298
kwiberg55b97fe2016-01-28 05:22:45 -08001299 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001300
kwiberg55b97fe2016-01-28 05:22:45 -08001301 size_t bytesSent(0);
1302 uint32_t packetsSent(0);
1303 size_t bytesReceived(0);
1304 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001305
kwiberg55b97fe2016-01-28 05:22:45 -08001306 if (statistician) {
1307 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1308 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001309
kwiberg55b97fe2016-01-28 05:22:45 -08001310 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001311 RTC_LOG(LS_WARNING)
1312 << "GetRTPStatistics() failed to retrieve RTP datacounters"
1313 << " => output will not be complete";
kwiberg55b97fe2016-01-28 05:22:45 -08001314 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001315
kwiberg55b97fe2016-01-28 05:22:45 -08001316 stats.bytesSent = bytesSent;
1317 stats.packetsSent = packetsSent;
1318 stats.bytesReceived = bytesReceived;
1319 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001320
kwiberg55b97fe2016-01-28 05:22:45 -08001321 // --- Timestamps
1322 {
1323 rtc::CritScope lock(&ts_stats_lock_);
1324 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1325 }
1326 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001327}
1328
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001329void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1330 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001331 // If pacing is enabled we always store packets.
1332 if (!pacing_enabled_)
1333 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001334 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001335 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001336 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001337 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001338 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001339}
1340
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001341// Called when we are missing one or more packets.
1342int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001343 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1344}
1345
henrikaec6fbd22017-03-31 05:43:36 -07001346void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001347 // Avoid posting any new tasks if sending was already stopped in StopSend().
1348 rtc::CritScope cs(&encoder_queue_lock_);
1349 if (!encoder_queue_is_active_) {
1350 return;
1351 }
henrikaec6fbd22017-03-31 05:43:36 -07001352 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1353 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1354 // either into pool of frames or into the task itself.
1355 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001356 // Profile time between when the audio frame is added to the task queue and
1357 // when the task is actually executed.
1358 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001359 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1360 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001361}
1362
henrikaec6fbd22017-03-31 05:43:36 -07001363void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1364 int sample_rate,
1365 size_t number_of_frames,
1366 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001367 // Avoid posting as new task if sending was already stopped in StopSend().
1368 rtc::CritScope cs(&encoder_queue_lock_);
1369 if (!encoder_queue_is_active_) {
1370 return;
1371 }
henrikaec6fbd22017-03-31 05:43:36 -07001372 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
Karl Wiberg88182372017-10-17 01:02:46 +02001373 const auto props = GetEncoderProps();
1374 RTC_CHECK(props);
1375 audio_frame->sample_rate_hz_ = std::min(props->sample_rate_hz, sample_rate);
1376 audio_frame->num_channels_ =
1377 std::min(props->num_channels, number_of_channels);
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001378 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001379 sample_rate, &input_resampler_, audio_frame.get());
1380 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1381 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001382}
1383
henrikaec6fbd22017-03-31 05:43:36 -07001384void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1385 RTC_DCHECK_RUN_ON(encoder_queue_);
1386 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1387 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001388
henrika45802172017-09-28 09:39:34 +02001389 // Measure time between when the audio frame is added to the task queue and
1390 // when the task is actually executed. Goal is to keep track of unwanted
1391 // extra latency added by the task queue.
1392 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1393 audio_input->ElapsedProfileTimeMs());
1394
henrikaec6fbd22017-03-31 05:43:36 -07001395 bool is_muted = InputMute();
1396 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001397
kwiberg55b97fe2016-01-28 05:22:45 -08001398 if (_includeAudioLevelIndication) {
1399 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001400 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001401 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001402 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001403 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001404 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001405 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001406 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001407 }
kwiberg55b97fe2016-01-28 05:22:45 -08001408 }
solenberg1c2af8e2016-03-24 10:36:00 -07001409 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001410
henrikaec6fbd22017-03-31 05:43:36 -07001411 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001412
kwiberg55b97fe2016-01-28 05:22:45 -08001413 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001414 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001415 // This call will trigger AudioPacketizationCallback::SendData if encoding
1416 // is done and payload is ready for packetization and transmission.
1417 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001418 if (audio_coding_->Add10MsData(*audio_input) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001419 RTC_LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
henrikaec6fbd22017-03-31 05:43:36 -07001420 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001421 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001422
henrikaec6fbd22017-03-31 05:43:36 -07001423 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001424}
1425
solenberg7602aab2016-11-14 11:30:07 -08001426void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1427 RTC_DCHECK(!channel.channel() ||
1428 channel.channel()->ChannelId() != _channelId);
1429 rtc::CritScope lock(&assoc_send_channel_lock_);
1430 associate_send_channel_ = channel;
1431}
1432
Minyue2013aec2015-05-13 14:14:42 +02001433void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001434 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001435 Channel* channel = associate_send_channel_.channel();
1436 if (channel && channel->ChannelId() == channel_id) {
1437 // If this channel is associated with a send channel of the specified
1438 // Channel ID, disassociate with it.
1439 ChannelOwner ref(NULL);
1440 associate_send_channel_ = ref;
1441 }
1442}
1443
ivoc14d5dbe2016-07-04 07:06:55 -07001444void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1445 event_log_proxy_->SetEventLog(event_log);
1446}
1447
michaelt9332b7d2016-11-30 07:51:13 -08001448void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1449 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1450}
1451
nisse284542b2017-01-10 08:58:32 -08001452void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001453 size_t overhead_per_packet =
1454 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001455 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1456 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001457 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001458 }
1459 });
1460}
1461
1462void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001463 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001464 transport_overhead_per_packet_ = transport_overhead_per_packet;
1465 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001466}
1467
hbos3fd31fe2017-02-28 05:43:16 -08001468// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001469void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001470 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001471 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1472 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001473}
1474
kwiberg55b97fe2016-01-28 05:22:45 -08001475int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1476 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001477}
1478
wu@webrtc.org24301a62013-12-13 19:17:43 +00001479void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1480 audio_coding_->GetDecodingCallStatistics(stats);
1481}
1482
ivoce1198e02017-09-08 08:13:19 -07001483ANAStats Channel::GetANAStatistics() const {
1484 return audio_coding_->GetANAStats();
1485}
1486
solenberg358057b2015-11-27 10:46:42 -08001487uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001488 rtc::CritScope lock(&video_sync_lock_);
1489 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001490}
1491
kwiberg55b97fe2016-01-28 05:22:45 -08001492int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001493 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1494 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001495 RTC_LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001496 return -1;
1497 }
1498 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001499 RTC_LOG(LS_ERROR)
1500 << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001501 return -1;
1502 }
1503 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001504}
1505
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001506int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001507 uint32_t playout_timestamp_rtp = 0;
1508 {
tommi31fc21f2016-01-21 10:37:37 -08001509 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001510 playout_timestamp_rtp = playout_timestamp_rtp_;
1511 }
kwiberg55b97fe2016-01-28 05:22:45 -08001512 if (playout_timestamp_rtp == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001513 RTC_LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001514 return -1;
1515 }
deadbeef74375882015-08-13 12:09:10 -07001516 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001517 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001518}
1519
kwiberg55b97fe2016-01-28 05:22:45 -08001520int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1521 RtpReceiver** rtp_receiver) const {
1522 *rtpRtcpModule = _rtpRtcpModule.get();
1523 *rtp_receiver = rtp_receiver_.get();
1524 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001525}
1526
deadbeef74375882015-08-13 12:09:10 -07001527void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001528 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001529
henrik.lundin96bd5022016-04-06 04:13:56 -07001530 if (!jitter_buffer_playout_timestamp_) {
1531 // This can happen if this channel has not received any RTP packets. In
1532 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001533 return;
1534 }
1535
1536 uint16_t delay_ms = 0;
1537 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001538 RTC_LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1539 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001540 return;
1541 }
1542
henrik.lundin96bd5022016-04-06 04:13:56 -07001543 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1544 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001545
1546 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001547 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001548
deadbeef74375882015-08-13 12:09:10 -07001549 {
tommi31fc21f2016-01-21 10:37:37 -08001550 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001551 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001552 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001553 }
1554 playout_delay_ms_ = delay_ms;
1555 }
1556}
1557
kwiberg55b97fe2016-01-28 05:22:45 -08001558void Channel::RegisterReceiveCodecsToRTPModule() {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001559 // TODO(kwiberg): Iterate over the factory's supported codecs instead?
1560 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001561 for (int idx = 0; idx < nSupportedCodecs; idx++) {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001562 CodecInst codec;
1563 if (audio_coding_->Codec(idx, &codec) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001564 RTC_LOG(LS_WARNING) << "Unable to register codec #" << idx
1565 << " for RTP/RTCP receiver.";
Karl Wibergc62f6c72017-10-04 12:38:53 +02001566 continue;
1567 }
1568 const SdpAudioFormat format = CodecInstToSdp(codec);
1569 if (!decoder_factory_->IsSupportedDecoder(format) ||
1570 rtp_receiver_->RegisterReceivePayload(codec.pltype, format) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001571 RTC_LOG(LS_WARNING) << "Unable to register " << format
1572 << " for RTP/RTCP receiver.";
niklase@google.com470e71d2011-07-07 08:21:25 +00001573 }
kwiberg55b97fe2016-01-28 05:22:45 -08001574 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001575}
1576
kwiberg55b97fe2016-01-28 05:22:45 -08001577int Channel::SetSendRtpHeaderExtension(bool enable,
1578 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001579 unsigned char id) {
1580 int error = 0;
1581 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1582 if (enable) {
1583 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1584 }
1585 return error;
1586}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001587
ossue280cde2016-10-12 11:04:10 -07001588int Channel::GetRtpTimestampRateHz() const {
1589 const auto format = audio_coding_->ReceiveFormat();
1590 // Default to the playout frequency if we've not gotten any packets yet.
1591 // TODO(ossu): Zero clockrate can only happen if we've added an external
1592 // decoder for a format we don't support internally. Remove once that way of
1593 // adding decoders is gone!
1594 return (format && format->clockrate_hz != 0)
1595 ? format->clockrate_hz
1596 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001597}
1598
Minyue2013aec2015-05-13 14:14:42 +02001599int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001600 RtcpMode method = _rtpRtcpModule->RTCP();
1601 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001602 return 0;
1603 }
1604 std::vector<RTCPReportBlock> report_blocks;
1605 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001606
1607 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001608 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001609 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001610 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001611 Channel* channel = associate_send_channel_.channel();
1612 // Tries to get RTT from an associated channel. This is important for
1613 // receive-only channels.
1614 if (channel) {
1615 // To prevent infinite recursion and deadlock, calling GetRTT of
1616 // associate channel should always use "false" for argument:
1617 // |allow_associate_channel|.
1618 rtt = channel->GetRTT(false);
1619 }
1620 }
1621 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001622 }
1623
1624 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1625 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1626 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001627 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001628 break;
1629 }
1630 if (it == report_blocks.end()) {
1631 // We have not received packets with SSRC matching the report blocks.
1632 // To calculate RTT we try with the SSRC of the first report block.
1633 // This is very important for send-only channels where we don't know
1634 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001635 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001636 }
Minyue2013aec2015-05-13 14:14:42 +02001637
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001638 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001639 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001640 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001641 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1642 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001643 return 0;
1644 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001645 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001646}
1647
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001648} // namespace voe
1649} // namespace webrtc