blob: d978c457c9a4c22ed7495de282353b3cfdef7757 [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 Narest78609d52017-10-20 10:37:47 +0200218 void SetAccountForAudioPackets(bool account_for_audio) override {
219 RTC_NOTREACHED();
220 }
221
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100222 private:
223 rtc::ThreadChecker thread_checker_;
224 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700225 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100226};
227
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000228class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000229 public:
stefan7de8d642017-02-07 07:14:08 -0800230 explicit VoERtcpObserver(Channel* owner)
231 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000232 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000233
stefan7de8d642017-02-07 07:14:08 -0800234 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
235 rtc::CritScope lock(&crit_);
236 bandwidth_observer_ = bandwidth_observer;
237 }
238
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000239 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800240 rtc::CritScope lock(&crit_);
241 if (bandwidth_observer_) {
242 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
243 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000244 }
245
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000246 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
247 int64_t rtt,
248 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800249 {
250 rtc::CritScope lock(&crit_);
251 if (bandwidth_observer_) {
252 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
253 now_ms);
254 }
255 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000256 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
257 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
258 // report for VoiceEngine?
259 if (report_blocks.empty())
260 return;
261
262 int fraction_lost_aggregate = 0;
263 int total_number_of_packets = 0;
264
265 // If receiving multiple report blocks, calculate the weighted average based
266 // on the number of packets a report refers to.
267 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
268 block_it != report_blocks.end(); ++block_it) {
269 // Find the previous extended high sequence number for this remote SSRC,
270 // to calculate the number of RTP packets this report refers to. Ignore if
271 // we haven't seen this SSRC before.
272 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700273 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000274 int number_of_packets = 0;
275 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700276 number_of_packets =
277 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000278 }
srte3e69e5c2017-08-09 06:13:45 -0700279 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000280 total_number_of_packets += number_of_packets;
281
srte3e69e5c2017-08-09 06:13:45 -0700282 extended_max_sequence_number_[block_it->source_ssrc] =
283 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000284 }
285 int weighted_fraction_lost = 0;
286 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800287 weighted_fraction_lost =
288 (fraction_lost_aggregate + total_number_of_packets / 2) /
289 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000290 }
elad.alond12a8e12017-03-23 11:04:48 -0700291 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000292 }
293
294 private:
295 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000296 // Maps remote side ssrc to extended highest sequence number received.
297 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800298 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700299 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000300};
301
henrikaec6fbd22017-03-31 05:43:36 -0700302class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
303 public:
304 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
305 Channel* channel)
306 : audio_frame_(std::move(audio_frame)), channel_(channel) {
307 RTC_DCHECK(channel_);
308 }
309
310 private:
311 bool Run() override {
312 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
313 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
314 return true;
315 }
316
317 std::unique_ptr<AudioFrame> audio_frame_;
318 Channel* const channel_;
319};
320
kwiberg55b97fe2016-01-28 05:22:45 -0800321int32_t Channel::SendData(FrameType frameType,
322 uint8_t payloadType,
323 uint32_t timeStamp,
324 const uint8_t* payloadData,
325 size_t payloadSize,
326 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700327 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800328 if (_includeAudioLevelIndication) {
329 // Store current audio level in the RTP/RTCP module.
330 // The level will be used in combination with voice-activity state
331 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800332 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800333 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000334
kwiberg55b97fe2016-01-28 05:22:45 -0800335 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
336 // packetization.
337 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700338 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800339 (FrameType&)frameType, payloadType, timeStamp,
340 // Leaving the time when this frame was
341 // received from the capture device as
342 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700343 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
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
Henrik Lundin9bde6b72017-11-02 15:01:56 +0100551 {
552 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
553 rtc::CritScope lock(&video_sync_lock_);
554 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
555 jitter_buffer_delay + playout_delay_ms_);
556 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
557 jitter_buffer_delay);
558 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
559 playout_delay_ms_);
560 }
561
solenberg2397b9a2017-09-22 06:48:10 -0700562 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
563 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000564}
565
solenberg2397b9a2017-09-22 06:48:10 -0700566int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800567 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700568 return std::max(audio_coding_->ReceiveFrequency(),
569 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000570}
571
henrikaec6fbd22017-03-31 05:43:36 -0700572int32_t Channel::CreateChannel(Channel*& channel,
573 int32_t channelId,
574 uint32_t instanceId,
575 const VoEBase::ChannelConfig& config) {
solenberg88499ec2016-09-07 07:34:41 -0700576 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800577 if (channel == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200578 LOG(LS_ERROR) << "unable to allocate memory for new channel";
kwiberg55b97fe2016-01-28 05:22:45 -0800579 return -1;
580 }
581 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000582}
583
pbos@webrtc.org92135212013-05-14 08:31:39 +0000584Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000585 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700586 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800587 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100588 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700589 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800590 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100591 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800592 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100593 rtp_receive_statistics_(
594 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
595 rtp_receiver_(
596 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100597 this,
598 this,
599 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700600 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100601 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100602 _timeStamp(0), // This is just an offset, RTP module will add it's own
603 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100604 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100605 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100606 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100607 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100608 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
609 capture_start_rtp_time_stamp_(-1),
610 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100611 _moduleProcessThreadPtr(NULL),
612 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100613 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700614 input_mute_(false),
615 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100616 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100617 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800618 transport_overhead_per_packet_(0),
619 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100620 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100621 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100622 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700623 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800624 feedback_observer_proxy_(new TransportFeedbackProxy()),
625 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700626 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200627 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
628 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700629 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700630 use_twcc_plr_for_ana_(
631 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
solenberg88499ec2016-09-07 07:34:41 -0700632 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700633 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800634 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200635
kwiberg55b97fe2016-01-28 05:22:45 -0800636 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000637
kwiberg55b97fe2016-01-28 05:22:45 -0800638 RtpRtcp::Configuration configuration;
639 configuration.audio = true;
640 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800641 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800642 configuration.receive_statistics = rtp_receive_statistics_.get();
643 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800644 if (pacing_enabled_) {
645 configuration.paced_sender = rtp_packet_sender_proxy_.get();
646 configuration.transport_sequence_number_allocator =
647 seq_num_allocator_proxy_.get();
648 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
649 }
ivoc14d5dbe2016-07-04 07:06:55 -0700650 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800651 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200652 configuration.retransmission_rate_limiter =
653 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000654
kwiberg55b97fe2016-01-28 05:22:45 -0800655 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100656 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000657}
658
kwiberg55b97fe2016-01-28 05:22:45 -0800659Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700660 RTC_DCHECK(!channel_state_.Get().sending);
661 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000662}
663
kwiberg55b97fe2016-01-28 05:22:45 -0800664int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700665 RTC_DCHECK(construction_thread_.CalledOnValidThread());
niklase@google.com470e71d2011-07-07 08:21:25 +0000666
kwiberg55b97fe2016-01-28 05:22:45 -0800667 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000668
kwiberg55b97fe2016-01-28 05:22:45 -0800669 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000670
solenberg1c239d42017-09-29 06:00:28 -0700671 if (_moduleProcessThreadPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200672 LOG(LS_ERROR) << "Channel::Init() must call SetEngineInformation() first";
kwiberg55b97fe2016-01-28 05:22:45 -0800673 return -1;
674 }
675
676 // --- Add modules to process thread (for periodic schedulation)
677
tommidea489f2017-03-03 03:20:24 -0800678 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800679
680 // --- ACM initialization
681
682 if (audio_coding_->InitializeReceiver() == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700683 LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800684 return -1;
685 }
686
687 // --- RTP/RTCP module initialization
688
689 // Ensure that RTCP is enabled by default for the created channel.
690 // Note that, the module will keep generating RTCP until it is explicitly
691 // disabled by the user.
692 // After StopListen (when no sockets exists), RTCP packets will no longer
693 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700694 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800695 // RTCP is enabled by default.
696 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
697 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800698 if (audio_coding_->RegisterTransportCallback(this) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700699 LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800700 return -1;
701 }
702
kwiberg1c07c702017-03-27 07:15:49 -0700703 return 0;
704}
705
tommi0a2391f2017-03-21 02:31:51 -0700706void Channel::Terminate() {
707 RTC_DCHECK(construction_thread_.CalledOnValidThread());
708 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700709 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
710
711 StopSend();
712 StopPlayout();
713
tommi0a2391f2017-03-21 02:31:51 -0700714 // The order to safely shutdown modules in a channel is:
715 // 1. De-register callbacks in modules
716 // 2. De-register modules in process thread
717 // 3. Destroy modules
718 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200719 LOG(LS_WARNING) << "Terminate() failed to de-register transport callback"
720 << " (Audio coding module)";
tommi0a2391f2017-03-21 02:31:51 -0700721 }
722
tommi0a2391f2017-03-21 02:31:51 -0700723 // De-register modules in process thread
724 if (_moduleProcessThreadPtr)
725 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
726
727 // End of modules shutdown
728}
729
solenberg1c239d42017-09-29 06:00:28 -0700730int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800731 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700732 rtc::TaskQueue* encoder_queue) {
733 RTC_DCHECK(encoder_queue);
734 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800735 _moduleProcessThreadPtr = &moduleProcessThread;
736 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700737 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800738 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000739}
740
kwibergb7f89d62016-02-17 10:04:18 -0800741void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800742 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800743 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100744}
745
ossu29b1a8d2016-06-13 07:34:51 -0700746const rtc::scoped_refptr<AudioDecoderFactory>&
747Channel::GetAudioDecoderFactory() const {
748 return decoder_factory_;
749}
750
kwiberg55b97fe2016-01-28 05:22:45 -0800751int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800752 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000753 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800754 }
755
kwiberg55b97fe2016-01-28 05:22:45 -0800756 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800757
758 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000759}
760
kwiberg55b97fe2016-01-28 05:22:45 -0800761int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800762 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000763 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800764 }
765
kwiberg55b97fe2016-01-28 05:22:45 -0800766 channel_state_.SetPlaying(false);
767 _outputAudioLevel.Clear();
768
769 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000770}
771
kwiberg55b97fe2016-01-28 05:22:45 -0800772int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800773 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000774 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800775 }
776 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700777 {
778 // It is now OK to start posting tasks to the encoder task queue.
779 rtc::CritScope cs(&encoder_queue_lock_);
780 encoder_queue_is_active_ = true;
781 }
solenberg08b19df2017-02-15 00:42:31 -0800782 // Resume the previous sequence number which was reset by StopSend(). This
783 // needs to be done before |sending| is set to true on the RTP/RTCP module.
784 if (send_sequence_number_) {
785 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
786 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100787 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800788 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
solenberg1c239d42017-09-29 06:00:28 -0700789 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100790 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800791 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000792 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800793 return -1;
794 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000795
kwiberg55b97fe2016-01-28 05:22:45 -0800796 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000797}
798
henrikaec6fbd22017-03-31 05:43:36 -0700799void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800800 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700801 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800802 }
803 channel_state_.SetSending(false);
804
henrikaec6fbd22017-03-31 05:43:36 -0700805 // Post a task to the encoder thread which sets an event when the task is
806 // executed. We know that no more encoding tasks will be added to the task
807 // queue for this channel since sending is now deactivated. It means that,
808 // if we wait for the event to bet set, we know that no more pending tasks
809 // exists and it is therfore guaranteed that the task queue will never try
810 // to acccess and invalid channel object.
811 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700812
henrikaec6fbd22017-03-31 05:43:36 -0700813 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700814 {
815 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
816 // than this final "flush task" to be posted on the queue.
817 rtc::CritScope cs(&encoder_queue_lock_);
818 encoder_queue_is_active_ = false;
819 encoder_queue_->PostTask([&flush]() { flush.Set(); });
820 }
henrikaec6fbd22017-03-31 05:43:36 -0700821 flush.Wait(rtc::Event::kForever);
822
kwiberg55b97fe2016-01-28 05:22:45 -0800823 // Store the sequence number to be able to pick up the same sequence for
824 // the next StartSend(). This is needed for restarting device, otherwise
825 // it might cause libSRTP to complain about packets being replayed.
826 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
827 // CL is landed. See issue
828 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
829 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
830
831 // Reset sending SSRC and sequence number and triggers direct transmission
832 // of RTCP BYE
833 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700834 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800835 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100836 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000837}
838
ossu1ffbd6c2017-04-06 12:05:04 -0700839bool Channel::SetEncoder(int payload_type,
840 std::unique_ptr<AudioEncoder> encoder) {
841 RTC_DCHECK_GE(payload_type, 0);
842 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700843 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
844 // one for for us to keep track of sample rate and number of channels, etc.
845
846 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
847 // as well as some other things, so we collect this info and send it along.
848 CodecInst rtp_codec;
849 rtp_codec.pltype = payload_type;
850 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
851 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700852 // Seems unclear if it should be clock rate or sample rate. CodecInst
853 // supposedly carries the sample rate, but only clock rate seems sensible to
854 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700855 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
856 rtp_codec.pacsize = rtc::CheckedDivExact(
857 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
858 100);
859 rtp_codec.channels = encoder->NumChannels();
860 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700861
Karl Wiberg88182372017-10-17 01:02:46 +0200862 cached_encoder_props_.emplace(
863 EncoderProps{encoder->SampleRateHz(), encoder->NumChannels()});
ossu76d29f92017-06-09 07:30:13 -0700864
865 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700866 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700867 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200868 LOG(LS_ERROR)
869 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700870 return false;
871 }
872 }
873
874 audio_coding_->SetEncoder(std::move(encoder));
875 return true;
876}
877
ossu20a4b3f2017-04-27 02:08:52 -0700878void Channel::ModifyEncoder(
879 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
880 audio_coding_->ModifyEncoder(modifier);
881}
882
Karl Wiberg88182372017-10-17 01:02:46 +0200883rtc::Optional<Channel::EncoderProps> Channel::GetEncoderProps() const {
884 return cached_encoder_props_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000885}
886
kwiberg55b97fe2016-01-28 05:22:45 -0800887int32_t Channel::GetRecCodec(CodecInst& codec) {
888 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +0000889}
890
minyue78b4d562016-11-30 04:47:39 -0800891void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -0700892 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -0800893 if (*encoder) {
894 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -0800895 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -0800896 }
897 });
michaelt566d8202017-01-12 10:17:38 -0800898 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +0200899}
900
elad.alond12a8e12017-03-23 11:04:48 -0700901void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
902 if (!use_twcc_plr_for_ana_)
903 return;
minyue7e304322016-10-12 05:00:55 -0700904 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -0700905 if (*encoder) {
906 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
907 }
908 });
909}
910
elad.alondadb4dc2017-03-23 15:29:50 -0700911void Channel::OnRecoverableUplinkPacketLossRate(
912 float recoverable_packet_loss_rate) {
913 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
914 if (*encoder) {
915 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
916 recoverable_packet_loss_rate);
917 }
918 });
919}
920
elad.alond12a8e12017-03-23 11:04:48 -0700921void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
922 if (use_twcc_plr_for_ana_)
923 return;
924 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
925 if (*encoder) {
926 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
927 }
minyue7e304322016-10-12 05:00:55 -0700928 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000929}
930
kwiberg1c07c702017-03-27 07:15:49 -0700931void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
932 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
933 audio_coding_->SetReceiveCodecs(codecs);
934}
935
minyue7e304322016-10-12 05:00:55 -0700936bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
937 bool success = false;
938 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
939 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -0700940 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
941 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -0700942 }
943 });
944 return success;
945}
946
947void Channel::DisableAudioNetworkAdaptor() {
948 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
949 if (*encoder)
950 (*encoder)->DisableAudioNetworkAdaptor();
951 });
952}
953
954void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
955 int max_frame_length_ms) {
956 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
957 if (*encoder) {
958 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
959 max_frame_length_ms);
960 }
961 });
962}
963
solenberg1c239d42017-09-29 06:00:28 -0700964void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -0800965 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -0700966 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +0000967}
968
nisse657bab22017-02-21 06:28:10 -0800969void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -0800970 RTPHeader header;
971 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -0700972
973 // Store playout timestamp for the received RTP packet
974 UpdatePlayoutTimestamp(false);
975
976 header.payload_type_frequency =
977 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
978 if (header.payload_type_frequency >= 0) {
979 bool in_order = IsPacketInOrder(header);
980 rtp_receive_statistics_->IncomingPacket(
981 header, packet.size(), IsPacketRetransmitted(header, in_order));
982 rtp_payload_registry_->SetIncomingPayloadType(header);
983
Niels Möller22ec9522017-10-05 08:39:15 +0200984 ReceivePacket(packet.data(), packet.size(), header);
solenberg946d8862017-09-21 04:02:53 -0700985 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000986}
987
988bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000989 size_t packet_length,
Niels Möller22ec9522017-10-05 08:39:15 +0200990 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000991 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000992 assert(packet_length >= header.headerLength);
993 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +0200994 const auto pl =
995 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
996 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000997 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +0000998 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000999 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Niels Möller22ec9522017-10-05 08:39:15 +02001000 pl->typeSpecific);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001001}
1002
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001003bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1004 StreamStatistician* statistician =
1005 rtp_receive_statistics_->GetStatistician(header.ssrc);
1006 if (!statistician)
1007 return false;
1008 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001009}
1010
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001011bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1012 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001013 StreamStatistician* statistician =
1014 rtp_receive_statistics_->GetStatistician(header.ssrc);
1015 if (!statistician)
1016 return false;
1017 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001018 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001019 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001020 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001021}
1022
mflodman3d7db262016-04-29 00:57:13 -07001023int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001024 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001025 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001026
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001027 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001028 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001029
Minyue2013aec2015-05-13 14:14:42 +02001030 int64_t rtt = GetRTT(true);
1031 if (rtt == 0) {
1032 // Waiting for valid RTT.
1033 return 0;
1034 }
Erik Språng737336d2016-07-29 12:59:36 +02001035
1036 int64_t nack_window_ms = rtt;
1037 if (nack_window_ms < kMinRetransmissionWindowMs) {
1038 nack_window_ms = kMinRetransmissionWindowMs;
1039 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1040 nack_window_ms = kMaxRetransmissionWindowMs;
1041 }
1042 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1043
minyue7e304322016-10-12 05:00:55 -07001044 // Invoke audio encoders OnReceivedRtt().
1045 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1046 if (*encoder)
1047 (*encoder)->OnReceivedRtt(rtt);
1048 });
1049
Minyue2013aec2015-05-13 14:14:42 +02001050 uint32_t ntp_secs = 0;
1051 uint32_t ntp_frac = 0;
1052 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001053 if (0 !=
1054 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1055 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001056 // Waiting for RTCP.
1057 return 0;
1058 }
1059
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001060 {
tommi31fc21f2016-01-21 10:37:37 -08001061 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001062 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001063 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001064 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001065}
1066
solenberg8d73f8c2017-03-08 01:52:20 -08001067int Channel::GetSpeechOutputLevel() const {
1068 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001069}
1070
solenberg8d73f8c2017-03-08 01:52:20 -08001071int Channel::GetSpeechOutputLevelFullRange() const {
1072 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001073}
1074
zsteine76bd3a2017-07-14 12:17:49 -07001075double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001076 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001077}
1078
1079double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001080 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001081}
1082
solenberg8d73f8c2017-03-08 01:52:20 -08001083void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001084 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001085 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001086}
1087
solenberg1c2af8e2016-03-24 10:36:00 -07001088bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001089 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001090 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001091}
1092
solenberg8d73f8c2017-03-08 01:52:20 -08001093void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001094 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001095 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001096}
1097
solenberg8842c3e2016-03-11 03:06:41 -08001098int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001099 RTC_DCHECK_LE(0, event);
1100 RTC_DCHECK_GE(255, event);
1101 RTC_DCHECK_LE(0, duration_ms);
1102 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001103 if (!Sending()) {
1104 return -1;
1105 }
solenberg8842c3e2016-03-11 03:06:41 -08001106 if (_rtpRtcpModule->SendTelephoneEventOutband(
1107 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001108 LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001109 return -1;
1110 }
1111 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001112}
1113
solenbergffbbcac2016-11-17 05:25:37 -08001114int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1115 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001116 RTC_DCHECK_LE(0, payload_type);
1117 RTC_DCHECK_GE(127, payload_type);
1118 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001119 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001120 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001121 memcpy(codec.plname, "telephone-event", 16);
1122 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1123 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1124 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001125 LOG(LS_ERROR) << "SetSendTelephoneEventPayloadType() failed to register "
1126 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001127 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001128 }
kwiberg55b97fe2016-01-28 05:22:45 -08001129 }
kwiberg55b97fe2016-01-28 05:22:45 -08001130 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001131}
1132
kwiberg55b97fe2016-01-28 05:22:45 -08001133int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001134 if (channel_state_.Get().sending) {
solenberg1c239d42017-09-29 06:00:28 -07001135 LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001136 return -1;
1137 }
1138 _rtpRtcpModule->SetSSRC(ssrc);
1139 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001140}
1141
kwiberg55b97fe2016-01-28 05:22:45 -08001142int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1143 ssrc = rtp_receiver_->SSRC();
1144 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001145}
1146
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001147int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001148 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001149 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001150}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001151
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001152int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1153 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001154 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1155 if (enable &&
1156 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1157 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001158 return -1;
1159 }
1160 return 0;
1161}
1162
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001163void Channel::EnableSendTransportSequenceNumber(int id) {
1164 int ret =
1165 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1166 RTC_DCHECK_EQ(0, ret);
1167}
1168
stefan3313ec92016-01-21 06:32:43 -08001169void Channel::EnableReceiveTransportSequenceNumber(int id) {
1170 rtp_header_parser_->DeregisterRtpHeaderExtension(
1171 kRtpExtensionTransportSequenceNumber);
1172 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1173 kRtpExtensionTransportSequenceNumber, id);
1174 RTC_DCHECK(ret);
1175}
1176
stefanbba9dec2016-02-01 04:39:55 -08001177void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001178 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001179 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001180 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1181 TransportFeedbackObserver* transport_feedback_observer =
1182 transport->transport_feedback_observer();
1183 PacketRouter* packet_router = transport->packet_router();
1184
stefanbba9dec2016-02-01 04:39:55 -08001185 RTC_DCHECK(rtp_packet_sender);
1186 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001187 RTC_DCHECK(packet_router);
1188 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001189 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001190 feedback_observer_proxy_->SetTransportFeedbackObserver(
1191 transport_feedback_observer);
1192 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1193 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1194 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001195 constexpr bool remb_candidate = false;
1196 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001197 packet_router_ = packet_router;
1198}
1199
stefanbba9dec2016-02-01 04:39:55 -08001200void Channel::RegisterReceiverCongestionControlObjects(
1201 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001202 RTC_DCHECK(packet_router);
1203 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001204 constexpr bool remb_candidate = false;
1205 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001206 packet_router_ = packet_router;
1207}
1208
nissefdbfdc92017-03-31 05:44:52 -07001209void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001210 RTC_DCHECK(packet_router_);
1211 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001212 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001213 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1214 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001215 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001216 packet_router_ = nullptr;
1217 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1218}
1219
nissefdbfdc92017-03-31 05:44:52 -07001220void Channel::ResetReceiverCongestionControlObjects() {
1221 RTC_DCHECK(packet_router_);
1222 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1223 packet_router_ = nullptr;
1224}
1225
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001226void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001227 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001228}
1229
kwiberg55b97fe2016-01-28 05:22:45 -08001230int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001231 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001232 LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001233 return -1;
1234 }
1235 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001236}
1237
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001238int Channel::GetRemoteRTCPReportBlocks(
1239 std::vector<ReportBlock>* report_blocks) {
1240 if (report_blocks == NULL) {
solenberg1c239d42017-09-29 06:00:28 -07001241 LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001242 return -1;
1243 }
1244
1245 // Get the report blocks from the latest received RTCP Sender or Receiver
1246 // Report. Each element in the vector contains the sender's SSRC and a
1247 // report block according to RFC 3550.
1248 std::vector<RTCPReportBlock> rtcp_report_blocks;
1249 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001250 return -1;
1251 }
1252
1253 if (rtcp_report_blocks.empty())
1254 return 0;
1255
1256 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1257 for (; it != rtcp_report_blocks.end(); ++it) {
1258 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001259 report_block.sender_SSRC = it->sender_ssrc;
1260 report_block.source_SSRC = it->source_ssrc;
1261 report_block.fraction_lost = it->fraction_lost;
1262 report_block.cumulative_num_packets_lost = it->packets_lost;
1263 report_block.extended_highest_sequence_number =
1264 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001265 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001266 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1267 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001268 report_blocks->push_back(report_block);
1269 }
1270 return 0;
1271}
1272
kwiberg55b97fe2016-01-28 05:22:45 -08001273int Channel::GetRTPStatistics(CallStatistics& stats) {
1274 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001275
kwiberg55b97fe2016-01-28 05:22:45 -08001276 // The jitter statistics is updated for each received RTP packet and is
1277 // based on received packets.
1278 RtcpStatistics statistics;
1279 StreamStatistician* statistician =
1280 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001281 if (statistician) {
1282 statistician->GetStatistics(&statistics,
1283 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001284 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001285
kwiberg55b97fe2016-01-28 05:22:45 -08001286 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001287 stats.cumulativeLost = statistics.packets_lost;
1288 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001289 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001290
kwiberg55b97fe2016-01-28 05:22:45 -08001291 // --- RTT
1292 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001293
kwiberg55b97fe2016-01-28 05:22:45 -08001294 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001295
kwiberg55b97fe2016-01-28 05:22:45 -08001296 size_t bytesSent(0);
1297 uint32_t packetsSent(0);
1298 size_t bytesReceived(0);
1299 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001300
kwiberg55b97fe2016-01-28 05:22:45 -08001301 if (statistician) {
1302 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1303 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001304
kwiberg55b97fe2016-01-28 05:22:45 -08001305 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001306 LOG(LS_WARNING) << "GetRTPStatistics() failed to retrieve RTP datacounters"
1307 << " => output will not be complete";
kwiberg55b97fe2016-01-28 05:22:45 -08001308 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001309
kwiberg55b97fe2016-01-28 05:22:45 -08001310 stats.bytesSent = bytesSent;
1311 stats.packetsSent = packetsSent;
1312 stats.bytesReceived = bytesReceived;
1313 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001314
kwiberg55b97fe2016-01-28 05:22:45 -08001315 // --- Timestamps
1316 {
1317 rtc::CritScope lock(&ts_stats_lock_);
1318 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1319 }
1320 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001321}
1322
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001323void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1324 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001325 // If pacing is enabled we always store packets.
1326 if (!pacing_enabled_)
1327 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001328 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001329 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001330 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001331 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001332 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001333}
1334
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001335// Called when we are missing one or more packets.
1336int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001337 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1338}
1339
henrikaec6fbd22017-03-31 05:43:36 -07001340void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001341 // Avoid posting any new tasks if sending was already stopped in StopSend().
1342 rtc::CritScope cs(&encoder_queue_lock_);
1343 if (!encoder_queue_is_active_) {
1344 return;
1345 }
henrikaec6fbd22017-03-31 05:43:36 -07001346 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1347 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1348 // either into pool of frames or into the task itself.
1349 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001350 // Profile time between when the audio frame is added to the task queue and
1351 // when the task is actually executed.
1352 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001353 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1354 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001355}
1356
henrikaec6fbd22017-03-31 05:43:36 -07001357void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1358 int sample_rate,
1359 size_t number_of_frames,
1360 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001361 // Avoid posting as new task if sending was already stopped in StopSend().
1362 rtc::CritScope cs(&encoder_queue_lock_);
1363 if (!encoder_queue_is_active_) {
1364 return;
1365 }
henrikaec6fbd22017-03-31 05:43:36 -07001366 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
Karl Wiberg88182372017-10-17 01:02:46 +02001367 const auto props = GetEncoderProps();
1368 RTC_CHECK(props);
1369 audio_frame->sample_rate_hz_ = std::min(props->sample_rate_hz, sample_rate);
1370 audio_frame->num_channels_ =
1371 std::min(props->num_channels, number_of_channels);
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001372 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001373 sample_rate, &input_resampler_, audio_frame.get());
1374 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1375 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001376}
1377
henrikaec6fbd22017-03-31 05:43:36 -07001378void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1379 RTC_DCHECK_RUN_ON(encoder_queue_);
1380 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1381 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001382
henrika45802172017-09-28 09:39:34 +02001383 // Measure time between when the audio frame is added to the task queue and
1384 // when the task is actually executed. Goal is to keep track of unwanted
1385 // extra latency added by the task queue.
1386 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1387 audio_input->ElapsedProfileTimeMs());
1388
henrikaec6fbd22017-03-31 05:43:36 -07001389 bool is_muted = InputMute();
1390 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001391
kwiberg55b97fe2016-01-28 05:22:45 -08001392 if (_includeAudioLevelIndication) {
1393 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001394 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001395 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001396 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001397 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001398 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001399 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001400 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001401 }
kwiberg55b97fe2016-01-28 05:22:45 -08001402 }
solenberg1c2af8e2016-03-24 10:36:00 -07001403 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001404
henrikaec6fbd22017-03-31 05:43:36 -07001405 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001406
kwiberg55b97fe2016-01-28 05:22:45 -08001407 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001408 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001409 // This call will trigger AudioPacketizationCallback::SendData if encoding
1410 // is done and payload is ready for packetization and transmission.
1411 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001412 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1413 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1414 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001415 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001416
henrikaec6fbd22017-03-31 05:43:36 -07001417 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001418}
1419
solenberg7602aab2016-11-14 11:30:07 -08001420void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1421 RTC_DCHECK(!channel.channel() ||
1422 channel.channel()->ChannelId() != _channelId);
1423 rtc::CritScope lock(&assoc_send_channel_lock_);
1424 associate_send_channel_ = channel;
1425}
1426
Minyue2013aec2015-05-13 14:14:42 +02001427void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001428 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001429 Channel* channel = associate_send_channel_.channel();
1430 if (channel && channel->ChannelId() == channel_id) {
1431 // If this channel is associated with a send channel of the specified
1432 // Channel ID, disassociate with it.
1433 ChannelOwner ref(NULL);
1434 associate_send_channel_ = ref;
1435 }
1436}
1437
ivoc14d5dbe2016-07-04 07:06:55 -07001438void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1439 event_log_proxy_->SetEventLog(event_log);
1440}
1441
michaelt9332b7d2016-11-30 07:51:13 -08001442void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1443 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1444}
1445
nisse284542b2017-01-10 08:58:32 -08001446void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001447 size_t overhead_per_packet =
1448 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001449 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1450 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001451 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001452 }
1453 });
1454}
1455
1456void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001457 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001458 transport_overhead_per_packet_ = transport_overhead_per_packet;
1459 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001460}
1461
hbos3fd31fe2017-02-28 05:43:16 -08001462// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001463void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001464 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001465 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1466 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001467}
1468
kwiberg55b97fe2016-01-28 05:22:45 -08001469int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1470 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001471}
1472
wu@webrtc.org24301a62013-12-13 19:17:43 +00001473void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1474 audio_coding_->GetDecodingCallStatistics(stats);
1475}
1476
ivoce1198e02017-09-08 08:13:19 -07001477ANAStats Channel::GetANAStatistics() const {
1478 return audio_coding_->GetANAStats();
1479}
1480
solenberg358057b2015-11-27 10:46:42 -08001481uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001482 rtc::CritScope lock(&video_sync_lock_);
1483 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001484}
1485
kwiberg55b97fe2016-01-28 05:22:45 -08001486int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001487 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1488 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
solenberg1c239d42017-09-29 06:00:28 -07001489 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001490 return -1;
1491 }
1492 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001493 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001494 return -1;
1495 }
1496 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001497}
1498
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001499int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001500 uint32_t playout_timestamp_rtp = 0;
1501 {
tommi31fc21f2016-01-21 10:37:37 -08001502 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001503 playout_timestamp_rtp = playout_timestamp_rtp_;
1504 }
kwiberg55b97fe2016-01-28 05:22:45 -08001505 if (playout_timestamp_rtp == 0) {
solenberg1c239d42017-09-29 06:00:28 -07001506 LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001507 return -1;
1508 }
deadbeef74375882015-08-13 12:09:10 -07001509 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001510 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001511}
1512
kwiberg55b97fe2016-01-28 05:22:45 -08001513int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1514 RtpReceiver** rtp_receiver) const {
1515 *rtpRtcpModule = _rtpRtcpModule.get();
1516 *rtp_receiver = rtp_receiver_.get();
1517 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001518}
1519
deadbeef74375882015-08-13 12:09:10 -07001520void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001521 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001522
henrik.lundin96bd5022016-04-06 04:13:56 -07001523 if (!jitter_buffer_playout_timestamp_) {
1524 // This can happen if this channel has not received any RTP packets. In
1525 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001526 return;
1527 }
1528
1529 uint16_t delay_ms = 0;
1530 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001531 LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1532 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001533 return;
1534 }
1535
henrik.lundin96bd5022016-04-06 04:13:56 -07001536 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1537 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001538
1539 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001540 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001541
deadbeef74375882015-08-13 12:09:10 -07001542 {
tommi31fc21f2016-01-21 10:37:37 -08001543 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001544 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001545 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001546 }
1547 playout_delay_ms_ = delay_ms;
1548 }
1549}
1550
kwiberg55b97fe2016-01-28 05:22:45 -08001551void Channel::RegisterReceiveCodecsToRTPModule() {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001552 // TODO(kwiberg): Iterate over the factory's supported codecs instead?
1553 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001554 for (int idx = 0; idx < nSupportedCodecs; idx++) {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001555 CodecInst codec;
1556 if (audio_coding_->Codec(idx, &codec) == -1) {
1557 LOG(LS_WARNING) << "Unable to register codec #" << idx
1558 << " for RTP/RTCP receiver.";
1559 continue;
1560 }
1561 const SdpAudioFormat format = CodecInstToSdp(codec);
1562 if (!decoder_factory_->IsSupportedDecoder(format) ||
1563 rtp_receiver_->RegisterReceivePayload(codec.pltype, format) == -1) {
1564 LOG(LS_WARNING) << "Unable to register " << format
1565 << " for RTP/RTCP receiver.";
niklase@google.com470e71d2011-07-07 08:21:25 +00001566 }
kwiberg55b97fe2016-01-28 05:22:45 -08001567 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001568}
1569
kwiberg55b97fe2016-01-28 05:22:45 -08001570int Channel::SetSendRtpHeaderExtension(bool enable,
1571 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001572 unsigned char id) {
1573 int error = 0;
1574 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1575 if (enable) {
1576 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1577 }
1578 return error;
1579}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001580
ossue280cde2016-10-12 11:04:10 -07001581int Channel::GetRtpTimestampRateHz() const {
1582 const auto format = audio_coding_->ReceiveFormat();
1583 // Default to the playout frequency if we've not gotten any packets yet.
1584 // TODO(ossu): Zero clockrate can only happen if we've added an external
1585 // decoder for a format we don't support internally. Remove once that way of
1586 // adding decoders is gone!
1587 return (format && format->clockrate_hz != 0)
1588 ? format->clockrate_hz
1589 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001590}
1591
Minyue2013aec2015-05-13 14:14:42 +02001592int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001593 RtcpMode method = _rtpRtcpModule->RTCP();
1594 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001595 return 0;
1596 }
1597 std::vector<RTCPReportBlock> report_blocks;
1598 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001599
1600 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001601 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001602 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001603 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001604 Channel* channel = associate_send_channel_.channel();
1605 // Tries to get RTT from an associated channel. This is important for
1606 // receive-only channels.
1607 if (channel) {
1608 // To prevent infinite recursion and deadlock, calling GetRTT of
1609 // associate channel should always use "false" for argument:
1610 // |allow_associate_channel|.
1611 rtt = channel->GetRTT(false);
1612 }
1613 }
1614 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001615 }
1616
1617 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1618 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1619 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001620 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001621 break;
1622 }
1623 if (it == report_blocks.end()) {
1624 // We have not received packets with SSRC matching the report blocks.
1625 // To calculate RTT we try with the SSRC of the first report block.
1626 // This is very important for send-only channels where we don't know
1627 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001628 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001629 }
Minyue2013aec2015-05-13 14:14:42 +02001630
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001631 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001632 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001633 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001634 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1635 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001636 return 0;
1637 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001638 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001639}
1640
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001641} // namespace voe
1642} // namespace webrtc