blob: 0130d4271d62a4d795cea34551f58bf976612b4e [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
Elad Alon83ccca12017-10-04 13:18:26 +020068 bool StartLogging(std::unique_ptr<RtcEventLogOutput> output) override {
69 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 Naresta5fbc232017-10-18 18:31:07 +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)) {
solenberg1c239d42017-09-29 06:00:28 -0700344 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) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200358 LOG(LS_ERROR) << "Channel::SendPacket() failed to send RTP packet due to"
359 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800360 return false;
361 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000362
kwiberg55b97fe2016-01-28 05:22:45 -0800363 uint8_t* bufferToSendPtr = (uint8_t*)data;
364 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000365
kwiberg55b97fe2016-01-28 05:22:45 -0800366 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
solenberg1c239d42017-09-29 06:00:28 -0700367 LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800368 return false;
369 }
370 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000371}
372
kwiberg55b97fe2016-01-28 05:22:45 -0800373bool Channel::SendRtcp(const uint8_t* data, size_t len) {
kwiberg55b97fe2016-01-28 05:22:45 -0800374 rtc::CritScope cs(&_callbackCritSect);
375 if (_transportPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200376 LOG(LS_ERROR) << "Channel::SendRtcp() failed to send RTCP packet due to"
377 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800378 return false;
379 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000380
kwiberg55b97fe2016-01-28 05:22:45 -0800381 uint8_t* bufferToSendPtr = (uint8_t*)data;
382 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000383
kwiberg55b97fe2016-01-28 05:22:45 -0800384 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
385 if (n < 0) {
solenberg1c239d42017-09-29 06:00:28 -0700386 LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800387 return false;
388 }
389 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000390}
391
kwiberg55b97fe2016-01-28 05:22:45 -0800392void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -0800393 // Update ssrc so that NTP for AV sync can be updated.
394 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000395}
396
Peter Boströmac547a62015-09-17 23:03:57 +0200397void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200398 // TODO(saza): remove.
niklase@google.com470e71d2011-07-07 08:21:25 +0000399}
400
Karl Wibergc62f6c72017-10-04 12:38:53 +0200401int32_t Channel::OnInitializeDecoder(int payload_type,
402 const SdpAudioFormat& audio_format,
403 uint32_t rate) {
404 if (!audio_coding_->RegisterReceiveCodec(payload_type, audio_format)) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200405 LOG(LS_WARNING) << "Channel::OnInitializeDecoder() invalid codec (pt="
Karl Wibergc62f6c72017-10-04 12:38:53 +0200406 << payload_type << ", " << audio_format << ") received -1";
kwiberg55b97fe2016-01-28 05:22:45 -0800407 return -1;
408 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000409
kwiberg55b97fe2016-01-28 05:22:45 -0800410 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000411}
412
kwiberg55b97fe2016-01-28 05:22:45 -0800413int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
414 size_t payloadSize,
415 const WebRtcRTPHeader* rtpHeader) {
kwiberg55b97fe2016-01-28 05:22:45 -0800416 if (!channel_state_.Get().playing) {
417 // Avoid inserting into NetEQ when we are not playing. Count the
418 // packet as discarded.
niklase@google.com470e71d2011-07-07 08:21:25 +0000419 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800420 }
421
422 // Push the incoming payload (parsed and ready for decoding) into the ACM
423 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
424 0) {
solenberg1c239d42017-09-29 06:00:28 -0700425 LOG(LS_ERROR) <<
426 "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800427 return -1;
428 }
429
kwiberg55b97fe2016-01-28 05:22:45 -0800430 int64_t round_trip_time = 0;
431 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
432 NULL);
433
434 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
435 if (!nack_list.empty()) {
436 // Can't use nack_list.data() since it's not supported by all
437 // compilers.
438 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
439 }
440 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000441}
442
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000443bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000444 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000445 RTPHeader header;
446 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200447 LOG(LS_WARNING) << "IncomingPacket invalid RTP header";
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000448 return false;
449 }
450 header.payload_type_frequency =
451 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
452 if (header.payload_type_frequency < 0)
453 return false;
Niels Möller22ec9522017-10-05 08:39:15 +0200454 // TODO(nisse): Pass RtpPacketReceived with |recovered()| true.
455 return ReceivePacket(rtp_packet, rtp_packet_length, header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000456}
457
solenberg2397b9a2017-09-22 06:48:10 -0700458AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
459 int sample_rate_hz,
460 AudioFrame* audio_frame) {
461 audio_frame->sample_rate_hz_ = sample_rate_hz;
462
ivoc14d5dbe2016-07-04 07:06:55 -0700463 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800464 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
Elad Alon4a87e1c2017-10-03 16:11:34 +0200465 event_log_proxy_->Log(rtc::MakeUnique<RtcEventAudioPlayout>(ssrc));
kwiberg55b97fe2016-01-28 05:22:45 -0800466 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700467 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700468 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700469 &muted) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200470 LOG(LS_ERROR) << "Channel::GetAudioFrame() PlayoutData10Ms() failed!";
kwiberg55b97fe2016-01-28 05:22:45 -0800471 // In all likelihood, the audio in this frame is garbage. We return an
472 // error so that the audio mixer module doesn't add it to the mix. As
473 // a result, it won't be played out and the actions skipped here are
474 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700475 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800476 }
henrik.lundina89ab962016-05-18 08:52:45 -0700477
478 if (muted) {
479 // TODO(henrik.lundin): We should be able to do better than this. But we
480 // will have to go through all the cases below where the audio samples may
481 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700482 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700483 }
kwiberg55b97fe2016-01-28 05:22:45 -0800484
kwiberg55b97fe2016-01-28 05:22:45 -0800485 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700486 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800487
kwiberg55b97fe2016-01-28 05:22:45 -0800488 {
489 // Pass the audio buffers to an optional sink callback, before applying
490 // scaling/panning, as that applies to the mix operation.
491 // External recipients of the audio (e.g. via AudioTrack), will do their
492 // own mixing/dynamic processing.
493 rtc::CritScope cs(&_callbackCritSect);
494 if (audio_sink_) {
495 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700496 audio_frame->data(), audio_frame->samples_per_channel_,
497 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
498 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800499 audio_sink_->OnData(data);
500 }
501 }
502
503 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800504 {
505 rtc::CritScope cs(&volume_settings_critsect_);
506 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800507 }
508
509 // Output volume scaling
510 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800511 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700512 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800513 }
514
kwiberg55b97fe2016-01-28 05:22:45 -0800515 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700516 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700517 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700518 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700519 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800520
solenberg2397b9a2017-09-22 06:48:10 -0700521 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800522 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700523 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800524 }
525
526 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700527 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800528
529 // Compute elapsed time.
530 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700531 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
532 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800533 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700534 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800535
niklase@google.com470e71d2011-07-07 08:21:25 +0000536 {
kwiberg55b97fe2016-01-28 05:22:45 -0800537 rtc::CritScope lock(&ts_stats_lock_);
538 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700539 audio_frame->ntp_time_ms_ =
540 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800541 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700542 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800543 // Compute |capture_start_ntp_time_ms_| so that
544 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
545 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700546 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000547 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000548 }
kwiberg55b97fe2016-01-28 05:22:45 -0800549 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000550
solenberg2397b9a2017-09-22 06:48:10 -0700551 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
552 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000553}
554
solenberg2397b9a2017-09-22 06:48:10 -0700555int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800556 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700557 return std::max(audio_coding_->ReceiveFrequency(),
558 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000559}
560
henrikaec6fbd22017-03-31 05:43:36 -0700561int32_t Channel::CreateChannel(Channel*& channel,
562 int32_t channelId,
563 uint32_t instanceId,
564 const VoEBase::ChannelConfig& config) {
solenberg88499ec2016-09-07 07:34:41 -0700565 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800566 if (channel == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200567 LOG(LS_ERROR) << "unable to allocate memory for new channel";
kwiberg55b97fe2016-01-28 05:22:45 -0800568 return -1;
569 }
570 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000571}
572
pbos@webrtc.org92135212013-05-14 08:31:39 +0000573Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000574 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700575 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800576 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100577 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700578 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800579 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100580 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800581 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100582 rtp_receive_statistics_(
583 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
584 rtp_receiver_(
585 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100586 this,
587 this,
588 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700589 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100590 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100591 _timeStamp(0), // This is just an offset, RTP module will add it's own
592 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100593 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100594 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100595 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100596 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100597 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
598 capture_start_rtp_time_stamp_(-1),
599 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100600 _moduleProcessThreadPtr(NULL),
601 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100602 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700603 input_mute_(false),
604 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100605 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100606 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800607 transport_overhead_per_packet_(0),
608 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100609 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100610 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100611 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700612 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800613 feedback_observer_proxy_(new TransportFeedbackProxy()),
614 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700615 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200616 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
617 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700618 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700619 use_twcc_plr_for_ana_(
620 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
solenberg88499ec2016-09-07 07:34:41 -0700621 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700622 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800623 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200624
kwiberg55b97fe2016-01-28 05:22:45 -0800625 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000626
kwiberg55b97fe2016-01-28 05:22:45 -0800627 RtpRtcp::Configuration configuration;
628 configuration.audio = true;
629 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800630 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800631 configuration.receive_statistics = rtp_receive_statistics_.get();
632 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800633 if (pacing_enabled_) {
634 configuration.paced_sender = rtp_packet_sender_proxy_.get();
635 configuration.transport_sequence_number_allocator =
636 seq_num_allocator_proxy_.get();
637 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
638 }
ivoc14d5dbe2016-07-04 07:06:55 -0700639 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800640 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200641 configuration.retransmission_rate_limiter =
642 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000643
kwiberg55b97fe2016-01-28 05:22:45 -0800644 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100645 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000646}
647
kwiberg55b97fe2016-01-28 05:22:45 -0800648Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700649 RTC_DCHECK(!channel_state_.Get().sending);
650 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000651}
652
kwiberg55b97fe2016-01-28 05:22:45 -0800653int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700654 RTC_DCHECK(construction_thread_.CalledOnValidThread());
niklase@google.com470e71d2011-07-07 08:21:25 +0000655
kwiberg55b97fe2016-01-28 05:22:45 -0800656 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000657
kwiberg55b97fe2016-01-28 05:22:45 -0800658 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000659
solenberg1c239d42017-09-29 06:00:28 -0700660 if (_moduleProcessThreadPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200661 LOG(LS_ERROR) << "Channel::Init() must call SetEngineInformation() first";
kwiberg55b97fe2016-01-28 05:22:45 -0800662 return -1;
663 }
664
665 // --- Add modules to process thread (for periodic schedulation)
666
tommidea489f2017-03-03 03:20:24 -0800667 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800668
669 // --- ACM initialization
670
671 if (audio_coding_->InitializeReceiver() == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700672 LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800673 return -1;
674 }
675
676 // --- RTP/RTCP module initialization
677
678 // Ensure that RTCP is enabled by default for the created channel.
679 // Note that, the module will keep generating RTCP until it is explicitly
680 // disabled by the user.
681 // After StopListen (when no sockets exists), RTCP packets will no longer
682 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700683 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800684 // RTCP is enabled by default.
685 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
686 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800687 if (audio_coding_->RegisterTransportCallback(this) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700688 LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800689 return -1;
690 }
691
kwiberg1c07c702017-03-27 07:15:49 -0700692 return 0;
693}
694
tommi0a2391f2017-03-21 02:31:51 -0700695void Channel::Terminate() {
696 RTC_DCHECK(construction_thread_.CalledOnValidThread());
697 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700698 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
699
700 StopSend();
701 StopPlayout();
702
tommi0a2391f2017-03-21 02:31:51 -0700703 // The order to safely shutdown modules in a channel is:
704 // 1. De-register callbacks in modules
705 // 2. De-register modules in process thread
706 // 3. Destroy modules
707 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200708 LOG(LS_WARNING) << "Terminate() failed to de-register transport callback"
709 << " (Audio coding module)";
tommi0a2391f2017-03-21 02:31:51 -0700710 }
711
tommi0a2391f2017-03-21 02:31:51 -0700712 // De-register modules in process thread
713 if (_moduleProcessThreadPtr)
714 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
715
716 // End of modules shutdown
717}
718
solenberg1c239d42017-09-29 06:00:28 -0700719int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800720 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700721 rtc::TaskQueue* encoder_queue) {
722 RTC_DCHECK(encoder_queue);
723 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800724 _moduleProcessThreadPtr = &moduleProcessThread;
725 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700726 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800727 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000728}
729
kwibergb7f89d62016-02-17 10:04:18 -0800730void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800731 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800732 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100733}
734
ossu29b1a8d2016-06-13 07:34:51 -0700735const rtc::scoped_refptr<AudioDecoderFactory>&
736Channel::GetAudioDecoderFactory() const {
737 return decoder_factory_;
738}
739
kwiberg55b97fe2016-01-28 05:22:45 -0800740int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800741 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000742 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800743 }
744
kwiberg55b97fe2016-01-28 05:22:45 -0800745 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800746
747 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000748}
749
kwiberg55b97fe2016-01-28 05:22:45 -0800750int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800751 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000752 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800753 }
754
kwiberg55b97fe2016-01-28 05:22:45 -0800755 channel_state_.SetPlaying(false);
756 _outputAudioLevel.Clear();
757
758 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000759}
760
kwiberg55b97fe2016-01-28 05:22:45 -0800761int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800762 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000763 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800764 }
765 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700766 {
767 // It is now OK to start posting tasks to the encoder task queue.
768 rtc::CritScope cs(&encoder_queue_lock_);
769 encoder_queue_is_active_ = true;
770 }
solenberg08b19df2017-02-15 00:42:31 -0800771 // Resume the previous sequence number which was reset by StopSend(). This
772 // needs to be done before |sending| is set to true on the RTP/RTCP module.
773 if (send_sequence_number_) {
774 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
775 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100776 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800777 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
solenberg1c239d42017-09-29 06:00:28 -0700778 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100779 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800780 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000781 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800782 return -1;
783 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000784
kwiberg55b97fe2016-01-28 05:22:45 -0800785 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000786}
787
henrikaec6fbd22017-03-31 05:43:36 -0700788void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800789 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700790 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800791 }
792 channel_state_.SetSending(false);
793
henrikaec6fbd22017-03-31 05:43:36 -0700794 // Post a task to the encoder thread which sets an event when the task is
795 // executed. We know that no more encoding tasks will be added to the task
796 // queue for this channel since sending is now deactivated. It means that,
797 // if we wait for the event to bet set, we know that no more pending tasks
798 // exists and it is therfore guaranteed that the task queue will never try
799 // to acccess and invalid channel object.
800 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700801
henrikaec6fbd22017-03-31 05:43:36 -0700802 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700803 {
804 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
805 // than this final "flush task" to be posted on the queue.
806 rtc::CritScope cs(&encoder_queue_lock_);
807 encoder_queue_is_active_ = false;
808 encoder_queue_->PostTask([&flush]() { flush.Set(); });
809 }
henrikaec6fbd22017-03-31 05:43:36 -0700810 flush.Wait(rtc::Event::kForever);
811
kwiberg55b97fe2016-01-28 05:22:45 -0800812 // Store the sequence number to be able to pick up the same sequence for
813 // the next StartSend(). This is needed for restarting device, otherwise
814 // it might cause libSRTP to complain about packets being replayed.
815 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
816 // CL is landed. See issue
817 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
818 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
819
820 // Reset sending SSRC and sequence number and triggers direct transmission
821 // of RTCP BYE
822 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700823 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800824 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100825 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000826}
827
ossu1ffbd6c2017-04-06 12:05:04 -0700828bool Channel::SetEncoder(int payload_type,
829 std::unique_ptr<AudioEncoder> encoder) {
830 RTC_DCHECK_GE(payload_type, 0);
831 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700832 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
833 // one for for us to keep track of sample rate and number of channels, etc.
834
835 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
836 // as well as some other things, so we collect this info and send it along.
837 CodecInst rtp_codec;
838 rtp_codec.pltype = payload_type;
839 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
840 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700841 // Seems unclear if it should be clock rate or sample rate. CodecInst
842 // supposedly carries the sample rate, but only clock rate seems sensible to
843 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700844 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
845 rtp_codec.pacsize = rtc::CheckedDivExact(
846 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
847 100);
848 rtp_codec.channels = encoder->NumChannels();
849 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700850
ossu76d29f92017-06-09 07:30:13 -0700851 // For audio encoding we need, instead, the actual sample rate of the codec.
852 // The rest of the information should be the same.
853 CodecInst send_codec = rtp_codec;
854 send_codec.plfreq = encoder->SampleRateHz();
855 cached_send_codec_.emplace(send_codec);
856
857 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700858 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700859 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200860 LOG(LS_ERROR)
861 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700862 return false;
863 }
864 }
865
866 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -0700867 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -0700868 return true;
869}
870
ossu20a4b3f2017-04-27 02:08:52 -0700871void Channel::ModifyEncoder(
872 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
873 audio_coding_->ModifyEncoder(modifier);
874}
875
kwiberg55b97fe2016-01-28 05:22:45 -0800876int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -0700877 if (cached_send_codec_) {
878 codec = *cached_send_codec_;
879 return 0;
880 } else {
ossu20a4b3f2017-04-27 02:08:52 -0700881 const CodecInst* send_codec = codec_manager_.GetCodecInst();
882 if (send_codec) {
883 codec = *send_codec;
884 return 0;
885 }
886 }
kwiberg1fd4a4a2015-11-03 11:20:50 -0800887 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +0000888}
889
kwiberg55b97fe2016-01-28 05:22:45 -0800890int32_t Channel::GetRecCodec(CodecInst& codec) {
891 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +0000892}
893
kwiberg55b97fe2016-01-28 05:22:45 -0800894int32_t Channel::SetSendCodec(const CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -0700895 if (!codec_manager_.RegisterEncoder(codec) ||
896 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200897 LOG(LS_ERROR) << "SetSendCodec() failed to register codec to ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800898 return -1;
899 }
900
901 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
902 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
903 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200904 LOG(LS_ERROR)
905 << "SetSendCodec() failed to register codec to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800906 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +0000907 }
kwiberg55b97fe2016-01-28 05:22:45 -0800908 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000909
ossu76d29f92017-06-09 07:30:13 -0700910 cached_send_codec_.reset();
911
kwiberg55b97fe2016-01-28 05:22:45 -0800912 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000913}
914
minyue78b4d562016-11-30 04:47:39 -0800915void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -0700916 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -0800917 if (*encoder) {
918 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -0800919 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -0800920 }
921 });
michaelt566d8202017-01-12 10:17:38 -0800922 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +0200923}
924
elad.alond12a8e12017-03-23 11:04:48 -0700925void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
926 if (!use_twcc_plr_for_ana_)
927 return;
minyue7e304322016-10-12 05:00:55 -0700928 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -0700929 if (*encoder) {
930 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
931 }
932 });
933}
934
elad.alondadb4dc2017-03-23 15:29:50 -0700935void Channel::OnRecoverableUplinkPacketLossRate(
936 float recoverable_packet_loss_rate) {
937 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
938 if (*encoder) {
939 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
940 recoverable_packet_loss_rate);
941 }
942 });
943}
944
elad.alond12a8e12017-03-23 11:04:48 -0700945void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
946 if (use_twcc_plr_for_ana_)
947 return;
948 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
949 if (*encoder) {
950 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
951 }
minyue7e304322016-10-12 05:00:55 -0700952 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000953}
954
kwiberg1c07c702017-03-27 07:15:49 -0700955void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
956 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
957 audio_coding_->SetReceiveCodecs(codecs);
958}
959
minyue7e304322016-10-12 05:00:55 -0700960bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
961 bool success = false;
962 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
963 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -0700964 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
965 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -0700966 }
967 });
968 return success;
969}
970
971void Channel::DisableAudioNetworkAdaptor() {
972 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
973 if (*encoder)
974 (*encoder)->DisableAudioNetworkAdaptor();
975 });
976}
977
978void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
979 int max_frame_length_ms) {
980 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
981 if (*encoder) {
982 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
983 max_frame_length_ms);
984 }
985 });
986}
987
solenberg1c239d42017-09-29 06:00:28 -0700988void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -0800989 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -0700990 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +0000991}
992
nisse657bab22017-02-21 06:28:10 -0800993void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -0800994 RTPHeader header;
995 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -0700996
997 // Store playout timestamp for the received RTP packet
998 UpdatePlayoutTimestamp(false);
999
1000 header.payload_type_frequency =
1001 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1002 if (header.payload_type_frequency >= 0) {
1003 bool in_order = IsPacketInOrder(header);
1004 rtp_receive_statistics_->IncomingPacket(
1005 header, packet.size(), IsPacketRetransmitted(header, in_order));
1006 rtp_payload_registry_->SetIncomingPayloadType(header);
1007
Niels Möller22ec9522017-10-05 08:39:15 +02001008 ReceivePacket(packet.data(), packet.size(), header);
solenberg946d8862017-09-21 04:02:53 -07001009 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001010}
1011
1012bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001013 size_t packet_length,
Niels Möller22ec9522017-10-05 08:39:15 +02001014 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001015 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001016 assert(packet_length >= header.headerLength);
1017 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001018 const auto pl =
1019 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1020 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001021 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001022 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001023 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Niels Möller22ec9522017-10-05 08:39:15 +02001024 pl->typeSpecific);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001025}
1026
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001027bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1028 StreamStatistician* statistician =
1029 rtp_receive_statistics_->GetStatistician(header.ssrc);
1030 if (!statistician)
1031 return false;
1032 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001033}
1034
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001035bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1036 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001037 StreamStatistician* statistician =
1038 rtp_receive_statistics_->GetStatistician(header.ssrc);
1039 if (!statistician)
1040 return false;
1041 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001042 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001043 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001044 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001045}
1046
mflodman3d7db262016-04-29 00:57:13 -07001047int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001048 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001049 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001050
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001051 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001052 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001053
Minyue2013aec2015-05-13 14:14:42 +02001054 int64_t rtt = GetRTT(true);
1055 if (rtt == 0) {
1056 // Waiting for valid RTT.
1057 return 0;
1058 }
Erik Språng737336d2016-07-29 12:59:36 +02001059
1060 int64_t nack_window_ms = rtt;
1061 if (nack_window_ms < kMinRetransmissionWindowMs) {
1062 nack_window_ms = kMinRetransmissionWindowMs;
1063 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1064 nack_window_ms = kMaxRetransmissionWindowMs;
1065 }
1066 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1067
minyue7e304322016-10-12 05:00:55 -07001068 // Invoke audio encoders OnReceivedRtt().
1069 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1070 if (*encoder)
1071 (*encoder)->OnReceivedRtt(rtt);
1072 });
1073
Minyue2013aec2015-05-13 14:14:42 +02001074 uint32_t ntp_secs = 0;
1075 uint32_t ntp_frac = 0;
1076 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001077 if (0 !=
1078 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1079 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001080 // Waiting for RTCP.
1081 return 0;
1082 }
1083
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001084 {
tommi31fc21f2016-01-21 10:37:37 -08001085 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001086 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001087 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001088 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001089}
1090
solenberg8d73f8c2017-03-08 01:52:20 -08001091int Channel::GetSpeechOutputLevel() const {
1092 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001093}
1094
solenberg8d73f8c2017-03-08 01:52:20 -08001095int Channel::GetSpeechOutputLevelFullRange() const {
1096 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001097}
1098
zsteine76bd3a2017-07-14 12:17:49 -07001099double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001100 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001101}
1102
1103double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001104 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001105}
1106
solenberg8d73f8c2017-03-08 01:52:20 -08001107void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001108 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001109 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001110}
1111
solenberg1c2af8e2016-03-24 10:36:00 -07001112bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001113 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001114 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001115}
1116
solenberg8d73f8c2017-03-08 01:52:20 -08001117void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001118 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001119 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001120}
1121
solenberg8842c3e2016-03-11 03:06:41 -08001122int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001123 RTC_DCHECK_LE(0, event);
1124 RTC_DCHECK_GE(255, event);
1125 RTC_DCHECK_LE(0, duration_ms);
1126 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001127 if (!Sending()) {
1128 return -1;
1129 }
solenberg8842c3e2016-03-11 03:06:41 -08001130 if (_rtpRtcpModule->SendTelephoneEventOutband(
1131 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001132 LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001133 return -1;
1134 }
1135 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001136}
1137
solenbergffbbcac2016-11-17 05:25:37 -08001138int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1139 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001140 RTC_DCHECK_LE(0, payload_type);
1141 RTC_DCHECK_GE(127, payload_type);
1142 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001143 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001144 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001145 memcpy(codec.plname, "telephone-event", 16);
1146 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1147 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1148 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001149 LOG(LS_ERROR) << "SetSendTelephoneEventPayloadType() failed to register "
1150 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001151 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001152 }
kwiberg55b97fe2016-01-28 05:22:45 -08001153 }
kwiberg55b97fe2016-01-28 05:22:45 -08001154 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001155}
1156
kwiberg55b97fe2016-01-28 05:22:45 -08001157int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001158 if (channel_state_.Get().sending) {
solenberg1c239d42017-09-29 06:00:28 -07001159 LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001160 return -1;
1161 }
1162 _rtpRtcpModule->SetSSRC(ssrc);
1163 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001164}
1165
kwiberg55b97fe2016-01-28 05:22:45 -08001166int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1167 ssrc = rtp_receiver_->SSRC();
1168 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001169}
1170
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001171int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001172 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001173 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001174}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001175
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001176int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1177 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001178 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1179 if (enable &&
1180 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1181 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001182 return -1;
1183 }
1184 return 0;
1185}
1186
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001187void Channel::EnableSendTransportSequenceNumber(int id) {
1188 int ret =
1189 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1190 RTC_DCHECK_EQ(0, ret);
1191}
1192
stefan3313ec92016-01-21 06:32:43 -08001193void Channel::EnableReceiveTransportSequenceNumber(int id) {
1194 rtp_header_parser_->DeregisterRtpHeaderExtension(
1195 kRtpExtensionTransportSequenceNumber);
1196 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1197 kRtpExtensionTransportSequenceNumber, id);
1198 RTC_DCHECK(ret);
1199}
1200
stefanbba9dec2016-02-01 04:39:55 -08001201void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001202 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001203 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001204 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1205 TransportFeedbackObserver* transport_feedback_observer =
1206 transport->transport_feedback_observer();
1207 PacketRouter* packet_router = transport->packet_router();
1208
stefanbba9dec2016-02-01 04:39:55 -08001209 RTC_DCHECK(rtp_packet_sender);
1210 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001211 RTC_DCHECK(packet_router);
1212 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001213 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001214 feedback_observer_proxy_->SetTransportFeedbackObserver(
1215 transport_feedback_observer);
1216 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1217 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1218 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001219 constexpr bool remb_candidate = false;
1220 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001221 packet_router_ = packet_router;
1222}
1223
stefanbba9dec2016-02-01 04:39:55 -08001224void Channel::RegisterReceiverCongestionControlObjects(
1225 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001226 RTC_DCHECK(packet_router);
1227 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001228 constexpr bool remb_candidate = false;
1229 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001230 packet_router_ = packet_router;
1231}
1232
nissefdbfdc92017-03-31 05:44:52 -07001233void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001234 RTC_DCHECK(packet_router_);
1235 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001236 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001237 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1238 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001239 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001240 packet_router_ = nullptr;
1241 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1242}
1243
nissefdbfdc92017-03-31 05:44:52 -07001244void Channel::ResetReceiverCongestionControlObjects() {
1245 RTC_DCHECK(packet_router_);
1246 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1247 packet_router_ = nullptr;
1248}
1249
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001250void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001251 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001252}
1253
kwiberg55b97fe2016-01-28 05:22:45 -08001254int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001255 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001256 LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001257 return -1;
1258 }
1259 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001260}
1261
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001262int Channel::GetRemoteRTCPReportBlocks(
1263 std::vector<ReportBlock>* report_blocks) {
1264 if (report_blocks == NULL) {
solenberg1c239d42017-09-29 06:00:28 -07001265 LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001266 return -1;
1267 }
1268
1269 // Get the report blocks from the latest received RTCP Sender or Receiver
1270 // Report. Each element in the vector contains the sender's SSRC and a
1271 // report block according to RFC 3550.
1272 std::vector<RTCPReportBlock> rtcp_report_blocks;
1273 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001274 return -1;
1275 }
1276
1277 if (rtcp_report_blocks.empty())
1278 return 0;
1279
1280 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1281 for (; it != rtcp_report_blocks.end(); ++it) {
1282 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001283 report_block.sender_SSRC = it->sender_ssrc;
1284 report_block.source_SSRC = it->source_ssrc;
1285 report_block.fraction_lost = it->fraction_lost;
1286 report_block.cumulative_num_packets_lost = it->packets_lost;
1287 report_block.extended_highest_sequence_number =
1288 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001289 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001290 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1291 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001292 report_blocks->push_back(report_block);
1293 }
1294 return 0;
1295}
1296
kwiberg55b97fe2016-01-28 05:22:45 -08001297int Channel::GetRTPStatistics(CallStatistics& stats) {
1298 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001299
kwiberg55b97fe2016-01-28 05:22:45 -08001300 // The jitter statistics is updated for each received RTP packet and is
1301 // based on received packets.
1302 RtcpStatistics statistics;
1303 StreamStatistician* statistician =
1304 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001305 if (statistician) {
1306 statistician->GetStatistics(&statistics,
1307 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001308 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001309
kwiberg55b97fe2016-01-28 05:22:45 -08001310 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001311 stats.cumulativeLost = statistics.packets_lost;
1312 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001313 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001314
kwiberg55b97fe2016-01-28 05:22:45 -08001315 // --- RTT
1316 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001317
kwiberg55b97fe2016-01-28 05:22:45 -08001318 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001319
kwiberg55b97fe2016-01-28 05:22:45 -08001320 size_t bytesSent(0);
1321 uint32_t packetsSent(0);
1322 size_t bytesReceived(0);
1323 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001324
kwiberg55b97fe2016-01-28 05:22:45 -08001325 if (statistician) {
1326 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1327 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001328
kwiberg55b97fe2016-01-28 05:22:45 -08001329 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001330 LOG(LS_WARNING) << "GetRTPStatistics() failed to retrieve RTP datacounters"
1331 << " => output will not be complete";
kwiberg55b97fe2016-01-28 05:22:45 -08001332 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001333
kwiberg55b97fe2016-01-28 05:22:45 -08001334 stats.bytesSent = bytesSent;
1335 stats.packetsSent = packetsSent;
1336 stats.bytesReceived = bytesReceived;
1337 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001338
kwiberg55b97fe2016-01-28 05:22:45 -08001339 // --- Timestamps
1340 {
1341 rtc::CritScope lock(&ts_stats_lock_);
1342 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1343 }
1344 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001345}
1346
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001347void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1348 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001349 // If pacing is enabled we always store packets.
1350 if (!pacing_enabled_)
1351 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001352 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001353 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001354 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001355 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001356 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001357}
1358
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001359// Called when we are missing one or more packets.
1360int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001361 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1362}
1363
henrikaec6fbd22017-03-31 05:43:36 -07001364void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001365 // Avoid posting any new tasks if sending was already stopped in StopSend().
1366 rtc::CritScope cs(&encoder_queue_lock_);
1367 if (!encoder_queue_is_active_) {
1368 return;
1369 }
henrikaec6fbd22017-03-31 05:43:36 -07001370 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1371 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1372 // either into pool of frames or into the task itself.
1373 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001374 // Profile time between when the audio frame is added to the task queue and
1375 // when the task is actually executed.
1376 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001377 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1378 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001379}
1380
henrikaec6fbd22017-03-31 05:43:36 -07001381void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1382 int sample_rate,
1383 size_t number_of_frames,
1384 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001385 // Avoid posting as new task if sending was already stopped in StopSend().
1386 rtc::CritScope cs(&encoder_queue_lock_);
1387 if (!encoder_queue_is_active_) {
1388 return;
1389 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001390 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001391 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001392 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
ossu950c1c92017-07-11 08:19:31 -07001393 // TODO(ossu): Investigate how this could happen. b/62909493
1394 if (result == 0) {
1395 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1396 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1397 } else {
1398 audio_frame->sample_rate_hz_ = sample_rate;
1399 audio_frame->num_channels_ = number_of_channels;
1400 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1401 RTC_NOTREACHED();
1402 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001403 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001404 sample_rate, &input_resampler_, audio_frame.get());
1405 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1406 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001407}
1408
henrikaec6fbd22017-03-31 05:43:36 -07001409void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1410 RTC_DCHECK_RUN_ON(encoder_queue_);
1411 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1412 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001413
henrika45802172017-09-28 09:39:34 +02001414 // Measure time between when the audio frame is added to the task queue and
1415 // when the task is actually executed. Goal is to keep track of unwanted
1416 // extra latency added by the task queue.
1417 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1418 audio_input->ElapsedProfileTimeMs());
1419
henrikaec6fbd22017-03-31 05:43:36 -07001420 bool is_muted = InputMute();
1421 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001422
kwiberg55b97fe2016-01-28 05:22:45 -08001423 if (_includeAudioLevelIndication) {
1424 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001425 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001426 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001427 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001428 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001429 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001430 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001431 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001432 }
kwiberg55b97fe2016-01-28 05:22:45 -08001433 }
solenberg1c2af8e2016-03-24 10:36:00 -07001434 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001435
henrikaec6fbd22017-03-31 05:43:36 -07001436 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001437
kwiberg55b97fe2016-01-28 05:22:45 -08001438 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001439 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001440 // This call will trigger AudioPacketizationCallback::SendData if encoding
1441 // is done and payload is ready for packetization and transmission.
1442 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001443 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1444 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1445 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001446 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001447
henrikaec6fbd22017-03-31 05:43:36 -07001448 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001449}
1450
solenberg7602aab2016-11-14 11:30:07 -08001451void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1452 RTC_DCHECK(!channel.channel() ||
1453 channel.channel()->ChannelId() != _channelId);
1454 rtc::CritScope lock(&assoc_send_channel_lock_);
1455 associate_send_channel_ = channel;
1456}
1457
Minyue2013aec2015-05-13 14:14:42 +02001458void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001459 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001460 Channel* channel = associate_send_channel_.channel();
1461 if (channel && channel->ChannelId() == channel_id) {
1462 // If this channel is associated with a send channel of the specified
1463 // Channel ID, disassociate with it.
1464 ChannelOwner ref(NULL);
1465 associate_send_channel_ = ref;
1466 }
1467}
1468
ivoc14d5dbe2016-07-04 07:06:55 -07001469void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1470 event_log_proxy_->SetEventLog(event_log);
1471}
1472
michaelt9332b7d2016-11-30 07:51:13 -08001473void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1474 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1475}
1476
nisse284542b2017-01-10 08:58:32 -08001477void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001478 size_t overhead_per_packet =
1479 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001480 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1481 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001482 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001483 }
1484 });
1485}
1486
1487void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001488 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001489 transport_overhead_per_packet_ = transport_overhead_per_packet;
1490 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001491}
1492
hbos3fd31fe2017-02-28 05:43:16 -08001493// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001494void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001495 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001496 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1497 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001498}
1499
kwiberg55b97fe2016-01-28 05:22:45 -08001500int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1501 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001502}
1503
wu@webrtc.org24301a62013-12-13 19:17:43 +00001504void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1505 audio_coding_->GetDecodingCallStatistics(stats);
1506}
1507
ivoce1198e02017-09-08 08:13:19 -07001508ANAStats Channel::GetANAStatistics() const {
1509 return audio_coding_->GetANAStats();
1510}
1511
solenberg358057b2015-11-27 10:46:42 -08001512uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001513 rtc::CritScope lock(&video_sync_lock_);
1514 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001515}
1516
kwiberg55b97fe2016-01-28 05:22:45 -08001517int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001518 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1519 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
solenberg1c239d42017-09-29 06:00:28 -07001520 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001521 return -1;
1522 }
1523 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001524 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001525 return -1;
1526 }
1527 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001528}
1529
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001530int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001531 uint32_t playout_timestamp_rtp = 0;
1532 {
tommi31fc21f2016-01-21 10:37:37 -08001533 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001534 playout_timestamp_rtp = playout_timestamp_rtp_;
1535 }
kwiberg55b97fe2016-01-28 05:22:45 -08001536 if (playout_timestamp_rtp == 0) {
solenberg1c239d42017-09-29 06:00:28 -07001537 LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001538 return -1;
1539 }
deadbeef74375882015-08-13 12:09:10 -07001540 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001541 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001542}
1543
kwiberg55b97fe2016-01-28 05:22:45 -08001544int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1545 RtpReceiver** rtp_receiver) const {
1546 *rtpRtcpModule = _rtpRtcpModule.get();
1547 *rtp_receiver = rtp_receiver_.get();
1548 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001549}
1550
deadbeef74375882015-08-13 12:09:10 -07001551void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001552 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001553
henrik.lundin96bd5022016-04-06 04:13:56 -07001554 if (!jitter_buffer_playout_timestamp_) {
1555 // This can happen if this channel has not received any RTP packets. In
1556 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001557 return;
1558 }
1559
1560 uint16_t delay_ms = 0;
1561 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001562 LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1563 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001564 return;
1565 }
1566
henrik.lundin96bd5022016-04-06 04:13:56 -07001567 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1568 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001569
1570 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001571 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001572
deadbeef74375882015-08-13 12:09:10 -07001573 {
tommi31fc21f2016-01-21 10:37:37 -08001574 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001575 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001576 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001577 }
1578 playout_delay_ms_ = delay_ms;
1579 }
1580}
1581
kwiberg55b97fe2016-01-28 05:22:45 -08001582void Channel::RegisterReceiveCodecsToRTPModule() {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001583 // TODO(kwiberg): Iterate over the factory's supported codecs instead?
1584 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001585 for (int idx = 0; idx < nSupportedCodecs; idx++) {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001586 CodecInst codec;
1587 if (audio_coding_->Codec(idx, &codec) == -1) {
1588 LOG(LS_WARNING) << "Unable to register codec #" << idx
1589 << " for RTP/RTCP receiver.";
1590 continue;
1591 }
1592 const SdpAudioFormat format = CodecInstToSdp(codec);
1593 if (!decoder_factory_->IsSupportedDecoder(format) ||
1594 rtp_receiver_->RegisterReceivePayload(codec.pltype, format) == -1) {
1595 LOG(LS_WARNING) << "Unable to register " << format
1596 << " for RTP/RTCP receiver.";
niklase@google.com470e71d2011-07-07 08:21:25 +00001597 }
kwiberg55b97fe2016-01-28 05:22:45 -08001598 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001599}
1600
kwiberg55b97fe2016-01-28 05:22:45 -08001601int Channel::SetSendRtpHeaderExtension(bool enable,
1602 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001603 unsigned char id) {
1604 int error = 0;
1605 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1606 if (enable) {
1607 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1608 }
1609 return error;
1610}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001611
ossue280cde2016-10-12 11:04:10 -07001612int Channel::GetRtpTimestampRateHz() const {
1613 const auto format = audio_coding_->ReceiveFormat();
1614 // Default to the playout frequency if we've not gotten any packets yet.
1615 // TODO(ossu): Zero clockrate can only happen if we've added an external
1616 // decoder for a format we don't support internally. Remove once that way of
1617 // adding decoders is gone!
1618 return (format && format->clockrate_hz != 0)
1619 ? format->clockrate_hz
1620 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001621}
1622
Minyue2013aec2015-05-13 14:14:42 +02001623int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001624 RtcpMode method = _rtpRtcpModule->RTCP();
1625 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001626 return 0;
1627 }
1628 std::vector<RTCPReportBlock> report_blocks;
1629 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001630
1631 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001632 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001633 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001634 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001635 Channel* channel = associate_send_channel_.channel();
1636 // Tries to get RTT from an associated channel. This is important for
1637 // receive-only channels.
1638 if (channel) {
1639 // To prevent infinite recursion and deadlock, calling GetRTT of
1640 // associate channel should always use "false" for argument:
1641 // |allow_associate_channel|.
1642 rtt = channel->GetRTT(false);
1643 }
1644 }
1645 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001646 }
1647
1648 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1649 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1650 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001651 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001652 break;
1653 }
1654 if (it == report_blocks.end()) {
1655 // We have not received packets with SSRC matching the report blocks.
1656 // To calculate RTT we try with the SSRC of the first report block.
1657 // This is very important for send-only channels where we don't know
1658 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001659 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001660 }
Minyue2013aec2015-05-13 14:14:42 +02001661
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001662 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001663 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001664 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001665 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1666 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001667 return 0;
1668 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001669 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001670}
1671
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001672} // namespace voe
1673} // namespace webrtc