blob: 542ea2d8318d5840af3615ee0a2a4424ae028600 [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
218 private:
219 rtc::ThreadChecker thread_checker_;
220 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700221 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100222};
223
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000224class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000225 public:
stefan7de8d642017-02-07 07:14:08 -0800226 explicit VoERtcpObserver(Channel* owner)
227 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000228 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000229
stefan7de8d642017-02-07 07:14:08 -0800230 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
231 rtc::CritScope lock(&crit_);
232 bandwidth_observer_ = bandwidth_observer;
233 }
234
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000235 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800236 rtc::CritScope lock(&crit_);
237 if (bandwidth_observer_) {
238 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
239 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000240 }
241
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000242 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
243 int64_t rtt,
244 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800245 {
246 rtc::CritScope lock(&crit_);
247 if (bandwidth_observer_) {
248 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
249 now_ms);
250 }
251 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000252 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
253 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
254 // report for VoiceEngine?
255 if (report_blocks.empty())
256 return;
257
258 int fraction_lost_aggregate = 0;
259 int total_number_of_packets = 0;
260
261 // If receiving multiple report blocks, calculate the weighted average based
262 // on the number of packets a report refers to.
263 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
264 block_it != report_blocks.end(); ++block_it) {
265 // Find the previous extended high sequence number for this remote SSRC,
266 // to calculate the number of RTP packets this report refers to. Ignore if
267 // we haven't seen this SSRC before.
268 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700269 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000270 int number_of_packets = 0;
271 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700272 number_of_packets =
273 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000274 }
srte3e69e5c2017-08-09 06:13:45 -0700275 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000276 total_number_of_packets += number_of_packets;
277
srte3e69e5c2017-08-09 06:13:45 -0700278 extended_max_sequence_number_[block_it->source_ssrc] =
279 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000280 }
281 int weighted_fraction_lost = 0;
282 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800283 weighted_fraction_lost =
284 (fraction_lost_aggregate + total_number_of_packets / 2) /
285 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000286 }
elad.alond12a8e12017-03-23 11:04:48 -0700287 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000288 }
289
290 private:
291 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000292 // Maps remote side ssrc to extended highest sequence number received.
293 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800294 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700295 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000296};
297
henrikaec6fbd22017-03-31 05:43:36 -0700298class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
299 public:
300 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
301 Channel* channel)
302 : audio_frame_(std::move(audio_frame)), channel_(channel) {
303 RTC_DCHECK(channel_);
304 }
305
306 private:
307 bool Run() override {
308 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
309 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
310 return true;
311 }
312
313 std::unique_ptr<AudioFrame> audio_frame_;
314 Channel* const channel_;
315};
316
kwiberg55b97fe2016-01-28 05:22:45 -0800317int32_t Channel::SendData(FrameType frameType,
318 uint8_t payloadType,
319 uint32_t timeStamp,
320 const uint8_t* payloadData,
321 size_t payloadSize,
322 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700323 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800324 if (_includeAudioLevelIndication) {
325 // Store current audio level in the RTP/RTCP module.
326 // The level will be used in combination with voice-activity state
327 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800328 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800329 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000330
kwiberg55b97fe2016-01-28 05:22:45 -0800331 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
332 // packetization.
333 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700334 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800335 (FrameType&)frameType, payloadType, timeStamp,
336 // Leaving the time when this frame was
337 // received from the capture device as
338 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700339 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
solenberg1c239d42017-09-29 06:00:28 -0700340 LOG(LS_ERROR) <<
341 "Channel::SendData() failed to send data to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800342 return -1;
343 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000344
kwiberg55b97fe2016-01-28 05:22:45 -0800345 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000346}
347
stefan1d8a5062015-10-02 03:39:33 -0700348bool Channel::SendRtp(const uint8_t* data,
349 size_t len,
350 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800351 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000352
kwiberg55b97fe2016-01-28 05:22:45 -0800353 if (_transportPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200354 LOG(LS_ERROR) << "Channel::SendPacket() failed to send RTP packet due to"
355 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800356 return false;
357 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000358
kwiberg55b97fe2016-01-28 05:22:45 -0800359 uint8_t* bufferToSendPtr = (uint8_t*)data;
360 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000361
kwiberg55b97fe2016-01-28 05:22:45 -0800362 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
solenberg1c239d42017-09-29 06:00:28 -0700363 LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800364 return false;
365 }
366 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000367}
368
kwiberg55b97fe2016-01-28 05:22:45 -0800369bool Channel::SendRtcp(const uint8_t* data, size_t len) {
kwiberg55b97fe2016-01-28 05:22:45 -0800370 rtc::CritScope cs(&_callbackCritSect);
371 if (_transportPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200372 LOG(LS_ERROR) << "Channel::SendRtcp() failed to send RTCP packet due to"
373 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800374 return false;
375 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000376
kwiberg55b97fe2016-01-28 05:22:45 -0800377 uint8_t* bufferToSendPtr = (uint8_t*)data;
378 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000379
kwiberg55b97fe2016-01-28 05:22:45 -0800380 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
381 if (n < 0) {
solenberg1c239d42017-09-29 06:00:28 -0700382 LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800383 return false;
384 }
385 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000386}
387
kwiberg55b97fe2016-01-28 05:22:45 -0800388void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -0800389 // Update ssrc so that NTP for AV sync can be updated.
390 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000391}
392
Peter Boströmac547a62015-09-17 23:03:57 +0200393void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200394 // TODO(saza): remove.
niklase@google.com470e71d2011-07-07 08:21:25 +0000395}
396
Karl Wibergc62f6c72017-10-04 12:38:53 +0200397int32_t Channel::OnInitializeDecoder(int payload_type,
398 const SdpAudioFormat& audio_format,
399 uint32_t rate) {
400 if (!audio_coding_->RegisterReceiveCodec(payload_type, audio_format)) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200401 LOG(LS_WARNING) << "Channel::OnInitializeDecoder() invalid codec (pt="
Karl Wibergc62f6c72017-10-04 12:38:53 +0200402 << payload_type << ", " << audio_format << ") received -1";
kwiberg55b97fe2016-01-28 05:22:45 -0800403 return -1;
404 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000405
kwiberg55b97fe2016-01-28 05:22:45 -0800406 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000407}
408
kwiberg55b97fe2016-01-28 05:22:45 -0800409int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
410 size_t payloadSize,
411 const WebRtcRTPHeader* rtpHeader) {
kwiberg55b97fe2016-01-28 05:22:45 -0800412 if (!channel_state_.Get().playing) {
413 // Avoid inserting into NetEQ when we are not playing. Count the
414 // packet as discarded.
niklase@google.com470e71d2011-07-07 08:21:25 +0000415 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800416 }
417
418 // Push the incoming payload (parsed and ready for decoding) into the ACM
419 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
420 0) {
solenberg1c239d42017-09-29 06:00:28 -0700421 LOG(LS_ERROR) <<
422 "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800423 return -1;
424 }
425
kwiberg55b97fe2016-01-28 05:22:45 -0800426 int64_t round_trip_time = 0;
427 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
428 NULL);
429
430 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
431 if (!nack_list.empty()) {
432 // Can't use nack_list.data() since it's not supported by all
433 // compilers.
434 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
435 }
436 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000437}
438
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000439bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000440 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000441 RTPHeader header;
442 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200443 LOG(LS_WARNING) << "IncomingPacket invalid RTP header";
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000444 return false;
445 }
446 header.payload_type_frequency =
447 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
448 if (header.payload_type_frequency < 0)
449 return false;
Niels Möller22ec9522017-10-05 08:39:15 +0200450 // TODO(nisse): Pass RtpPacketReceived with |recovered()| true.
451 return ReceivePacket(rtp_packet, rtp_packet_length, header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000452}
453
solenberg2397b9a2017-09-22 06:48:10 -0700454AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
455 int sample_rate_hz,
456 AudioFrame* audio_frame) {
457 audio_frame->sample_rate_hz_ = sample_rate_hz;
458
ivoc14d5dbe2016-07-04 07:06:55 -0700459 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800460 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
Elad Alon4a87e1c2017-10-03 16:11:34 +0200461 event_log_proxy_->Log(rtc::MakeUnique<RtcEventAudioPlayout>(ssrc));
kwiberg55b97fe2016-01-28 05:22:45 -0800462 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700463 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700464 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700465 &muted) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200466 LOG(LS_ERROR) << "Channel::GetAudioFrame() PlayoutData10Ms() failed!";
kwiberg55b97fe2016-01-28 05:22:45 -0800467 // In all likelihood, the audio in this frame is garbage. We return an
468 // error so that the audio mixer module doesn't add it to the mix. As
469 // a result, it won't be played out and the actions skipped here are
470 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700471 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800472 }
henrik.lundina89ab962016-05-18 08:52:45 -0700473
474 if (muted) {
475 // TODO(henrik.lundin): We should be able to do better than this. But we
476 // will have to go through all the cases below where the audio samples may
477 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700478 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700479 }
kwiberg55b97fe2016-01-28 05:22:45 -0800480
kwiberg55b97fe2016-01-28 05:22:45 -0800481 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700482 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800483
kwiberg55b97fe2016-01-28 05:22:45 -0800484 {
485 // Pass the audio buffers to an optional sink callback, before applying
486 // scaling/panning, as that applies to the mix operation.
487 // External recipients of the audio (e.g. via AudioTrack), will do their
488 // own mixing/dynamic processing.
489 rtc::CritScope cs(&_callbackCritSect);
490 if (audio_sink_) {
491 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700492 audio_frame->data(), audio_frame->samples_per_channel_,
493 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
494 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800495 audio_sink_->OnData(data);
496 }
497 }
498
499 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800500 {
501 rtc::CritScope cs(&volume_settings_critsect_);
502 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800503 }
504
505 // Output volume scaling
506 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800507 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700508 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800509 }
510
kwiberg55b97fe2016-01-28 05:22:45 -0800511 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700512 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700513 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700514 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700515 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800516
solenberg2397b9a2017-09-22 06:48:10 -0700517 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800518 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700519 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800520 }
521
522 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700523 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800524
525 // Compute elapsed time.
526 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700527 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
528 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800529 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700530 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800531
niklase@google.com470e71d2011-07-07 08:21:25 +0000532 {
kwiberg55b97fe2016-01-28 05:22:45 -0800533 rtc::CritScope lock(&ts_stats_lock_);
534 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700535 audio_frame->ntp_time_ms_ =
536 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800537 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700538 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800539 // Compute |capture_start_ntp_time_ms_| so that
540 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
541 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700542 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000543 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000544 }
kwiberg55b97fe2016-01-28 05:22:45 -0800545 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000546
solenberg2397b9a2017-09-22 06:48:10 -0700547 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
548 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000549}
550
solenberg2397b9a2017-09-22 06:48:10 -0700551int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800552 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700553 return std::max(audio_coding_->ReceiveFrequency(),
554 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000555}
556
henrikaec6fbd22017-03-31 05:43:36 -0700557int32_t Channel::CreateChannel(Channel*& channel,
558 int32_t channelId,
559 uint32_t instanceId,
560 const VoEBase::ChannelConfig& config) {
solenberg88499ec2016-09-07 07:34:41 -0700561 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800562 if (channel == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200563 LOG(LS_ERROR) << "unable to allocate memory for new channel";
kwiberg55b97fe2016-01-28 05:22:45 -0800564 return -1;
565 }
566 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000567}
568
pbos@webrtc.org92135212013-05-14 08:31:39 +0000569Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000570 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700571 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800572 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100573 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700574 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800575 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100576 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800577 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100578 rtp_receive_statistics_(
579 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
580 rtp_receiver_(
581 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100582 this,
583 this,
584 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700585 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100586 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100587 _timeStamp(0), // This is just an offset, RTP module will add it's own
588 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100589 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100590 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100591 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100592 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100593 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
594 capture_start_rtp_time_stamp_(-1),
595 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100596 _moduleProcessThreadPtr(NULL),
597 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100598 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700599 input_mute_(false),
600 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100601 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100602 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800603 transport_overhead_per_packet_(0),
604 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100605 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100606 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100607 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700608 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800609 feedback_observer_proxy_(new TransportFeedbackProxy()),
610 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700611 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200612 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
613 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700614 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700615 use_twcc_plr_for_ana_(
616 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
solenberg88499ec2016-09-07 07:34:41 -0700617 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700618 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800619 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200620
kwiberg55b97fe2016-01-28 05:22:45 -0800621 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000622
kwiberg55b97fe2016-01-28 05:22:45 -0800623 RtpRtcp::Configuration configuration;
624 configuration.audio = true;
625 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800626 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800627 configuration.receive_statistics = rtp_receive_statistics_.get();
628 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800629 if (pacing_enabled_) {
630 configuration.paced_sender = rtp_packet_sender_proxy_.get();
631 configuration.transport_sequence_number_allocator =
632 seq_num_allocator_proxy_.get();
633 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
634 }
ivoc14d5dbe2016-07-04 07:06:55 -0700635 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800636 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200637 configuration.retransmission_rate_limiter =
638 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000639
kwiberg55b97fe2016-01-28 05:22:45 -0800640 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100641 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000642}
643
kwiberg55b97fe2016-01-28 05:22:45 -0800644Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700645 RTC_DCHECK(!channel_state_.Get().sending);
646 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000647}
648
kwiberg55b97fe2016-01-28 05:22:45 -0800649int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700650 RTC_DCHECK(construction_thread_.CalledOnValidThread());
niklase@google.com470e71d2011-07-07 08:21:25 +0000651
kwiberg55b97fe2016-01-28 05:22:45 -0800652 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000653
kwiberg55b97fe2016-01-28 05:22:45 -0800654 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000655
solenberg1c239d42017-09-29 06:00:28 -0700656 if (_moduleProcessThreadPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200657 LOG(LS_ERROR) << "Channel::Init() must call SetEngineInformation() first";
kwiberg55b97fe2016-01-28 05:22:45 -0800658 return -1;
659 }
660
661 // --- Add modules to process thread (for periodic schedulation)
662
tommidea489f2017-03-03 03:20:24 -0800663 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800664
665 // --- ACM initialization
666
667 if (audio_coding_->InitializeReceiver() == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700668 LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800669 return -1;
670 }
671
672 // --- RTP/RTCP module initialization
673
674 // Ensure that RTCP is enabled by default for the created channel.
675 // Note that, the module will keep generating RTCP until it is explicitly
676 // disabled by the user.
677 // After StopListen (when no sockets exists), RTCP packets will no longer
678 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700679 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800680 // RTCP is enabled by default.
681 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
682 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800683 if (audio_coding_->RegisterTransportCallback(this) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700684 LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800685 return -1;
686 }
687
kwiberg1c07c702017-03-27 07:15:49 -0700688 return 0;
689}
690
tommi0a2391f2017-03-21 02:31:51 -0700691void Channel::Terminate() {
692 RTC_DCHECK(construction_thread_.CalledOnValidThread());
693 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700694 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
695
696 StopSend();
697 StopPlayout();
698
tommi0a2391f2017-03-21 02:31:51 -0700699 // The order to safely shutdown modules in a channel is:
700 // 1. De-register callbacks in modules
701 // 2. De-register modules in process thread
702 // 3. Destroy modules
703 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200704 LOG(LS_WARNING) << "Terminate() failed to de-register transport callback"
705 << " (Audio coding module)";
tommi0a2391f2017-03-21 02:31:51 -0700706 }
707
tommi0a2391f2017-03-21 02:31:51 -0700708 // De-register modules in process thread
709 if (_moduleProcessThreadPtr)
710 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
711
712 // End of modules shutdown
713}
714
solenberg1c239d42017-09-29 06:00:28 -0700715int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800716 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700717 rtc::TaskQueue* encoder_queue) {
718 RTC_DCHECK(encoder_queue);
719 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800720 _moduleProcessThreadPtr = &moduleProcessThread;
721 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700722 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800723 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000724}
725
kwibergb7f89d62016-02-17 10:04:18 -0800726void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800727 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800728 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100729}
730
ossu29b1a8d2016-06-13 07:34:51 -0700731const rtc::scoped_refptr<AudioDecoderFactory>&
732Channel::GetAudioDecoderFactory() const {
733 return decoder_factory_;
734}
735
kwiberg55b97fe2016-01-28 05:22:45 -0800736int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800737 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000738 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800739 }
740
kwiberg55b97fe2016-01-28 05:22:45 -0800741 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800742
743 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
kwiberg55b97fe2016-01-28 05:22:45 -0800746int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800747 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000748 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800749 }
750
kwiberg55b97fe2016-01-28 05:22:45 -0800751 channel_state_.SetPlaying(false);
752 _outputAudioLevel.Clear();
753
754 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000755}
756
kwiberg55b97fe2016-01-28 05:22:45 -0800757int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800758 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000759 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800760 }
761 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700762 {
763 // It is now OK to start posting tasks to the encoder task queue.
764 rtc::CritScope cs(&encoder_queue_lock_);
765 encoder_queue_is_active_ = true;
766 }
solenberg08b19df2017-02-15 00:42:31 -0800767 // Resume the previous sequence number which was reset by StopSend(). This
768 // needs to be done before |sending| is set to true on the RTP/RTCP module.
769 if (send_sequence_number_) {
770 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
771 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100772 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800773 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
solenberg1c239d42017-09-29 06:00:28 -0700774 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100775 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800776 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000777 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800778 return -1;
779 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000780
kwiberg55b97fe2016-01-28 05:22:45 -0800781 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000782}
783
henrikaec6fbd22017-03-31 05:43:36 -0700784void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800785 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700786 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800787 }
788 channel_state_.SetSending(false);
789
henrikaec6fbd22017-03-31 05:43:36 -0700790 // Post a task to the encoder thread which sets an event when the task is
791 // executed. We know that no more encoding tasks will be added to the task
792 // queue for this channel since sending is now deactivated. It means that,
793 // if we wait for the event to bet set, we know that no more pending tasks
794 // exists and it is therfore guaranteed that the task queue will never try
795 // to acccess and invalid channel object.
796 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700797
henrikaec6fbd22017-03-31 05:43:36 -0700798 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700799 {
800 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
801 // than this final "flush task" to be posted on the queue.
802 rtc::CritScope cs(&encoder_queue_lock_);
803 encoder_queue_is_active_ = false;
804 encoder_queue_->PostTask([&flush]() { flush.Set(); });
805 }
henrikaec6fbd22017-03-31 05:43:36 -0700806 flush.Wait(rtc::Event::kForever);
807
kwiberg55b97fe2016-01-28 05:22:45 -0800808 // Store the sequence number to be able to pick up the same sequence for
809 // the next StartSend(). This is needed for restarting device, otherwise
810 // it might cause libSRTP to complain about packets being replayed.
811 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
812 // CL is landed. See issue
813 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
814 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
815
816 // Reset sending SSRC and sequence number and triggers direct transmission
817 // of RTCP BYE
818 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700819 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800820 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100821 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000822}
823
ossu1ffbd6c2017-04-06 12:05:04 -0700824bool Channel::SetEncoder(int payload_type,
825 std::unique_ptr<AudioEncoder> encoder) {
826 RTC_DCHECK_GE(payload_type, 0);
827 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700828 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
829 // one for for us to keep track of sample rate and number of channels, etc.
830
831 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
832 // as well as some other things, so we collect this info and send it along.
833 CodecInst rtp_codec;
834 rtp_codec.pltype = payload_type;
835 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
836 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700837 // Seems unclear if it should be clock rate or sample rate. CodecInst
838 // supposedly carries the sample rate, but only clock rate seems sensible to
839 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700840 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
841 rtp_codec.pacsize = rtc::CheckedDivExact(
842 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
843 100);
844 rtp_codec.channels = encoder->NumChannels();
845 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700846
ossu76d29f92017-06-09 07:30:13 -0700847 // For audio encoding we need, instead, the actual sample rate of the codec.
848 // The rest of the information should be the same.
849 CodecInst send_codec = rtp_codec;
850 send_codec.plfreq = encoder->SampleRateHz();
851 cached_send_codec_.emplace(send_codec);
852
853 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700854 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700855 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200856 LOG(LS_ERROR)
857 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700858 return false;
859 }
860 }
861
862 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -0700863 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -0700864 return true;
865}
866
ossu20a4b3f2017-04-27 02:08:52 -0700867void Channel::ModifyEncoder(
868 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
869 audio_coding_->ModifyEncoder(modifier);
870}
871
kwiberg55b97fe2016-01-28 05:22:45 -0800872int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -0700873 if (cached_send_codec_) {
874 codec = *cached_send_codec_;
875 return 0;
876 } else {
ossu20a4b3f2017-04-27 02:08:52 -0700877 const CodecInst* send_codec = codec_manager_.GetCodecInst();
878 if (send_codec) {
879 codec = *send_codec;
880 return 0;
881 }
882 }
kwiberg1fd4a4a2015-11-03 11:20:50 -0800883 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +0000884}
885
kwiberg55b97fe2016-01-28 05:22:45 -0800886int32_t Channel::GetRecCodec(CodecInst& codec) {
887 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +0000888}
889
kwiberg55b97fe2016-01-28 05:22:45 -0800890int32_t Channel::SetSendCodec(const CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -0700891 if (!codec_manager_.RegisterEncoder(codec) ||
892 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200893 LOG(LS_ERROR) << "SetSendCodec() failed to register codec to ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800894 return -1;
895 }
896
897 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
898 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
899 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200900 LOG(LS_ERROR)
901 << "SetSendCodec() failed to register codec to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800902 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +0000903 }
kwiberg55b97fe2016-01-28 05:22:45 -0800904 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000905
ossu76d29f92017-06-09 07:30:13 -0700906 cached_send_codec_.reset();
907
kwiberg55b97fe2016-01-28 05:22:45 -0800908 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000909}
910
minyue78b4d562016-11-30 04:47:39 -0800911void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -0700912 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -0800913 if (*encoder) {
914 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -0800915 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -0800916 }
917 });
michaelt566d8202017-01-12 10:17:38 -0800918 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +0200919}
920
elad.alond12a8e12017-03-23 11:04:48 -0700921void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
922 if (!use_twcc_plr_for_ana_)
923 return;
minyue7e304322016-10-12 05:00:55 -0700924 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -0700925 if (*encoder) {
926 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
927 }
928 });
929}
930
elad.alondadb4dc2017-03-23 15:29:50 -0700931void Channel::OnRecoverableUplinkPacketLossRate(
932 float recoverable_packet_loss_rate) {
933 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
934 if (*encoder) {
935 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
936 recoverable_packet_loss_rate);
937 }
938 });
939}
940
elad.alond12a8e12017-03-23 11:04:48 -0700941void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
942 if (use_twcc_plr_for_ana_)
943 return;
944 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
945 if (*encoder) {
946 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
947 }
minyue7e304322016-10-12 05:00:55 -0700948 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000949}
950
kwiberg1c07c702017-03-27 07:15:49 -0700951void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
952 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
953 audio_coding_->SetReceiveCodecs(codecs);
954}
955
minyue7e304322016-10-12 05:00:55 -0700956bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
957 bool success = false;
958 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
959 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -0700960 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
961 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -0700962 }
963 });
964 return success;
965}
966
967void Channel::DisableAudioNetworkAdaptor() {
968 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
969 if (*encoder)
970 (*encoder)->DisableAudioNetworkAdaptor();
971 });
972}
973
974void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
975 int max_frame_length_ms) {
976 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
977 if (*encoder) {
978 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
979 max_frame_length_ms);
980 }
981 });
982}
983
solenberg1c239d42017-09-29 06:00:28 -0700984void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -0800985 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -0700986 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +0000987}
988
nisse657bab22017-02-21 06:28:10 -0800989void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -0800990 RTPHeader header;
991 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -0700992
993 // Store playout timestamp for the received RTP packet
994 UpdatePlayoutTimestamp(false);
995
996 header.payload_type_frequency =
997 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
998 if (header.payload_type_frequency >= 0) {
999 bool in_order = IsPacketInOrder(header);
1000 rtp_receive_statistics_->IncomingPacket(
1001 header, packet.size(), IsPacketRetransmitted(header, in_order));
1002 rtp_payload_registry_->SetIncomingPayloadType(header);
1003
Niels Möller22ec9522017-10-05 08:39:15 +02001004 ReceivePacket(packet.data(), packet.size(), header);
solenberg946d8862017-09-21 04:02:53 -07001005 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001006}
1007
1008bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001009 size_t packet_length,
Niels Möller22ec9522017-10-05 08:39:15 +02001010 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001011 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001012 assert(packet_length >= header.headerLength);
1013 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001014 const auto pl =
1015 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1016 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001017 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001018 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001019 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Niels Möller22ec9522017-10-05 08:39:15 +02001020 pl->typeSpecific);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001021}
1022
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001023bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1024 StreamStatistician* statistician =
1025 rtp_receive_statistics_->GetStatistician(header.ssrc);
1026 if (!statistician)
1027 return false;
1028 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001029}
1030
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001031bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1032 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001033 StreamStatistician* statistician =
1034 rtp_receive_statistics_->GetStatistician(header.ssrc);
1035 if (!statistician)
1036 return false;
1037 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001038 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001039 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001040 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001041}
1042
mflodman3d7db262016-04-29 00:57:13 -07001043int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001044 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001045 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001046
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001047 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001048 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001049
Minyue2013aec2015-05-13 14:14:42 +02001050 int64_t rtt = GetRTT(true);
1051 if (rtt == 0) {
1052 // Waiting for valid RTT.
1053 return 0;
1054 }
Erik Språng737336d2016-07-29 12:59:36 +02001055
1056 int64_t nack_window_ms = rtt;
1057 if (nack_window_ms < kMinRetransmissionWindowMs) {
1058 nack_window_ms = kMinRetransmissionWindowMs;
1059 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1060 nack_window_ms = kMaxRetransmissionWindowMs;
1061 }
1062 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1063
minyue7e304322016-10-12 05:00:55 -07001064 // Invoke audio encoders OnReceivedRtt().
1065 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1066 if (*encoder)
1067 (*encoder)->OnReceivedRtt(rtt);
1068 });
1069
Minyue2013aec2015-05-13 14:14:42 +02001070 uint32_t ntp_secs = 0;
1071 uint32_t ntp_frac = 0;
1072 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001073 if (0 !=
1074 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1075 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001076 // Waiting for RTCP.
1077 return 0;
1078 }
1079
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001080 {
tommi31fc21f2016-01-21 10:37:37 -08001081 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001082 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001083 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001084 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001085}
1086
solenberg8d73f8c2017-03-08 01:52:20 -08001087int Channel::GetSpeechOutputLevel() const {
1088 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001089}
1090
solenberg8d73f8c2017-03-08 01:52:20 -08001091int Channel::GetSpeechOutputLevelFullRange() const {
1092 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001093}
1094
zsteine76bd3a2017-07-14 12:17:49 -07001095double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001096 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001097}
1098
1099double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001100 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001101}
1102
solenberg8d73f8c2017-03-08 01:52:20 -08001103void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001104 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001105 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001106}
1107
solenberg1c2af8e2016-03-24 10:36:00 -07001108bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001109 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001110 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001111}
1112
solenberg8d73f8c2017-03-08 01:52:20 -08001113void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001114 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001115 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001116}
1117
solenberg8842c3e2016-03-11 03:06:41 -08001118int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001119 RTC_DCHECK_LE(0, event);
1120 RTC_DCHECK_GE(255, event);
1121 RTC_DCHECK_LE(0, duration_ms);
1122 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001123 if (!Sending()) {
1124 return -1;
1125 }
solenberg8842c3e2016-03-11 03:06:41 -08001126 if (_rtpRtcpModule->SendTelephoneEventOutband(
1127 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001128 LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001129 return -1;
1130 }
1131 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001132}
1133
solenbergffbbcac2016-11-17 05:25:37 -08001134int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1135 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001136 RTC_DCHECK_LE(0, payload_type);
1137 RTC_DCHECK_GE(127, payload_type);
1138 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001139 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001140 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001141 memcpy(codec.plname, "telephone-event", 16);
1142 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1143 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1144 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001145 LOG(LS_ERROR) << "SetSendTelephoneEventPayloadType() failed to register "
1146 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001147 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001148 }
kwiberg55b97fe2016-01-28 05:22:45 -08001149 }
kwiberg55b97fe2016-01-28 05:22:45 -08001150 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001151}
1152
kwiberg55b97fe2016-01-28 05:22:45 -08001153int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001154 if (channel_state_.Get().sending) {
solenberg1c239d42017-09-29 06:00:28 -07001155 LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001156 return -1;
1157 }
1158 _rtpRtcpModule->SetSSRC(ssrc);
1159 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001160}
1161
kwiberg55b97fe2016-01-28 05:22:45 -08001162int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1163 ssrc = rtp_receiver_->SSRC();
1164 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001165}
1166
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001167int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001168 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001169 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001170}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001171
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001172int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1173 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001174 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1175 if (enable &&
1176 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1177 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001178 return -1;
1179 }
1180 return 0;
1181}
1182
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001183void Channel::EnableSendTransportSequenceNumber(int id) {
1184 int ret =
1185 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1186 RTC_DCHECK_EQ(0, ret);
1187}
1188
stefan3313ec92016-01-21 06:32:43 -08001189void Channel::EnableReceiveTransportSequenceNumber(int id) {
1190 rtp_header_parser_->DeregisterRtpHeaderExtension(
1191 kRtpExtensionTransportSequenceNumber);
1192 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1193 kRtpExtensionTransportSequenceNumber, id);
1194 RTC_DCHECK(ret);
1195}
1196
stefanbba9dec2016-02-01 04:39:55 -08001197void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001198 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001199 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001200 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1201 TransportFeedbackObserver* transport_feedback_observer =
1202 transport->transport_feedback_observer();
1203 PacketRouter* packet_router = transport->packet_router();
1204
stefanbba9dec2016-02-01 04:39:55 -08001205 RTC_DCHECK(rtp_packet_sender);
1206 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001207 RTC_DCHECK(packet_router);
1208 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001209 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001210 feedback_observer_proxy_->SetTransportFeedbackObserver(
1211 transport_feedback_observer);
1212 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1213 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1214 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001215 constexpr bool remb_candidate = false;
1216 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001217 packet_router_ = packet_router;
1218}
1219
stefanbba9dec2016-02-01 04:39:55 -08001220void Channel::RegisterReceiverCongestionControlObjects(
1221 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001222 RTC_DCHECK(packet_router);
1223 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001224 constexpr bool remb_candidate = false;
1225 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001226 packet_router_ = packet_router;
1227}
1228
nissefdbfdc92017-03-31 05:44:52 -07001229void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001230 RTC_DCHECK(packet_router_);
1231 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001232 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001233 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1234 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001235 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001236 packet_router_ = nullptr;
1237 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1238}
1239
nissefdbfdc92017-03-31 05:44:52 -07001240void Channel::ResetReceiverCongestionControlObjects() {
1241 RTC_DCHECK(packet_router_);
1242 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1243 packet_router_ = nullptr;
1244}
1245
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001246void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001247 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001248}
1249
kwiberg55b97fe2016-01-28 05:22:45 -08001250int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001251 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001252 LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001253 return -1;
1254 }
1255 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001256}
1257
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001258int Channel::GetRemoteRTCPReportBlocks(
1259 std::vector<ReportBlock>* report_blocks) {
1260 if (report_blocks == NULL) {
solenberg1c239d42017-09-29 06:00:28 -07001261 LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001262 return -1;
1263 }
1264
1265 // Get the report blocks from the latest received RTCP Sender or Receiver
1266 // Report. Each element in the vector contains the sender's SSRC and a
1267 // report block according to RFC 3550.
1268 std::vector<RTCPReportBlock> rtcp_report_blocks;
1269 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001270 return -1;
1271 }
1272
1273 if (rtcp_report_blocks.empty())
1274 return 0;
1275
1276 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1277 for (; it != rtcp_report_blocks.end(); ++it) {
1278 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001279 report_block.sender_SSRC = it->sender_ssrc;
1280 report_block.source_SSRC = it->source_ssrc;
1281 report_block.fraction_lost = it->fraction_lost;
1282 report_block.cumulative_num_packets_lost = it->packets_lost;
1283 report_block.extended_highest_sequence_number =
1284 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001285 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001286 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1287 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001288 report_blocks->push_back(report_block);
1289 }
1290 return 0;
1291}
1292
kwiberg55b97fe2016-01-28 05:22:45 -08001293int Channel::GetRTPStatistics(CallStatistics& stats) {
1294 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001295
kwiberg55b97fe2016-01-28 05:22:45 -08001296 // The jitter statistics is updated for each received RTP packet and is
1297 // based on received packets.
1298 RtcpStatistics statistics;
1299 StreamStatistician* statistician =
1300 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001301 if (statistician) {
1302 statistician->GetStatistics(&statistics,
1303 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001304 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001305
kwiberg55b97fe2016-01-28 05:22:45 -08001306 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001307 stats.cumulativeLost = statistics.packets_lost;
1308 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001309 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001310
kwiberg55b97fe2016-01-28 05:22:45 -08001311 // --- RTT
1312 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001313
kwiberg55b97fe2016-01-28 05:22:45 -08001314 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001315
kwiberg55b97fe2016-01-28 05:22:45 -08001316 size_t bytesSent(0);
1317 uint32_t packetsSent(0);
1318 size_t bytesReceived(0);
1319 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001320
kwiberg55b97fe2016-01-28 05:22:45 -08001321 if (statistician) {
1322 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1323 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001324
kwiberg55b97fe2016-01-28 05:22:45 -08001325 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001326 LOG(LS_WARNING) << "GetRTPStatistics() failed to retrieve RTP datacounters"
1327 << " => output will not be complete";
kwiberg55b97fe2016-01-28 05:22:45 -08001328 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001329
kwiberg55b97fe2016-01-28 05:22:45 -08001330 stats.bytesSent = bytesSent;
1331 stats.packetsSent = packetsSent;
1332 stats.bytesReceived = bytesReceived;
1333 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001334
kwiberg55b97fe2016-01-28 05:22:45 -08001335 // --- Timestamps
1336 {
1337 rtc::CritScope lock(&ts_stats_lock_);
1338 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1339 }
1340 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001341}
1342
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001343void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1344 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001345 // If pacing is enabled we always store packets.
1346 if (!pacing_enabled_)
1347 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001348 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001349 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001350 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001351 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001352 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001353}
1354
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001355// Called when we are missing one or more packets.
1356int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001357 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1358}
1359
henrikaec6fbd22017-03-31 05:43:36 -07001360void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001361 // Avoid posting any new tasks 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());
1367 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1368 // either into pool of frames or into the task itself.
1369 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001370 // Profile time between when the audio frame is added to the task queue and
1371 // when the task is actually executed.
1372 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001373 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1374 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001375}
1376
henrikaec6fbd22017-03-31 05:43:36 -07001377void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1378 int sample_rate,
1379 size_t number_of_frames,
1380 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001381 // Avoid posting as new task if sending was already stopped in StopSend().
1382 rtc::CritScope cs(&encoder_queue_lock_);
1383 if (!encoder_queue_is_active_) {
1384 return;
1385 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001386 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001387 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001388 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
ossu950c1c92017-07-11 08:19:31 -07001389 // TODO(ossu): Investigate how this could happen. b/62909493
1390 if (result == 0) {
1391 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1392 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1393 } else {
1394 audio_frame->sample_rate_hz_ = sample_rate;
1395 audio_frame->num_channels_ = number_of_channels;
1396 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1397 RTC_NOTREACHED();
1398 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001399 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001400 sample_rate, &input_resampler_, audio_frame.get());
1401 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1402 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001403}
1404
henrikaec6fbd22017-03-31 05:43:36 -07001405void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1406 RTC_DCHECK_RUN_ON(encoder_queue_);
1407 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1408 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001409
henrika45802172017-09-28 09:39:34 +02001410 // Measure time between when the audio frame is added to the task queue and
1411 // when the task is actually executed. Goal is to keep track of unwanted
1412 // extra latency added by the task queue.
1413 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1414 audio_input->ElapsedProfileTimeMs());
1415
henrikaec6fbd22017-03-31 05:43:36 -07001416 bool is_muted = InputMute();
1417 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001418
kwiberg55b97fe2016-01-28 05:22:45 -08001419 if (_includeAudioLevelIndication) {
1420 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001421 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001422 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001423 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001424 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001425 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001426 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001427 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001428 }
kwiberg55b97fe2016-01-28 05:22:45 -08001429 }
solenberg1c2af8e2016-03-24 10:36:00 -07001430 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001431
henrikaec6fbd22017-03-31 05:43:36 -07001432 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001433
kwiberg55b97fe2016-01-28 05:22:45 -08001434 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001435 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001436 // This call will trigger AudioPacketizationCallback::SendData if encoding
1437 // is done and payload is ready for packetization and transmission.
1438 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001439 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1440 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1441 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001442 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001443
henrikaec6fbd22017-03-31 05:43:36 -07001444 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001445}
1446
solenberg7602aab2016-11-14 11:30:07 -08001447void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1448 RTC_DCHECK(!channel.channel() ||
1449 channel.channel()->ChannelId() != _channelId);
1450 rtc::CritScope lock(&assoc_send_channel_lock_);
1451 associate_send_channel_ = channel;
1452}
1453
Minyue2013aec2015-05-13 14:14:42 +02001454void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001455 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001456 Channel* channel = associate_send_channel_.channel();
1457 if (channel && channel->ChannelId() == channel_id) {
1458 // If this channel is associated with a send channel of the specified
1459 // Channel ID, disassociate with it.
1460 ChannelOwner ref(NULL);
1461 associate_send_channel_ = ref;
1462 }
1463}
1464
ivoc14d5dbe2016-07-04 07:06:55 -07001465void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1466 event_log_proxy_->SetEventLog(event_log);
1467}
1468
michaelt9332b7d2016-11-30 07:51:13 -08001469void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1470 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1471}
1472
nisse284542b2017-01-10 08:58:32 -08001473void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001474 size_t overhead_per_packet =
1475 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001476 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1477 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001478 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001479 }
1480 });
1481}
1482
1483void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001484 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001485 transport_overhead_per_packet_ = transport_overhead_per_packet;
1486 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001487}
1488
hbos3fd31fe2017-02-28 05:43:16 -08001489// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001490void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001491 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001492 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1493 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001494}
1495
kwiberg55b97fe2016-01-28 05:22:45 -08001496int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1497 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001498}
1499
wu@webrtc.org24301a62013-12-13 19:17:43 +00001500void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1501 audio_coding_->GetDecodingCallStatistics(stats);
1502}
1503
ivoce1198e02017-09-08 08:13:19 -07001504ANAStats Channel::GetANAStatistics() const {
1505 return audio_coding_->GetANAStats();
1506}
1507
solenberg358057b2015-11-27 10:46:42 -08001508uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001509 rtc::CritScope lock(&video_sync_lock_);
1510 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001511}
1512
kwiberg55b97fe2016-01-28 05:22:45 -08001513int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001514 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1515 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
solenberg1c239d42017-09-29 06:00:28 -07001516 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001517 return -1;
1518 }
1519 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001520 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001521 return -1;
1522 }
1523 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001524}
1525
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001526int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001527 uint32_t playout_timestamp_rtp = 0;
1528 {
tommi31fc21f2016-01-21 10:37:37 -08001529 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001530 playout_timestamp_rtp = playout_timestamp_rtp_;
1531 }
kwiberg55b97fe2016-01-28 05:22:45 -08001532 if (playout_timestamp_rtp == 0) {
solenberg1c239d42017-09-29 06:00:28 -07001533 LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001534 return -1;
1535 }
deadbeef74375882015-08-13 12:09:10 -07001536 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001537 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001538}
1539
kwiberg55b97fe2016-01-28 05:22:45 -08001540int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1541 RtpReceiver** rtp_receiver) const {
1542 *rtpRtcpModule = _rtpRtcpModule.get();
1543 *rtp_receiver = rtp_receiver_.get();
1544 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001545}
1546
deadbeef74375882015-08-13 12:09:10 -07001547void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001548 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001549
henrik.lundin96bd5022016-04-06 04:13:56 -07001550 if (!jitter_buffer_playout_timestamp_) {
1551 // This can happen if this channel has not received any RTP packets. In
1552 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001553 return;
1554 }
1555
1556 uint16_t delay_ms = 0;
1557 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001558 LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1559 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001560 return;
1561 }
1562
henrik.lundin96bd5022016-04-06 04:13:56 -07001563 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1564 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001565
1566 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001567 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001568
deadbeef74375882015-08-13 12:09:10 -07001569 {
tommi31fc21f2016-01-21 10:37:37 -08001570 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001571 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001572 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001573 }
1574 playout_delay_ms_ = delay_ms;
1575 }
1576}
1577
kwiberg55b97fe2016-01-28 05:22:45 -08001578void Channel::RegisterReceiveCodecsToRTPModule() {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001579 // TODO(kwiberg): Iterate over the factory's supported codecs instead?
1580 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001581 for (int idx = 0; idx < nSupportedCodecs; idx++) {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001582 CodecInst codec;
1583 if (audio_coding_->Codec(idx, &codec) == -1) {
1584 LOG(LS_WARNING) << "Unable to register codec #" << idx
1585 << " for RTP/RTCP receiver.";
1586 continue;
1587 }
1588 const SdpAudioFormat format = CodecInstToSdp(codec);
1589 if (!decoder_factory_->IsSupportedDecoder(format) ||
1590 rtp_receiver_->RegisterReceivePayload(codec.pltype, format) == -1) {
1591 LOG(LS_WARNING) << "Unable to register " << format
1592 << " for RTP/RTCP receiver.";
niklase@google.com470e71d2011-07-07 08:21:25 +00001593 }
kwiberg55b97fe2016-01-28 05:22:45 -08001594 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001595}
1596
kwiberg55b97fe2016-01-28 05:22:45 -08001597int Channel::SetSendRtpHeaderExtension(bool enable,
1598 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001599 unsigned char id) {
1600 int error = 0;
1601 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1602 if (enable) {
1603 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1604 }
1605 return error;
1606}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001607
ossue280cde2016-10-12 11:04:10 -07001608int Channel::GetRtpTimestampRateHz() const {
1609 const auto format = audio_coding_->ReceiveFormat();
1610 // Default to the playout frequency if we've not gotten any packets yet.
1611 // TODO(ossu): Zero clockrate can only happen if we've added an external
1612 // decoder for a format we don't support internally. Remove once that way of
1613 // adding decoders is gone!
1614 return (format && format->clockrate_hz != 0)
1615 ? format->clockrate_hz
1616 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001617}
1618
Minyue2013aec2015-05-13 14:14:42 +02001619int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001620 RtcpMode method = _rtpRtcpModule->RTCP();
1621 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001622 return 0;
1623 }
1624 std::vector<RTCPReportBlock> report_blocks;
1625 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001626
1627 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001628 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001629 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001630 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001631 Channel* channel = associate_send_channel_.channel();
1632 // Tries to get RTT from an associated channel. This is important for
1633 // receive-only channels.
1634 if (channel) {
1635 // To prevent infinite recursion and deadlock, calling GetRTT of
1636 // associate channel should always use "false" for argument:
1637 // |allow_associate_channel|.
1638 rtt = channel->GetRTT(false);
1639 }
1640 }
1641 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001642 }
1643
1644 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1645 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1646 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001647 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001648 break;
1649 }
1650 if (it == report_blocks.end()) {
1651 // We have not received packets with SSRC matching the report blocks.
1652 // To calculate RTT we try with the SSRC of the first report block.
1653 // This is very important for send-only channels where we don't know
1654 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001655 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001656 }
Minyue2013aec2015-05-13 14:14:42 +02001657
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001658 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001659 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001660 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001661 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1662 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001663 return 0;
1664 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001665 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001666}
1667
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001668} // namespace voe
1669} // namespace webrtc