blob: 20dc87f6c4101b079a6b71a26240b1d93df33dad [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
Bjorn Tereliusde939432017-11-20 17:38:14 +010068 bool StartLogging(std::unique_ptr<RtcEventLogOutput> output,
69 int64_t output_period_ms) override {
Elad Alon83ccca12017-10-04 13:18:26 +020070 RTC_NOTREACHED();
71 return false;
72 }
73
ivoc14d5dbe2016-07-04 07:06:55 -070074 void StopLogging() override { RTC_NOTREACHED(); }
75
Elad Alon4a87e1c2017-10-03 16:11:34 +020076 void Log(std::unique_ptr<RtcEvent> event) override {
77 rtc::CritScope lock(&crit_);
78 if (event_log_) {
79 event_log_->Log(std::move(event));
80 }
81 }
82
ivoc14d5dbe2016-07-04 07:06:55 -070083 void SetEventLog(RtcEventLog* event_log) {
84 rtc::CritScope lock(&crit_);
85 event_log_ = event_log;
86 }
87
88 private:
89 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -070090 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -070091 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
92};
93
michaelt9332b7d2016-11-30 07:51:13 -080094class RtcpRttStatsProxy final : public RtcpRttStats {
95 public:
96 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
97
98 void OnRttUpdate(int64_t rtt) override {
99 rtc::CritScope lock(&crit_);
100 if (rtcp_rtt_stats_)
101 rtcp_rtt_stats_->OnRttUpdate(rtt);
102 }
103
104 int64_t LastProcessedRtt() const override {
105 rtc::CritScope lock(&crit_);
106 if (!rtcp_rtt_stats_)
107 return 0;
108 return rtcp_rtt_stats_->LastProcessedRtt();
109 }
110
111 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
112 rtc::CritScope lock(&crit_);
113 rtcp_rtt_stats_ = rtcp_rtt_stats;
114 }
115
116 private:
117 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700118 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800119 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
120};
121
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100122class TransportFeedbackProxy : public TransportFeedbackObserver {
123 public:
124 TransportFeedbackProxy() : feedback_observer_(nullptr) {
125 pacer_thread_.DetachFromThread();
126 network_thread_.DetachFromThread();
127 }
128
129 void SetTransportFeedbackObserver(
130 TransportFeedbackObserver* feedback_observer) {
131 RTC_DCHECK(thread_checker_.CalledOnValidThread());
132 rtc::CritScope lock(&crit_);
133 feedback_observer_ = feedback_observer;
134 }
135
136 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700137 void AddPacket(uint32_t ssrc,
138 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100139 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800140 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100141 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
142 rtc::CritScope lock(&crit_);
143 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700144 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100145 }
philipel8aadd502017-02-23 02:56:13 -0800146
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100147 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
148 RTC_DCHECK(network_thread_.CalledOnValidThread());
149 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700150 if (feedback_observer_)
151 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200152 }
elad.alonf9490002017-03-06 05:32:21 -0800153 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200154 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800155 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100156 }
157
158 private:
159 rtc::CriticalSection crit_;
160 rtc::ThreadChecker thread_checker_;
161 rtc::ThreadChecker pacer_thread_;
162 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700163 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100164};
165
166class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
167 public:
168 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
169 pacer_thread_.DetachFromThread();
170 }
171
172 void SetSequenceNumberAllocator(
173 TransportSequenceNumberAllocator* seq_num_allocator) {
174 RTC_DCHECK(thread_checker_.CalledOnValidThread());
175 rtc::CritScope lock(&crit_);
176 seq_num_allocator_ = seq_num_allocator;
177 }
178
179 // Implements TransportSequenceNumberAllocator.
180 uint16_t AllocateSequenceNumber() override {
181 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
182 rtc::CritScope lock(&crit_);
183 if (!seq_num_allocator_)
184 return 0;
185 return seq_num_allocator_->AllocateSequenceNumber();
186 }
187
188 private:
189 rtc::CriticalSection crit_;
190 rtc::ThreadChecker thread_checker_;
191 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700192 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100193};
194
195class RtpPacketSenderProxy : public RtpPacketSender {
196 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800197 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100198
199 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
200 RTC_DCHECK(thread_checker_.CalledOnValidThread());
201 rtc::CritScope lock(&crit_);
202 rtp_packet_sender_ = rtp_packet_sender;
203 }
204
205 // Implements RtpPacketSender.
206 void InsertPacket(Priority priority,
207 uint32_t ssrc,
208 uint16_t sequence_number,
209 int64_t capture_time_ms,
210 size_t bytes,
211 bool retransmission) override {
212 rtc::CritScope lock(&crit_);
213 if (rtp_packet_sender_) {
214 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
215 capture_time_ms, bytes, retransmission);
216 }
217 }
218
Alex Narest78609d52017-10-20 10:37:47 +0200219 void SetAccountForAudioPackets(bool account_for_audio) override {
220 RTC_NOTREACHED();
221 }
222
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100223 private:
224 rtc::ThreadChecker thread_checker_;
225 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700226 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100227};
228
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000229class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000230 public:
stefan7de8d642017-02-07 07:14:08 -0800231 explicit VoERtcpObserver(Channel* owner)
232 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000233 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000234
stefan7de8d642017-02-07 07:14:08 -0800235 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
236 rtc::CritScope lock(&crit_);
237 bandwidth_observer_ = bandwidth_observer;
238 }
239
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000240 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800241 rtc::CritScope lock(&crit_);
242 if (bandwidth_observer_) {
243 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
244 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000245 }
246
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000247 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
248 int64_t rtt,
249 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800250 {
251 rtc::CritScope lock(&crit_);
252 if (bandwidth_observer_) {
253 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
254 now_ms);
255 }
256 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000257 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
258 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
259 // report for VoiceEngine?
260 if (report_blocks.empty())
261 return;
262
263 int fraction_lost_aggregate = 0;
264 int total_number_of_packets = 0;
265
266 // If receiving multiple report blocks, calculate the weighted average based
267 // on the number of packets a report refers to.
268 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
269 block_it != report_blocks.end(); ++block_it) {
270 // Find the previous extended high sequence number for this remote SSRC,
271 // to calculate the number of RTP packets this report refers to. Ignore if
272 // we haven't seen this SSRC before.
273 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700274 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000275 int number_of_packets = 0;
276 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700277 number_of_packets =
278 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000279 }
srte3e69e5c2017-08-09 06:13:45 -0700280 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000281 total_number_of_packets += number_of_packets;
282
srte3e69e5c2017-08-09 06:13:45 -0700283 extended_max_sequence_number_[block_it->source_ssrc] =
284 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000285 }
286 int weighted_fraction_lost = 0;
287 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800288 weighted_fraction_lost =
289 (fraction_lost_aggregate + total_number_of_packets / 2) /
290 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000291 }
elad.alond12a8e12017-03-23 11:04:48 -0700292 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000293 }
294
295 private:
296 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000297 // Maps remote side ssrc to extended highest sequence number received.
298 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800299 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700300 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000301};
302
henrikaec6fbd22017-03-31 05:43:36 -0700303class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
304 public:
305 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
306 Channel* channel)
307 : audio_frame_(std::move(audio_frame)), channel_(channel) {
308 RTC_DCHECK(channel_);
309 }
310
311 private:
312 bool Run() override {
313 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
314 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
315 return true;
316 }
317
318 std::unique_ptr<AudioFrame> audio_frame_;
319 Channel* const channel_;
320};
321
kwiberg55b97fe2016-01-28 05:22:45 -0800322int32_t Channel::SendData(FrameType frameType,
323 uint8_t payloadType,
324 uint32_t timeStamp,
325 const uint8_t* payloadData,
326 size_t payloadSize,
327 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700328 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800329 if (_includeAudioLevelIndication) {
330 // Store current audio level in the RTP/RTCP module.
331 // The level will be used in combination with voice-activity state
332 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800333 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800334 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000335
kwiberg55b97fe2016-01-28 05:22:45 -0800336 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
337 // packetization.
338 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700339 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800340 (FrameType&)frameType, payloadType, timeStamp,
341 // Leaving the time when this frame was
342 // received from the capture device as
343 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700344 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100345 RTC_LOG(LS_ERROR)
346 << "Channel::SendData() failed to send data to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800347 return -1;
348 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000349
kwiberg55b97fe2016-01-28 05:22:45 -0800350 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000351}
352
stefan1d8a5062015-10-02 03:39:33 -0700353bool Channel::SendRtp(const uint8_t* data,
354 size_t len,
355 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800356 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000357
kwiberg55b97fe2016-01-28 05:22:45 -0800358 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100359 RTC_LOG(LS_ERROR)
360 << "Channel::SendPacket() failed to send RTP packet due to"
361 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800362 return false;
363 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000364
kwiberg55b97fe2016-01-28 05:22:45 -0800365 uint8_t* bufferToSendPtr = (uint8_t*)data;
366 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000367
kwiberg55b97fe2016-01-28 05:22:45 -0800368 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100369 RTC_LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800370 return false;
371 }
372 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000373}
374
kwiberg55b97fe2016-01-28 05:22:45 -0800375bool Channel::SendRtcp(const uint8_t* data, size_t len) {
kwiberg55b97fe2016-01-28 05:22:45 -0800376 rtc::CritScope cs(&_callbackCritSect);
377 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100378 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() failed to send RTCP packet due to"
379 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800380 return false;
381 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000382
kwiberg55b97fe2016-01-28 05:22:45 -0800383 uint8_t* bufferToSendPtr = (uint8_t*)data;
384 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000385
kwiberg55b97fe2016-01-28 05:22:45 -0800386 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
387 if (n < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100388 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800389 return false;
390 }
391 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000392}
393
kwiberg55b97fe2016-01-28 05:22:45 -0800394void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -0800395 // Update ssrc so that NTP for AV sync can be updated.
396 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000397}
398
Peter Boströmac547a62015-09-17 23:03:57 +0200399void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200400 // TODO(saza): remove.
niklase@google.com470e71d2011-07-07 08:21:25 +0000401}
402
Karl Wibergc62f6c72017-10-04 12:38:53 +0200403int32_t Channel::OnInitializeDecoder(int payload_type,
404 const SdpAudioFormat& audio_format,
405 uint32_t rate) {
406 if (!audio_coding_->RegisterReceiveCodec(payload_type, audio_format)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100407 RTC_LOG(LS_WARNING) << "Channel::OnInitializeDecoder() invalid codec (pt="
408 << payload_type << ", " << audio_format
409 << ") received -1";
kwiberg55b97fe2016-01-28 05:22:45 -0800410 return -1;
411 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000412
kwiberg55b97fe2016-01-28 05:22:45 -0800413 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000414}
415
kwiberg55b97fe2016-01-28 05:22:45 -0800416int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
417 size_t payloadSize,
418 const WebRtcRTPHeader* rtpHeader) {
kwiberg55b97fe2016-01-28 05:22:45 -0800419 if (!channel_state_.Get().playing) {
420 // Avoid inserting into NetEQ when we are not playing. Count the
421 // packet as discarded.
niklase@google.com470e71d2011-07-07 08:21:25 +0000422 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800423 }
424
425 // Push the incoming payload (parsed and ready for decoding) into the ACM
426 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
427 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100428 RTC_LOG(LS_ERROR)
429 << "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800430 return -1;
431 }
432
kwiberg55b97fe2016-01-28 05:22:45 -0800433 int64_t round_trip_time = 0;
434 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
435 NULL);
436
437 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
438 if (!nack_list.empty()) {
439 // Can't use nack_list.data() since it's not supported by all
440 // compilers.
441 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
442 }
443 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000444}
445
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000446bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000447 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000448 RTPHeader header;
449 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100450 RTC_LOG(LS_WARNING) << "IncomingPacket invalid RTP header";
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000451 return false;
452 }
453 header.payload_type_frequency =
454 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
455 if (header.payload_type_frequency < 0)
456 return false;
Niels Möller22ec9522017-10-05 08:39:15 +0200457 // TODO(nisse): Pass RtpPacketReceived with |recovered()| true.
458 return ReceivePacket(rtp_packet, rtp_packet_length, header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000459}
460
solenberg2397b9a2017-09-22 06:48:10 -0700461AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
462 int sample_rate_hz,
463 AudioFrame* audio_frame) {
464 audio_frame->sample_rate_hz_ = sample_rate_hz;
465
ivoc14d5dbe2016-07-04 07:06:55 -0700466 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800467 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
Elad Alon4a87e1c2017-10-03 16:11:34 +0200468 event_log_proxy_->Log(rtc::MakeUnique<RtcEventAudioPlayout>(ssrc));
kwiberg55b97fe2016-01-28 05:22:45 -0800469 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700470 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700471 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700472 &muted) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100473 RTC_LOG(LS_ERROR) << "Channel::GetAudioFrame() PlayoutData10Ms() failed!";
kwiberg55b97fe2016-01-28 05:22:45 -0800474 // In all likelihood, the audio in this frame is garbage. We return an
475 // error so that the audio mixer module doesn't add it to the mix. As
476 // a result, it won't be played out and the actions skipped here are
477 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700478 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800479 }
henrik.lundina89ab962016-05-18 08:52:45 -0700480
481 if (muted) {
482 // TODO(henrik.lundin): We should be able to do better than this. But we
483 // will have to go through all the cases below where the audio samples may
484 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700485 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700486 }
kwiberg55b97fe2016-01-28 05:22:45 -0800487
kwiberg55b97fe2016-01-28 05:22:45 -0800488 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700489 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800490
kwiberg55b97fe2016-01-28 05:22:45 -0800491 {
492 // Pass the audio buffers to an optional sink callback, before applying
493 // scaling/panning, as that applies to the mix operation.
494 // External recipients of the audio (e.g. via AudioTrack), will do their
495 // own mixing/dynamic processing.
496 rtc::CritScope cs(&_callbackCritSect);
497 if (audio_sink_) {
498 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700499 audio_frame->data(), audio_frame->samples_per_channel_,
500 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
501 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800502 audio_sink_->OnData(data);
503 }
504 }
505
506 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800507 {
508 rtc::CritScope cs(&volume_settings_critsect_);
509 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800510 }
511
512 // Output volume scaling
513 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800514 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700515 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800516 }
517
kwiberg55b97fe2016-01-28 05:22:45 -0800518 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700519 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700520 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700521 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700522 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800523
solenberg2397b9a2017-09-22 06:48:10 -0700524 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800525 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700526 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800527 }
528
529 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700530 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800531
532 // Compute elapsed time.
533 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700534 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
535 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800536 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700537 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800538
niklase@google.com470e71d2011-07-07 08:21:25 +0000539 {
kwiberg55b97fe2016-01-28 05:22:45 -0800540 rtc::CritScope lock(&ts_stats_lock_);
541 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700542 audio_frame->ntp_time_ms_ =
543 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800544 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700545 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800546 // Compute |capture_start_ntp_time_ms_| so that
547 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
548 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700549 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000550 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000551 }
kwiberg55b97fe2016-01-28 05:22:45 -0800552 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000553
Henrik Lundin9bde6b72017-11-02 15:01:56 +0100554 {
555 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
556 rtc::CritScope lock(&video_sync_lock_);
557 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
558 jitter_buffer_delay + playout_delay_ms_);
559 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
560 jitter_buffer_delay);
561 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
562 playout_delay_ms_);
563 }
564
solenberg2397b9a2017-09-22 06:48:10 -0700565 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
566 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000567}
568
solenberg2397b9a2017-09-22 06:48:10 -0700569int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800570 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700571 return std::max(audio_coding_->ReceiveFrequency(),
572 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000573}
574
henrikaec6fbd22017-03-31 05:43:36 -0700575int32_t Channel::CreateChannel(Channel*& channel,
576 int32_t channelId,
577 uint32_t instanceId,
578 const VoEBase::ChannelConfig& config) {
solenberg88499ec2016-09-07 07:34:41 -0700579 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800580 if (channel == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100581 RTC_LOG(LS_ERROR) << "unable to allocate memory for new channel";
kwiberg55b97fe2016-01-28 05:22:45 -0800582 return -1;
583 }
584 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000585}
586
pbos@webrtc.org92135212013-05-14 08:31:39 +0000587Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000588 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700589 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800590 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100591 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700592 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800593 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100594 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800595 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100596 rtp_receive_statistics_(
597 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
598 rtp_receiver_(
599 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100600 this,
601 this,
602 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700603 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100604 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100605 _timeStamp(0), // This is just an offset, RTP module will add it's own
606 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100607 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100608 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100609 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100610 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100611 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
612 capture_start_rtp_time_stamp_(-1),
613 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100614 _moduleProcessThreadPtr(NULL),
615 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100616 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700617 input_mute_(false),
618 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100619 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100620 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800621 transport_overhead_per_packet_(0),
622 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100623 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100624 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100625 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700626 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800627 feedback_observer_proxy_(new TransportFeedbackProxy()),
628 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700629 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200630 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
631 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700632 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700633 use_twcc_plr_for_ana_(
634 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
solenberg88499ec2016-09-07 07:34:41 -0700635 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700636 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800637 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200638
kwiberg55b97fe2016-01-28 05:22:45 -0800639 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000640
kwiberg55b97fe2016-01-28 05:22:45 -0800641 RtpRtcp::Configuration configuration;
642 configuration.audio = true;
643 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800644 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800645 configuration.receive_statistics = rtp_receive_statistics_.get();
646 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800647 if (pacing_enabled_) {
648 configuration.paced_sender = rtp_packet_sender_proxy_.get();
649 configuration.transport_sequence_number_allocator =
650 seq_num_allocator_proxy_.get();
651 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
652 }
ivoc14d5dbe2016-07-04 07:06:55 -0700653 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800654 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200655 configuration.retransmission_rate_limiter =
656 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000657
kwiberg55b97fe2016-01-28 05:22:45 -0800658 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100659 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000660}
661
kwiberg55b97fe2016-01-28 05:22:45 -0800662Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700663 RTC_DCHECK(!channel_state_.Get().sending);
664 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000665}
666
kwiberg55b97fe2016-01-28 05:22:45 -0800667int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700668 RTC_DCHECK(construction_thread_.CalledOnValidThread());
niklase@google.com470e71d2011-07-07 08:21:25 +0000669
kwiberg55b97fe2016-01-28 05:22:45 -0800670 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000671
kwiberg55b97fe2016-01-28 05:22:45 -0800672 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000673
solenberg1c239d42017-09-29 06:00:28 -0700674 if (_moduleProcessThreadPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100675 RTC_LOG(LS_ERROR)
676 << "Channel::Init() must call SetEngineInformation() first";
kwiberg55b97fe2016-01-28 05:22:45 -0800677 return -1;
678 }
679
680 // --- Add modules to process thread (for periodic schedulation)
681
tommidea489f2017-03-03 03:20:24 -0800682 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800683
684 // --- ACM initialization
685
686 if (audio_coding_->InitializeReceiver() == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100687 RTC_LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800688 return -1;
689 }
690
691 // --- RTP/RTCP module initialization
692
693 // Ensure that RTCP is enabled by default for the created channel.
694 // Note that, the module will keep generating RTCP until it is explicitly
695 // disabled by the user.
696 // After StopListen (when no sockets exists), RTCP packets will no longer
697 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700698 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800699 // RTCP is enabled by default.
700 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
701 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800702 if (audio_coding_->RegisterTransportCallback(this) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100703 RTC_LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800704 return -1;
705 }
706
kwiberg1c07c702017-03-27 07:15:49 -0700707 return 0;
708}
709
tommi0a2391f2017-03-21 02:31:51 -0700710void Channel::Terminate() {
711 RTC_DCHECK(construction_thread_.CalledOnValidThread());
712 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700713 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
714
715 StopSend();
716 StopPlayout();
717
tommi0a2391f2017-03-21 02:31:51 -0700718 // The order to safely shutdown modules in a channel is:
719 // 1. De-register callbacks in modules
720 // 2. De-register modules in process thread
721 // 3. Destroy modules
722 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100723 RTC_LOG(LS_WARNING)
724 << "Terminate() failed to de-register transport callback"
725 << " (Audio coding module)";
tommi0a2391f2017-03-21 02:31:51 -0700726 }
727
tommi0a2391f2017-03-21 02:31:51 -0700728 // De-register modules in process thread
729 if (_moduleProcessThreadPtr)
730 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
731
732 // End of modules shutdown
733}
734
solenberg1c239d42017-09-29 06:00:28 -0700735int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800736 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700737 rtc::TaskQueue* encoder_queue) {
738 RTC_DCHECK(encoder_queue);
739 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800740 _moduleProcessThreadPtr = &moduleProcessThread;
741 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700742 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800743 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
kwibergb7f89d62016-02-17 10:04:18 -0800746void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800747 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800748 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100749}
750
ossu29b1a8d2016-06-13 07:34:51 -0700751const rtc::scoped_refptr<AudioDecoderFactory>&
752Channel::GetAudioDecoderFactory() const {
753 return decoder_factory_;
754}
755
kwiberg55b97fe2016-01-28 05:22:45 -0800756int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800757 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000758 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800759 }
760
kwiberg55b97fe2016-01-28 05:22:45 -0800761 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800762
763 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000764}
765
kwiberg55b97fe2016-01-28 05:22:45 -0800766int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800767 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000768 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800769 }
770
kwiberg55b97fe2016-01-28 05:22:45 -0800771 channel_state_.SetPlaying(false);
772 _outputAudioLevel.Clear();
773
774 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000775}
776
kwiberg55b97fe2016-01-28 05:22:45 -0800777int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800778 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000779 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800780 }
781 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700782 {
783 // It is now OK to start posting tasks to the encoder task queue.
784 rtc::CritScope cs(&encoder_queue_lock_);
785 encoder_queue_is_active_ = true;
786 }
solenberg08b19df2017-02-15 00:42:31 -0800787 // Resume the previous sequence number which was reset by StopSend(). This
788 // needs to be done before |sending| is set to true on the RTP/RTCP module.
789 if (send_sequence_number_) {
790 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
791 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100792 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800793 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100794 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100795 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800796 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000797 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800798 return -1;
799 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000800
kwiberg55b97fe2016-01-28 05:22:45 -0800801 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000802}
803
henrikaec6fbd22017-03-31 05:43:36 -0700804void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800805 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700806 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800807 }
808 channel_state_.SetSending(false);
809
henrikaec6fbd22017-03-31 05:43:36 -0700810 // Post a task to the encoder thread which sets an event when the task is
811 // executed. We know that no more encoding tasks will be added to the task
812 // queue for this channel since sending is now deactivated. It means that,
813 // if we wait for the event to bet set, we know that no more pending tasks
814 // exists and it is therfore guaranteed that the task queue will never try
815 // to acccess and invalid channel object.
816 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700817
henrikaec6fbd22017-03-31 05:43:36 -0700818 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700819 {
820 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
821 // than this final "flush task" to be posted on the queue.
822 rtc::CritScope cs(&encoder_queue_lock_);
823 encoder_queue_is_active_ = false;
824 encoder_queue_->PostTask([&flush]() { flush.Set(); });
825 }
henrikaec6fbd22017-03-31 05:43:36 -0700826 flush.Wait(rtc::Event::kForever);
827
kwiberg55b97fe2016-01-28 05:22:45 -0800828 // Store the sequence number to be able to pick up the same sequence for
829 // the next StartSend(). This is needed for restarting device, otherwise
830 // it might cause libSRTP to complain about packets being replayed.
831 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
832 // CL is landed. See issue
833 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
834 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
835
836 // Reset sending SSRC and sequence number and triggers direct transmission
837 // of RTCP BYE
838 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100839 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800840 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100841 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000842}
843
ossu1ffbd6c2017-04-06 12:05:04 -0700844bool Channel::SetEncoder(int payload_type,
845 std::unique_ptr<AudioEncoder> encoder) {
846 RTC_DCHECK_GE(payload_type, 0);
847 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700848 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
849 // one for for us to keep track of sample rate and number of channels, etc.
850
851 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
852 // as well as some other things, so we collect this info and send it along.
853 CodecInst rtp_codec;
854 rtp_codec.pltype = payload_type;
855 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
856 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700857 // Seems unclear if it should be clock rate or sample rate. CodecInst
858 // supposedly carries the sample rate, but only clock rate seems sensible to
859 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700860 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
861 rtp_codec.pacsize = rtc::CheckedDivExact(
862 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
863 100);
864 rtp_codec.channels = encoder->NumChannels();
865 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700866
Karl Wiberg88182372017-10-17 01:02:46 +0200867 cached_encoder_props_.emplace(
868 EncoderProps{encoder->SampleRateHz(), encoder->NumChannels()});
ossu76d29f92017-06-09 07:30:13 -0700869
870 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700871 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700872 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100873 RTC_LOG(LS_ERROR)
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200874 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700875 return false;
876 }
877 }
878
879 audio_coding_->SetEncoder(std::move(encoder));
880 return true;
881}
882
ossu20a4b3f2017-04-27 02:08:52 -0700883void Channel::ModifyEncoder(
884 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
885 audio_coding_->ModifyEncoder(modifier);
886}
887
Karl Wiberg88182372017-10-17 01:02:46 +0200888rtc::Optional<Channel::EncoderProps> Channel::GetEncoderProps() const {
889 return cached_encoder_props_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000890}
891
kwiberg55b97fe2016-01-28 05:22:45 -0800892int32_t Channel::GetRecCodec(CodecInst& codec) {
893 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +0000894}
895
minyue78b4d562016-11-30 04:47:39 -0800896void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -0700897 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -0800898 if (*encoder) {
899 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -0800900 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -0800901 }
902 });
michaelt566d8202017-01-12 10:17:38 -0800903 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +0200904}
905
elad.alond12a8e12017-03-23 11:04:48 -0700906void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
907 if (!use_twcc_plr_for_ana_)
908 return;
minyue7e304322016-10-12 05:00:55 -0700909 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -0700910 if (*encoder) {
911 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
912 }
913 });
914}
915
elad.alondadb4dc2017-03-23 15:29:50 -0700916void Channel::OnRecoverableUplinkPacketLossRate(
917 float recoverable_packet_loss_rate) {
918 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
919 if (*encoder) {
920 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
921 recoverable_packet_loss_rate);
922 }
923 });
924}
925
elad.alond12a8e12017-03-23 11:04:48 -0700926void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
927 if (use_twcc_plr_for_ana_)
928 return;
929 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
930 if (*encoder) {
931 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
932 }
minyue7e304322016-10-12 05:00:55 -0700933 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000934}
935
kwiberg1c07c702017-03-27 07:15:49 -0700936void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
937 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
938 audio_coding_->SetReceiveCodecs(codecs);
939}
940
minyue7e304322016-10-12 05:00:55 -0700941bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
942 bool success = false;
943 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
944 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -0700945 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
946 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -0700947 }
948 });
949 return success;
950}
951
952void Channel::DisableAudioNetworkAdaptor() {
953 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
954 if (*encoder)
955 (*encoder)->DisableAudioNetworkAdaptor();
956 });
957}
958
959void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
960 int max_frame_length_ms) {
961 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
962 if (*encoder) {
963 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
964 max_frame_length_ms);
965 }
966 });
967}
968
solenberg1c239d42017-09-29 06:00:28 -0700969void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -0800970 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -0700971 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +0000972}
973
nisse657bab22017-02-21 06:28:10 -0800974void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -0800975 RTPHeader header;
976 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -0700977
978 // Store playout timestamp for the received RTP packet
979 UpdatePlayoutTimestamp(false);
980
981 header.payload_type_frequency =
982 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
983 if (header.payload_type_frequency >= 0) {
984 bool in_order = IsPacketInOrder(header);
985 rtp_receive_statistics_->IncomingPacket(
986 header, packet.size(), IsPacketRetransmitted(header, in_order));
987 rtp_payload_registry_->SetIncomingPayloadType(header);
988
Niels Möller22ec9522017-10-05 08:39:15 +0200989 ReceivePacket(packet.data(), packet.size(), header);
solenberg946d8862017-09-21 04:02:53 -0700990 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000991}
992
993bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000994 size_t packet_length,
Niels Möller22ec9522017-10-05 08:39:15 +0200995 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000996 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000997 assert(packet_length >= header.headerLength);
998 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +0200999 const auto pl =
1000 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1001 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001002 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001003 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001004 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Niels Möller22ec9522017-10-05 08:39:15 +02001005 pl->typeSpecific);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001006}
1007
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001008bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1009 StreamStatistician* statistician =
1010 rtp_receive_statistics_->GetStatistician(header.ssrc);
1011 if (!statistician)
1012 return false;
1013 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001014}
1015
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001016bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1017 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001018 StreamStatistician* statistician =
1019 rtp_receive_statistics_->GetStatistician(header.ssrc);
1020 if (!statistician)
1021 return false;
1022 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001023 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001024 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001025 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001026}
1027
mflodman3d7db262016-04-29 00:57:13 -07001028int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001029 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001030 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001031
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001032 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001033 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001034
Minyue2013aec2015-05-13 14:14:42 +02001035 int64_t rtt = GetRTT(true);
1036 if (rtt == 0) {
1037 // Waiting for valid RTT.
1038 return 0;
1039 }
Erik Språng737336d2016-07-29 12:59:36 +02001040
1041 int64_t nack_window_ms = rtt;
1042 if (nack_window_ms < kMinRetransmissionWindowMs) {
1043 nack_window_ms = kMinRetransmissionWindowMs;
1044 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1045 nack_window_ms = kMaxRetransmissionWindowMs;
1046 }
1047 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1048
minyue7e304322016-10-12 05:00:55 -07001049 // Invoke audio encoders OnReceivedRtt().
1050 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1051 if (*encoder)
1052 (*encoder)->OnReceivedRtt(rtt);
1053 });
1054
Minyue2013aec2015-05-13 14:14:42 +02001055 uint32_t ntp_secs = 0;
1056 uint32_t ntp_frac = 0;
1057 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001058 if (0 !=
1059 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1060 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001061 // Waiting for RTCP.
1062 return 0;
1063 }
1064
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001065 {
tommi31fc21f2016-01-21 10:37:37 -08001066 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001067 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001068 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001069 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001070}
1071
solenberg8d73f8c2017-03-08 01:52:20 -08001072int Channel::GetSpeechOutputLevel() const {
1073 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001074}
1075
solenberg8d73f8c2017-03-08 01:52:20 -08001076int Channel::GetSpeechOutputLevelFullRange() const {
1077 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001078}
1079
zsteine76bd3a2017-07-14 12:17:49 -07001080double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001081 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001082}
1083
1084double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001085 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001086}
1087
solenberg8d73f8c2017-03-08 01:52:20 -08001088void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001089 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001090 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001091}
1092
solenberg1c2af8e2016-03-24 10:36:00 -07001093bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001094 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001095 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001096}
1097
solenberg8d73f8c2017-03-08 01:52:20 -08001098void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001099 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001100 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001101}
1102
solenberg8842c3e2016-03-11 03:06:41 -08001103int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001104 RTC_DCHECK_LE(0, event);
1105 RTC_DCHECK_GE(255, event);
1106 RTC_DCHECK_LE(0, duration_ms);
1107 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001108 if (!Sending()) {
1109 return -1;
1110 }
solenberg8842c3e2016-03-11 03:06:41 -08001111 if (_rtpRtcpModule->SendTelephoneEventOutband(
1112 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001113 RTC_LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001114 return -1;
1115 }
1116 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001117}
1118
solenbergffbbcac2016-11-17 05:25:37 -08001119int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1120 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001121 RTC_DCHECK_LE(0, payload_type);
1122 RTC_DCHECK_GE(127, payload_type);
1123 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001124 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001125 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001126 memcpy(codec.plname, "telephone-event", 16);
1127 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1128 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1129 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001130 RTC_LOG(LS_ERROR)
1131 << "SetSendTelephoneEventPayloadType() failed to register "
1132 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001133 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001134 }
kwiberg55b97fe2016-01-28 05:22:45 -08001135 }
kwiberg55b97fe2016-01-28 05:22:45 -08001136 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001137}
1138
kwiberg55b97fe2016-01-28 05:22:45 -08001139int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001140 if (channel_state_.Get().sending) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001141 RTC_LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001142 return -1;
1143 }
1144 _rtpRtcpModule->SetSSRC(ssrc);
1145 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001146}
1147
kwiberg55b97fe2016-01-28 05:22:45 -08001148int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1149 ssrc = rtp_receiver_->SSRC();
1150 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001151}
1152
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001153int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001154 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001155 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001156}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001157
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001158int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1159 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001160 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1161 if (enable &&
1162 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1163 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001164 return -1;
1165 }
1166 return 0;
1167}
1168
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001169void Channel::EnableSendTransportSequenceNumber(int id) {
1170 int ret =
1171 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1172 RTC_DCHECK_EQ(0, ret);
1173}
1174
stefan3313ec92016-01-21 06:32:43 -08001175void Channel::EnableReceiveTransportSequenceNumber(int id) {
1176 rtp_header_parser_->DeregisterRtpHeaderExtension(
1177 kRtpExtensionTransportSequenceNumber);
1178 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1179 kRtpExtensionTransportSequenceNumber, id);
1180 RTC_DCHECK(ret);
1181}
1182
stefanbba9dec2016-02-01 04:39:55 -08001183void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001184 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001185 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001186 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1187 TransportFeedbackObserver* transport_feedback_observer =
1188 transport->transport_feedback_observer();
1189 PacketRouter* packet_router = transport->packet_router();
1190
stefanbba9dec2016-02-01 04:39:55 -08001191 RTC_DCHECK(rtp_packet_sender);
1192 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001193 RTC_DCHECK(packet_router);
1194 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001195 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001196 feedback_observer_proxy_->SetTransportFeedbackObserver(
1197 transport_feedback_observer);
1198 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1199 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1200 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001201 constexpr bool remb_candidate = false;
1202 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001203 packet_router_ = packet_router;
1204}
1205
stefanbba9dec2016-02-01 04:39:55 -08001206void Channel::RegisterReceiverCongestionControlObjects(
1207 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001208 RTC_DCHECK(packet_router);
1209 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001210 constexpr bool remb_candidate = false;
1211 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001212 packet_router_ = packet_router;
1213}
1214
nissefdbfdc92017-03-31 05:44:52 -07001215void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001216 RTC_DCHECK(packet_router_);
1217 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001218 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001219 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1220 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001221 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001222 packet_router_ = nullptr;
1223 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1224}
1225
nissefdbfdc92017-03-31 05:44:52 -07001226void Channel::ResetReceiverCongestionControlObjects() {
1227 RTC_DCHECK(packet_router_);
1228 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1229 packet_router_ = nullptr;
1230}
1231
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001232void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001233 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001234}
1235
kwiberg55b97fe2016-01-28 05:22:45 -08001236int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001237 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001238 RTC_LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001239 return -1;
1240 }
1241 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001242}
1243
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001244int Channel::GetRemoteRTCPReportBlocks(
1245 std::vector<ReportBlock>* report_blocks) {
1246 if (report_blocks == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001247 RTC_LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001248 return -1;
1249 }
1250
1251 // Get the report blocks from the latest received RTCP Sender or Receiver
1252 // Report. Each element in the vector contains the sender's SSRC and a
1253 // report block according to RFC 3550.
1254 std::vector<RTCPReportBlock> rtcp_report_blocks;
1255 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001256 return -1;
1257 }
1258
1259 if (rtcp_report_blocks.empty())
1260 return 0;
1261
1262 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1263 for (; it != rtcp_report_blocks.end(); ++it) {
1264 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001265 report_block.sender_SSRC = it->sender_ssrc;
1266 report_block.source_SSRC = it->source_ssrc;
1267 report_block.fraction_lost = it->fraction_lost;
1268 report_block.cumulative_num_packets_lost = it->packets_lost;
1269 report_block.extended_highest_sequence_number =
1270 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001271 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001272 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1273 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001274 report_blocks->push_back(report_block);
1275 }
1276 return 0;
1277}
1278
kwiberg55b97fe2016-01-28 05:22:45 -08001279int Channel::GetRTPStatistics(CallStatistics& stats) {
1280 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001281
kwiberg55b97fe2016-01-28 05:22:45 -08001282 // The jitter statistics is updated for each received RTP packet and is
1283 // based on received packets.
1284 RtcpStatistics statistics;
1285 StreamStatistician* statistician =
1286 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001287 if (statistician) {
1288 statistician->GetStatistics(&statistics,
1289 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001290 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001291
kwiberg55b97fe2016-01-28 05:22:45 -08001292 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001293 stats.cumulativeLost = statistics.packets_lost;
1294 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001295 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001296
kwiberg55b97fe2016-01-28 05:22:45 -08001297 // --- RTT
1298 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001299
kwiberg55b97fe2016-01-28 05:22:45 -08001300 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001301
kwiberg55b97fe2016-01-28 05:22:45 -08001302 size_t bytesSent(0);
1303 uint32_t packetsSent(0);
1304 size_t bytesReceived(0);
1305 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001306
kwiberg55b97fe2016-01-28 05:22:45 -08001307 if (statistician) {
1308 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1309 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001310
kwiberg55b97fe2016-01-28 05:22:45 -08001311 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001312 RTC_LOG(LS_WARNING)
1313 << "GetRTPStatistics() failed to retrieve RTP datacounters"
1314 << " => output will not be complete";
kwiberg55b97fe2016-01-28 05:22:45 -08001315 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001316
kwiberg55b97fe2016-01-28 05:22:45 -08001317 stats.bytesSent = bytesSent;
1318 stats.packetsSent = packetsSent;
1319 stats.bytesReceived = bytesReceived;
1320 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001321
kwiberg55b97fe2016-01-28 05:22:45 -08001322 // --- Timestamps
1323 {
1324 rtc::CritScope lock(&ts_stats_lock_);
1325 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1326 }
1327 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001328}
1329
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001330void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1331 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001332 // If pacing is enabled we always store packets.
1333 if (!pacing_enabled_)
1334 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001335 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001336 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001337 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001338 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001339 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001340}
1341
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001342// Called when we are missing one or more packets.
1343int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001344 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1345}
1346
henrikaec6fbd22017-03-31 05:43:36 -07001347void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001348 // Avoid posting any new tasks if sending was already stopped in StopSend().
1349 rtc::CritScope cs(&encoder_queue_lock_);
1350 if (!encoder_queue_is_active_) {
1351 return;
1352 }
henrikaec6fbd22017-03-31 05:43:36 -07001353 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1354 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1355 // either into pool of frames or into the task itself.
1356 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001357 // Profile time between when the audio frame is added to the task queue and
1358 // when the task is actually executed.
1359 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001360 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1361 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001362}
1363
henrikaec6fbd22017-03-31 05:43:36 -07001364void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1365 int sample_rate,
1366 size_t number_of_frames,
1367 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001368 // Avoid posting as new task if sending was already stopped in StopSend().
1369 rtc::CritScope cs(&encoder_queue_lock_);
1370 if (!encoder_queue_is_active_) {
1371 return;
1372 }
henrikaec6fbd22017-03-31 05:43:36 -07001373 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
Karl Wiberg88182372017-10-17 01:02:46 +02001374 const auto props = GetEncoderProps();
1375 RTC_CHECK(props);
1376 audio_frame->sample_rate_hz_ = std::min(props->sample_rate_hz, sample_rate);
1377 audio_frame->num_channels_ =
1378 std::min(props->num_channels, number_of_channels);
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001379 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001380 sample_rate, &input_resampler_, audio_frame.get());
1381 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1382 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001383}
1384
henrikaec6fbd22017-03-31 05:43:36 -07001385void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1386 RTC_DCHECK_RUN_ON(encoder_queue_);
1387 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1388 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001389
henrika45802172017-09-28 09:39:34 +02001390 // Measure time between when the audio frame is added to the task queue and
1391 // when the task is actually executed. Goal is to keep track of unwanted
1392 // extra latency added by the task queue.
1393 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1394 audio_input->ElapsedProfileTimeMs());
1395
henrikaec6fbd22017-03-31 05:43:36 -07001396 bool is_muted = InputMute();
1397 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001398
kwiberg55b97fe2016-01-28 05:22:45 -08001399 if (_includeAudioLevelIndication) {
1400 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001401 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001402 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001403 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001404 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001405 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001406 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001407 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001408 }
kwiberg55b97fe2016-01-28 05:22:45 -08001409 }
solenberg1c2af8e2016-03-24 10:36:00 -07001410 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001411
henrikaec6fbd22017-03-31 05:43:36 -07001412 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001413
kwiberg55b97fe2016-01-28 05:22:45 -08001414 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001415 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001416 // This call will trigger AudioPacketizationCallback::SendData if encoding
1417 // is done and payload is ready for packetization and transmission.
1418 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001419 if (audio_coding_->Add10MsData(*audio_input) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
henrikaec6fbd22017-03-31 05:43:36 -07001421 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001422 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001423
henrikaec6fbd22017-03-31 05:43:36 -07001424 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001425}
1426
solenberg7602aab2016-11-14 11:30:07 -08001427void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1428 RTC_DCHECK(!channel.channel() ||
1429 channel.channel()->ChannelId() != _channelId);
1430 rtc::CritScope lock(&assoc_send_channel_lock_);
1431 associate_send_channel_ = channel;
1432}
1433
Minyue2013aec2015-05-13 14:14:42 +02001434void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001435 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001436 Channel* channel = associate_send_channel_.channel();
1437 if (channel && channel->ChannelId() == channel_id) {
1438 // If this channel is associated with a send channel of the specified
1439 // Channel ID, disassociate with it.
1440 ChannelOwner ref(NULL);
1441 associate_send_channel_ = ref;
1442 }
1443}
1444
ivoc14d5dbe2016-07-04 07:06:55 -07001445void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1446 event_log_proxy_->SetEventLog(event_log);
1447}
1448
michaelt9332b7d2016-11-30 07:51:13 -08001449void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1450 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1451}
1452
nisse284542b2017-01-10 08:58:32 -08001453void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001454 size_t overhead_per_packet =
1455 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001456 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1457 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001458 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001459 }
1460 });
1461}
1462
1463void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001464 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001465 transport_overhead_per_packet_ = transport_overhead_per_packet;
1466 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001467}
1468
hbos3fd31fe2017-02-28 05:43:16 -08001469// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001470void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001471 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001472 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1473 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001474}
1475
kwiberg55b97fe2016-01-28 05:22:45 -08001476int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1477 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001478}
1479
wu@webrtc.org24301a62013-12-13 19:17:43 +00001480void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1481 audio_coding_->GetDecodingCallStatistics(stats);
1482}
1483
ivoce1198e02017-09-08 08:13:19 -07001484ANAStats Channel::GetANAStatistics() const {
1485 return audio_coding_->GetANAStats();
1486}
1487
solenberg358057b2015-11-27 10:46:42 -08001488uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001489 rtc::CritScope lock(&video_sync_lock_);
1490 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001491}
1492
kwiberg55b97fe2016-01-28 05:22:45 -08001493int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001494 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1495 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001496 RTC_LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001497 return -1;
1498 }
1499 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001500 RTC_LOG(LS_ERROR)
1501 << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001502 return -1;
1503 }
1504 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001505}
1506
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001507int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001508 uint32_t playout_timestamp_rtp = 0;
1509 {
tommi31fc21f2016-01-21 10:37:37 -08001510 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001511 playout_timestamp_rtp = playout_timestamp_rtp_;
1512 }
kwiberg55b97fe2016-01-28 05:22:45 -08001513 if (playout_timestamp_rtp == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001514 RTC_LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001515 return -1;
1516 }
deadbeef74375882015-08-13 12:09:10 -07001517 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001518 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001519}
1520
kwiberg55b97fe2016-01-28 05:22:45 -08001521int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1522 RtpReceiver** rtp_receiver) const {
1523 *rtpRtcpModule = _rtpRtcpModule.get();
1524 *rtp_receiver = rtp_receiver_.get();
1525 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001526}
1527
deadbeef74375882015-08-13 12:09:10 -07001528void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001529 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001530
henrik.lundin96bd5022016-04-06 04:13:56 -07001531 if (!jitter_buffer_playout_timestamp_) {
1532 // This can happen if this channel has not received any RTP packets. In
1533 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001534 return;
1535 }
1536
1537 uint16_t delay_ms = 0;
1538 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001539 RTC_LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1540 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001541 return;
1542 }
1543
henrik.lundin96bd5022016-04-06 04:13:56 -07001544 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1545 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001546
1547 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001548 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001549
deadbeef74375882015-08-13 12:09:10 -07001550 {
tommi31fc21f2016-01-21 10:37:37 -08001551 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001552 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001553 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001554 }
1555 playout_delay_ms_ = delay_ms;
1556 }
1557}
1558
kwiberg55b97fe2016-01-28 05:22:45 -08001559void Channel::RegisterReceiveCodecsToRTPModule() {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001560 // TODO(kwiberg): Iterate over the factory's supported codecs instead?
1561 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001562 for (int idx = 0; idx < nSupportedCodecs; idx++) {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001563 CodecInst codec;
1564 if (audio_coding_->Codec(idx, &codec) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001565 RTC_LOG(LS_WARNING) << "Unable to register codec #" << idx
1566 << " for RTP/RTCP receiver.";
Karl Wibergc62f6c72017-10-04 12:38:53 +02001567 continue;
1568 }
1569 const SdpAudioFormat format = CodecInstToSdp(codec);
1570 if (!decoder_factory_->IsSupportedDecoder(format) ||
1571 rtp_receiver_->RegisterReceivePayload(codec.pltype, format) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001572 RTC_LOG(LS_WARNING) << "Unable to register " << format
1573 << " for RTP/RTCP receiver.";
niklase@google.com470e71d2011-07-07 08:21:25 +00001574 }
kwiberg55b97fe2016-01-28 05:22:45 -08001575 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001576}
1577
kwiberg55b97fe2016-01-28 05:22:45 -08001578int Channel::SetSendRtpHeaderExtension(bool enable,
1579 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001580 unsigned char id) {
1581 int error = 0;
1582 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1583 if (enable) {
1584 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1585 }
1586 return error;
1587}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001588
ossue280cde2016-10-12 11:04:10 -07001589int Channel::GetRtpTimestampRateHz() const {
1590 const auto format = audio_coding_->ReceiveFormat();
1591 // Default to the playout frequency if we've not gotten any packets yet.
1592 // TODO(ossu): Zero clockrate can only happen if we've added an external
1593 // decoder for a format we don't support internally. Remove once that way of
1594 // adding decoders is gone!
1595 return (format && format->clockrate_hz != 0)
1596 ? format->clockrate_hz
1597 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001598}
1599
Minyue2013aec2015-05-13 14:14:42 +02001600int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001601 RtcpMode method = _rtpRtcpModule->RTCP();
1602 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001603 return 0;
1604 }
1605 std::vector<RTCPReportBlock> report_blocks;
1606 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001607
1608 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001609 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001610 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001611 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001612 Channel* channel = associate_send_channel_.channel();
1613 // Tries to get RTT from an associated channel. This is important for
1614 // receive-only channels.
1615 if (channel) {
1616 // To prevent infinite recursion and deadlock, calling GetRTT of
1617 // associate channel should always use "false" for argument:
1618 // |allow_associate_channel|.
1619 rtt = channel->GetRTT(false);
1620 }
1621 }
1622 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001623 }
1624
1625 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1626 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1627 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001628 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001629 break;
1630 }
1631 if (it == report_blocks.end()) {
1632 // We have not received packets with SSRC matching the report blocks.
1633 // To calculate RTT we try with the SSRC of the first report block.
1634 // This is very important for send-only channels where we don't know
1635 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001636 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001637 }
Minyue2013aec2015-05-13 14:14:42 +02001638
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001639 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001640 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001641 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001642 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1643 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001644 return 0;
1645 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001646 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001647}
1648
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001649} // namespace voe
1650} // namespace webrtc