blob: de2d4a7626f5d326ecd474c36c372c966ebdc220 [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"
niklase@google.com470e71d2011-07-07 08:21:25 +000049
andrew@webrtc.org50419b02012-11-14 19:07:54 +000050namespace webrtc {
51namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000052
kwibergc8d071e2016-04-06 12:22:38 -070053namespace {
54
zsteine76bd3a2017-07-14 12:17:49 -070055constexpr double kAudioSampleDurationSeconds = 0.01;
Erik Språng737336d2016-07-29 12:59:36 +020056constexpr int64_t kMaxRetransmissionWindowMs = 1000;
57constexpr int64_t kMinRetransmissionWindowMs = 30;
58
Fredrik Solenberg55900fd2017-11-23 20:22:55 +010059// Video Sync.
60constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
61constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
62
kwibergc8d071e2016-04-06 12:22:38 -070063} // namespace
64
solenberg8842c3e2016-03-11 03:06:41 -080065const int kTelephoneEventAttenuationdB = 10;
66
ivoc14d5dbe2016-07-04 07:06:55 -070067class RtcEventLogProxy final : public webrtc::RtcEventLog {
68 public:
69 RtcEventLogProxy() : event_log_(nullptr) {}
70
Bjorn Tereliusde939432017-11-20 17:38:14 +010071 bool StartLogging(std::unique_ptr<RtcEventLogOutput> output,
72 int64_t output_period_ms) override {
Elad Alon83ccca12017-10-04 13:18:26 +020073 RTC_NOTREACHED();
74 return false;
75 }
76
ivoc14d5dbe2016-07-04 07:06:55 -070077 void StopLogging() override { RTC_NOTREACHED(); }
78
Elad Alon4a87e1c2017-10-03 16:11:34 +020079 void Log(std::unique_ptr<RtcEvent> event) override {
80 rtc::CritScope lock(&crit_);
81 if (event_log_) {
82 event_log_->Log(std::move(event));
83 }
84 }
85
ivoc14d5dbe2016-07-04 07:06:55 -070086 void SetEventLog(RtcEventLog* event_log) {
87 rtc::CritScope lock(&crit_);
88 event_log_ = event_log;
89 }
90
91 private:
92 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -070093 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -070094 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
95};
96
michaelt9332b7d2016-11-30 07:51:13 -080097class RtcpRttStatsProxy final : public RtcpRttStats {
98 public:
99 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
100
101 void OnRttUpdate(int64_t rtt) override {
102 rtc::CritScope lock(&crit_);
103 if (rtcp_rtt_stats_)
104 rtcp_rtt_stats_->OnRttUpdate(rtt);
105 }
106
107 int64_t LastProcessedRtt() const override {
108 rtc::CritScope lock(&crit_);
109 if (!rtcp_rtt_stats_)
110 return 0;
111 return rtcp_rtt_stats_->LastProcessedRtt();
112 }
113
114 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
115 rtc::CritScope lock(&crit_);
116 rtcp_rtt_stats_ = rtcp_rtt_stats;
117 }
118
119 private:
120 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700121 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800122 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
123};
124
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100125class TransportFeedbackProxy : public TransportFeedbackObserver {
126 public:
127 TransportFeedbackProxy() : feedback_observer_(nullptr) {
128 pacer_thread_.DetachFromThread();
129 network_thread_.DetachFromThread();
130 }
131
132 void SetTransportFeedbackObserver(
133 TransportFeedbackObserver* feedback_observer) {
134 RTC_DCHECK(thread_checker_.CalledOnValidThread());
135 rtc::CritScope lock(&crit_);
136 feedback_observer_ = feedback_observer;
137 }
138
139 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700140 void AddPacket(uint32_t ssrc,
141 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100142 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800143 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100144 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
145 rtc::CritScope lock(&crit_);
146 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700147 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100148 }
philipel8aadd502017-02-23 02:56:13 -0800149
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100150 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
151 RTC_DCHECK(network_thread_.CalledOnValidThread());
152 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700153 if (feedback_observer_)
154 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200155 }
elad.alonf9490002017-03-06 05:32:21 -0800156 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200157 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800158 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100159 }
160
161 private:
162 rtc::CriticalSection crit_;
163 rtc::ThreadChecker thread_checker_;
164 rtc::ThreadChecker pacer_thread_;
165 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700166 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100167};
168
169class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
170 public:
171 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
172 pacer_thread_.DetachFromThread();
173 }
174
175 void SetSequenceNumberAllocator(
176 TransportSequenceNumberAllocator* seq_num_allocator) {
177 RTC_DCHECK(thread_checker_.CalledOnValidThread());
178 rtc::CritScope lock(&crit_);
179 seq_num_allocator_ = seq_num_allocator;
180 }
181
182 // Implements TransportSequenceNumberAllocator.
183 uint16_t AllocateSequenceNumber() override {
184 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
185 rtc::CritScope lock(&crit_);
186 if (!seq_num_allocator_)
187 return 0;
188 return seq_num_allocator_->AllocateSequenceNumber();
189 }
190
191 private:
192 rtc::CriticalSection crit_;
193 rtc::ThreadChecker thread_checker_;
194 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700195 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100196};
197
198class RtpPacketSenderProxy : public RtpPacketSender {
199 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800200 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100201
202 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
203 RTC_DCHECK(thread_checker_.CalledOnValidThread());
204 rtc::CritScope lock(&crit_);
205 rtp_packet_sender_ = rtp_packet_sender;
206 }
207
208 // Implements RtpPacketSender.
209 void InsertPacket(Priority priority,
210 uint32_t ssrc,
211 uint16_t sequence_number,
212 int64_t capture_time_ms,
213 size_t bytes,
214 bool retransmission) override {
215 rtc::CritScope lock(&crit_);
216 if (rtp_packet_sender_) {
217 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
218 capture_time_ms, bytes, retransmission);
219 }
220 }
221
Alex Narest78609d52017-10-20 10:37:47 +0200222 void SetAccountForAudioPackets(bool account_for_audio) override {
223 RTC_NOTREACHED();
224 }
225
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100226 private:
227 rtc::ThreadChecker thread_checker_;
228 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700229 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100230};
231
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000232class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000233 public:
stefan7de8d642017-02-07 07:14:08 -0800234 explicit VoERtcpObserver(Channel* owner)
235 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000236 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000237
stefan7de8d642017-02-07 07:14:08 -0800238 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
239 rtc::CritScope lock(&crit_);
240 bandwidth_observer_ = bandwidth_observer;
241 }
242
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000243 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800244 rtc::CritScope lock(&crit_);
245 if (bandwidth_observer_) {
246 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
247 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000248 }
249
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000250 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
251 int64_t rtt,
252 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800253 {
254 rtc::CritScope lock(&crit_);
255 if (bandwidth_observer_) {
256 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
257 now_ms);
258 }
259 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000260 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
261 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
262 // report for VoiceEngine?
263 if (report_blocks.empty())
264 return;
265
266 int fraction_lost_aggregate = 0;
267 int total_number_of_packets = 0;
268
269 // If receiving multiple report blocks, calculate the weighted average based
270 // on the number of packets a report refers to.
271 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
272 block_it != report_blocks.end(); ++block_it) {
273 // Find the previous extended high sequence number for this remote SSRC,
274 // to calculate the number of RTP packets this report refers to. Ignore if
275 // we haven't seen this SSRC before.
276 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700277 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000278 int number_of_packets = 0;
279 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700280 number_of_packets =
281 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000282 }
srte3e69e5c2017-08-09 06:13:45 -0700283 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000284 total_number_of_packets += number_of_packets;
285
srte3e69e5c2017-08-09 06:13:45 -0700286 extended_max_sequence_number_[block_it->source_ssrc] =
287 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000288 }
289 int weighted_fraction_lost = 0;
290 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800291 weighted_fraction_lost =
292 (fraction_lost_aggregate + total_number_of_packets / 2) /
293 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000294 }
elad.alond12a8e12017-03-23 11:04:48 -0700295 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000296 }
297
298 private:
299 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000300 // Maps remote side ssrc to extended highest sequence number received.
301 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800302 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700303 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000304};
305
henrikaec6fbd22017-03-31 05:43:36 -0700306class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
307 public:
308 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
309 Channel* channel)
310 : audio_frame_(std::move(audio_frame)), channel_(channel) {
311 RTC_DCHECK(channel_);
312 }
313
314 private:
315 bool Run() override {
316 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
317 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
318 return true;
319 }
320
321 std::unique_ptr<AudioFrame> audio_frame_;
322 Channel* const channel_;
323};
324
kwiberg55b97fe2016-01-28 05:22:45 -0800325int32_t Channel::SendData(FrameType frameType,
326 uint8_t payloadType,
327 uint32_t timeStamp,
328 const uint8_t* payloadData,
329 size_t payloadSize,
330 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700331 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800332 if (_includeAudioLevelIndication) {
333 // Store current audio level in the RTP/RTCP module.
334 // The level will be used in combination with voice-activity state
335 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800336 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800337 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000338
kwiberg55b97fe2016-01-28 05:22:45 -0800339 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
340 // packetization.
341 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700342 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800343 (FrameType&)frameType, payloadType, timeStamp,
344 // Leaving the time when this frame was
345 // received from the capture device as
346 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700347 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100348 RTC_LOG(LS_ERROR)
349 << "Channel::SendData() failed to send data to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800350 return -1;
351 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000352
kwiberg55b97fe2016-01-28 05:22:45 -0800353 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000354}
355
stefan1d8a5062015-10-02 03:39:33 -0700356bool Channel::SendRtp(const uint8_t* data,
357 size_t len,
358 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800359 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000360
kwiberg55b97fe2016-01-28 05:22:45 -0800361 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100362 RTC_LOG(LS_ERROR)
363 << "Channel::SendPacket() failed to send RTP packet due to"
364 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800365 return false;
366 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000367
kwiberg55b97fe2016-01-28 05:22:45 -0800368 uint8_t* bufferToSendPtr = (uint8_t*)data;
369 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000370
kwiberg55b97fe2016-01-28 05:22:45 -0800371 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100372 RTC_LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800373 return false;
374 }
375 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000376}
377
kwiberg55b97fe2016-01-28 05:22:45 -0800378bool Channel::SendRtcp(const uint8_t* data, size_t len) {
kwiberg55b97fe2016-01-28 05:22:45 -0800379 rtc::CritScope cs(&_callbackCritSect);
380 if (_transportPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100381 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() failed to send RTCP packet due to"
382 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800383 return false;
384 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000385
kwiberg55b97fe2016-01-28 05:22:45 -0800386 uint8_t* bufferToSendPtr = (uint8_t*)data;
387 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000388
kwiberg55b97fe2016-01-28 05:22:45 -0800389 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
390 if (n < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100391 RTC_LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800392 return false;
393 }
394 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000395}
396
kwiberg55b97fe2016-01-28 05:22:45 -0800397void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -0800398 // Update ssrc so that NTP for AV sync can be updated.
399 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000400}
401
Peter Boströmac547a62015-09-17 23:03:57 +0200402void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200403 // TODO(saza): remove.
niklase@google.com470e71d2011-07-07 08:21:25 +0000404}
405
Karl Wibergc62f6c72017-10-04 12:38:53 +0200406int32_t Channel::OnInitializeDecoder(int payload_type,
407 const SdpAudioFormat& audio_format,
408 uint32_t rate) {
409 if (!audio_coding_->RegisterReceiveCodec(payload_type, audio_format)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100410 RTC_LOG(LS_WARNING) << "Channel::OnInitializeDecoder() invalid codec (pt="
411 << payload_type << ", " << audio_format
412 << ") received -1";
kwiberg55b97fe2016-01-28 05:22:45 -0800413 return -1;
414 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000415
kwiberg55b97fe2016-01-28 05:22:45 -0800416 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000417}
418
kwiberg55b97fe2016-01-28 05:22:45 -0800419int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
420 size_t payloadSize,
421 const WebRtcRTPHeader* rtpHeader) {
kwiberg55b97fe2016-01-28 05:22:45 -0800422 if (!channel_state_.Get().playing) {
423 // Avoid inserting into NetEQ when we are not playing. Count the
424 // packet as discarded.
niklase@google.com470e71d2011-07-07 08:21:25 +0000425 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800426 }
427
428 // Push the incoming payload (parsed and ready for decoding) into the ACM
429 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
430 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100431 RTC_LOG(LS_ERROR)
432 << "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800433 return -1;
434 }
435
kwiberg55b97fe2016-01-28 05:22:45 -0800436 int64_t round_trip_time = 0;
437 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
438 NULL);
439
440 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
441 if (!nack_list.empty()) {
442 // Can't use nack_list.data() since it's not supported by all
443 // compilers.
444 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
445 }
446 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000447}
448
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000449bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000450 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000451 RTPHeader header;
452 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100453 RTC_LOG(LS_WARNING) << "IncomingPacket invalid RTP header";
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000454 return false;
455 }
456 header.payload_type_frequency =
457 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
458 if (header.payload_type_frequency < 0)
459 return false;
Niels Möller22ec9522017-10-05 08:39:15 +0200460 // TODO(nisse): Pass RtpPacketReceived with |recovered()| true.
461 return ReceivePacket(rtp_packet, rtp_packet_length, header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000462}
463
solenberg2397b9a2017-09-22 06:48:10 -0700464AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
465 int sample_rate_hz,
466 AudioFrame* audio_frame) {
467 audio_frame->sample_rate_hz_ = sample_rate_hz;
468
ivoc14d5dbe2016-07-04 07:06:55 -0700469 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800470 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
Elad Alon4a87e1c2017-10-03 16:11:34 +0200471 event_log_proxy_->Log(rtc::MakeUnique<RtcEventAudioPlayout>(ssrc));
kwiberg55b97fe2016-01-28 05:22:45 -0800472 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700473 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700474 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700475 &muted) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_ERROR) << "Channel::GetAudioFrame() PlayoutData10Ms() failed!";
kwiberg55b97fe2016-01-28 05:22:45 -0800477 // In all likelihood, the audio in this frame is garbage. We return an
478 // error so that the audio mixer module doesn't add it to the mix. As
479 // a result, it won't be played out and the actions skipped here are
480 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700481 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800482 }
henrik.lundina89ab962016-05-18 08:52:45 -0700483
484 if (muted) {
485 // TODO(henrik.lundin): We should be able to do better than this. But we
486 // will have to go through all the cases below where the audio samples may
487 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700488 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700489 }
kwiberg55b97fe2016-01-28 05:22:45 -0800490
kwiberg55b97fe2016-01-28 05:22:45 -0800491 {
492 // Pass the audio buffers to an optional sink callback, before applying
493 // scaling/panning, as that applies to the mix operation.
494 // External recipients of the audio (e.g. via AudioTrack), will do their
495 // own mixing/dynamic processing.
496 rtc::CritScope cs(&_callbackCritSect);
497 if (audio_sink_) {
498 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700499 audio_frame->data(), audio_frame->samples_per_channel_,
500 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
501 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800502 audio_sink_->OnData(data);
503 }
504 }
505
506 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800507 {
508 rtc::CritScope cs(&volume_settings_critsect_);
509 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800510 }
511
512 // Output volume scaling
513 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800514 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700515 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800516 }
517
kwiberg55b97fe2016-01-28 05:22:45 -0800518 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700519 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700520 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700521 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700522 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800523
solenberg2397b9a2017-09-22 06:48:10 -0700524 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800525 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700526 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800527 }
528
529 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700530 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800531
532 // Compute elapsed time.
533 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700534 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
535 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800536 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700537 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800538
niklase@google.com470e71d2011-07-07 08:21:25 +0000539 {
kwiberg55b97fe2016-01-28 05:22:45 -0800540 rtc::CritScope lock(&ts_stats_lock_);
541 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700542 audio_frame->ntp_time_ms_ =
543 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800544 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700545 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800546 // Compute |capture_start_ntp_time_ms_| so that
547 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
548 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700549 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000550 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000551 }
kwiberg55b97fe2016-01-28 05:22:45 -0800552 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000553
Henrik Lundin9bde6b72017-11-02 15:01:56 +0100554 {
Henrik Lundinabbff892017-11-29 09:14:04 +0100555 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
556 audio_coding_->TargetDelayMs());
Henrik Lundin9bde6b72017-11-02 15:01:56 +0100557 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
558 rtc::CritScope lock(&video_sync_lock_);
559 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
560 jitter_buffer_delay + playout_delay_ms_);
561 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
562 jitter_buffer_delay);
563 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
564 playout_delay_ms_);
565 }
566
solenberg2397b9a2017-09-22 06:48:10 -0700567 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
568 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000569}
570
solenberg2397b9a2017-09-22 06:48:10 -0700571int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800572 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700573 return std::max(audio_coding_->ReceiveFrequency(),
574 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000575}
576
henrikaec6fbd22017-03-31 05:43:36 -0700577int32_t Channel::CreateChannel(Channel*& channel,
578 int32_t channelId,
579 uint32_t instanceId,
580 const VoEBase::ChannelConfig& config) {
solenberg88499ec2016-09-07 07:34:41 -0700581 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800582 if (channel == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100583 RTC_LOG(LS_ERROR) << "unable to allocate memory for new channel";
kwiberg55b97fe2016-01-28 05:22:45 -0800584 return -1;
585 }
586 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000587}
588
pbos@webrtc.org92135212013-05-14 08:31:39 +0000589Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000590 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700591 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800592 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100593 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700594 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800595 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100596 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800597 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100598 rtp_receive_statistics_(
599 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
600 rtp_receiver_(
601 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100602 this,
603 this,
604 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700605 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100606 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100607 _timeStamp(0), // This is just an offset, RTP module will add it's own
608 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100609 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100610 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100611 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100612 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100613 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
614 capture_start_rtp_time_stamp_(-1),
615 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100616 _moduleProcessThreadPtr(NULL),
617 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100618 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700619 input_mute_(false),
620 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100621 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100622 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800623 transport_overhead_per_packet_(0),
624 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100625 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100626 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700627 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800628 feedback_observer_proxy_(new TransportFeedbackProxy()),
629 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700630 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200631 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
632 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700633 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700634 use_twcc_plr_for_ana_(
635 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
solenberg88499ec2016-09-07 07:34:41 -0700636 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700637 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800638 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200639
kwiberg55b97fe2016-01-28 05:22:45 -0800640 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000641
kwiberg55b97fe2016-01-28 05:22:45 -0800642 RtpRtcp::Configuration configuration;
643 configuration.audio = true;
644 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800645 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800646 configuration.receive_statistics = rtp_receive_statistics_.get();
647 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800648 if (pacing_enabled_) {
649 configuration.paced_sender = rtp_packet_sender_proxy_.get();
650 configuration.transport_sequence_number_allocator =
651 seq_num_allocator_proxy_.get();
652 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
653 }
ivoc14d5dbe2016-07-04 07:06:55 -0700654 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800655 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200656 configuration.retransmission_rate_limiter =
657 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000658
kwiberg55b97fe2016-01-28 05:22:45 -0800659 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100660 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000661}
662
kwiberg55b97fe2016-01-28 05:22:45 -0800663Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700664 RTC_DCHECK(!channel_state_.Get().sending);
665 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000666}
667
kwiberg55b97fe2016-01-28 05:22:45 -0800668int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700669 RTC_DCHECK(construction_thread_.CalledOnValidThread());
niklase@google.com470e71d2011-07-07 08:21:25 +0000670
kwiberg55b97fe2016-01-28 05:22:45 -0800671 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000672
kwiberg55b97fe2016-01-28 05:22:45 -0800673 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000674
solenberg1c239d42017-09-29 06:00:28 -0700675 if (_moduleProcessThreadPtr == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100676 RTC_LOG(LS_ERROR)
677 << "Channel::Init() must call SetEngineInformation() first";
kwiberg55b97fe2016-01-28 05:22:45 -0800678 return -1;
679 }
680
681 // --- Add modules to process thread (for periodic schedulation)
682
tommidea489f2017-03-03 03:20:24 -0800683 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800684
685 // --- ACM initialization
686
687 if (audio_coding_->InitializeReceiver() == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100688 RTC_LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800689 return -1;
690 }
691
692 // --- RTP/RTCP module initialization
693
694 // Ensure that RTCP is enabled by default for the created channel.
695 // Note that, the module will keep generating RTCP until it is explicitly
696 // disabled by the user.
697 // After StopListen (when no sockets exists), RTCP packets will no longer
698 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700699 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800700 // RTCP is enabled by default.
701 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
702 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800703 if (audio_coding_->RegisterTransportCallback(this) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100704 RTC_LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800705 return -1;
706 }
707
kwiberg1c07c702017-03-27 07:15:49 -0700708 return 0;
709}
710
tommi0a2391f2017-03-21 02:31:51 -0700711void Channel::Terminate() {
712 RTC_DCHECK(construction_thread_.CalledOnValidThread());
713 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700714 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
715
716 StopSend();
717 StopPlayout();
718
tommi0a2391f2017-03-21 02:31:51 -0700719 // The order to safely shutdown modules in a channel is:
720 // 1. De-register callbacks in modules
721 // 2. De-register modules in process thread
722 // 3. Destroy modules
723 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100724 RTC_LOG(LS_WARNING)
725 << "Terminate() failed to de-register transport callback"
726 << " (Audio coding module)";
tommi0a2391f2017-03-21 02:31:51 -0700727 }
728
tommi0a2391f2017-03-21 02:31:51 -0700729 // De-register modules in process thread
730 if (_moduleProcessThreadPtr)
731 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
732
733 // End of modules shutdown
734}
735
solenberg1c239d42017-09-29 06:00:28 -0700736int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800737 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700738 rtc::TaskQueue* encoder_queue) {
739 RTC_DCHECK(encoder_queue);
740 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800741 _moduleProcessThreadPtr = &moduleProcessThread;
742 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700743 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800744 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000745}
746
kwibergb7f89d62016-02-17 10:04:18 -0800747void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800748 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800749 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100750}
751
ossu29b1a8d2016-06-13 07:34:51 -0700752const rtc::scoped_refptr<AudioDecoderFactory>&
753Channel::GetAudioDecoderFactory() const {
754 return decoder_factory_;
755}
756
kwiberg55b97fe2016-01-28 05:22:45 -0800757int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800758 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000759 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800760 }
761
kwiberg55b97fe2016-01-28 05:22:45 -0800762 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800763
764 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000765}
766
kwiberg55b97fe2016-01-28 05:22:45 -0800767int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800768 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000769 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800770 }
771
kwiberg55b97fe2016-01-28 05:22:45 -0800772 channel_state_.SetPlaying(false);
773 _outputAudioLevel.Clear();
774
775 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000776}
777
kwiberg55b97fe2016-01-28 05:22:45 -0800778int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800779 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000780 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800781 }
782 channel_state_.SetSending(true);
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100783
solenberg08b19df2017-02-15 00:42:31 -0800784 // Resume the previous sequence number which was reset by StopSend(). This
785 // needs to be done before |sending| is set to true on the RTP/RTCP module.
786 if (send_sequence_number_) {
787 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
788 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100789 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800790 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100791 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100792 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800793 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000794 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800795 return -1;
796 }
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100797 {
798 // It is now OK to start posting tasks to the encoder task queue.
799 rtc::CritScope cs(&encoder_queue_lock_);
800 encoder_queue_is_active_ = true;
801 }
kwiberg55b97fe2016-01-28 05:22:45 -0800802 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000803}
804
henrikaec6fbd22017-03-31 05:43:36 -0700805void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800806 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700807 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800808 }
809 channel_state_.SetSending(false);
810
henrikaec6fbd22017-03-31 05:43:36 -0700811 // Post a task to the encoder thread which sets an event when the task is
812 // executed. We know that no more encoding tasks will be added to the task
813 // queue for this channel since sending is now deactivated. It means that,
814 // if we wait for the event to bet set, we know that no more pending tasks
815 // exists and it is therfore guaranteed that the task queue will never try
816 // to acccess and invalid channel object.
817 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700818
henrikaec6fbd22017-03-31 05:43:36 -0700819 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700820 {
821 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
822 // than this final "flush task" to be posted on the queue.
823 rtc::CritScope cs(&encoder_queue_lock_);
824 encoder_queue_is_active_ = false;
825 encoder_queue_->PostTask([&flush]() { flush.Set(); });
826 }
henrikaec6fbd22017-03-31 05:43:36 -0700827 flush.Wait(rtc::Event::kForever);
828
kwiberg55b97fe2016-01-28 05:22:45 -0800829 // Store the sequence number to be able to pick up the same sequence for
830 // the next StartSend(). This is needed for restarting device, otherwise
831 // it might cause libSRTP to complain about packets being replayed.
832 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
833 // CL is landed. See issue
834 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
835 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
836
837 // Reset sending SSRC and sequence number and triggers direct transmission
838 // of RTCP BYE
839 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100840 RTC_LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800841 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100842 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000843}
844
ossu1ffbd6c2017-04-06 12:05:04 -0700845bool Channel::SetEncoder(int payload_type,
846 std::unique_ptr<AudioEncoder> encoder) {
847 RTC_DCHECK_GE(payload_type, 0);
848 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700849 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
850 // one for for us to keep track of sample rate and number of channels, etc.
851
852 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
853 // as well as some other things, so we collect this info and send it along.
854 CodecInst rtp_codec;
855 rtp_codec.pltype = payload_type;
856 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
857 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700858 // Seems unclear if it should be clock rate or sample rate. CodecInst
859 // supposedly carries the sample rate, but only clock rate seems sensible to
860 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700861 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
862 rtp_codec.pacsize = rtc::CheckedDivExact(
863 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
864 100);
865 rtp_codec.channels = encoder->NumChannels();
866 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700867
ossu76d29f92017-06-09 07:30:13 -0700868 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700869 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700870 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100871 RTC_LOG(LS_ERROR)
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200872 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700873 return false;
874 }
875 }
876
877 audio_coding_->SetEncoder(std::move(encoder));
878 return true;
879}
880
ossu20a4b3f2017-04-27 02:08:52 -0700881void Channel::ModifyEncoder(
882 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
883 audio_coding_->ModifyEncoder(modifier);
884}
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
minyue78b4d562016-11-30 04:47:39 -0800890void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -0700891 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -0800892 if (*encoder) {
Oskar Sundbom606c8822017-11-16 10:57:11 +0100893 (*encoder)->OnReceivedUplinkBandwidth(bitrate_bps, probing_interval_ms);
michaelt2fedf9c2016-11-28 02:34:18 -0800894 }
895 });
michaelt566d8202017-01-12 10:17:38 -0800896 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +0200897}
898
elad.alond12a8e12017-03-23 11:04:48 -0700899void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
900 if (!use_twcc_plr_for_ana_)
901 return;
minyue7e304322016-10-12 05:00:55 -0700902 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -0700903 if (*encoder) {
904 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
905 }
906 });
907}
908
elad.alondadb4dc2017-03-23 15:29:50 -0700909void Channel::OnRecoverableUplinkPacketLossRate(
910 float recoverable_packet_loss_rate) {
911 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
912 if (*encoder) {
913 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
914 recoverable_packet_loss_rate);
915 }
916 });
917}
918
elad.alond12a8e12017-03-23 11:04:48 -0700919void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
920 if (use_twcc_plr_for_ana_)
921 return;
922 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
923 if (*encoder) {
924 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
925 }
minyue7e304322016-10-12 05:00:55 -0700926 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000927}
928
kwiberg1c07c702017-03-27 07:15:49 -0700929void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
930 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
931 audio_coding_->SetReceiveCodecs(codecs);
932}
933
minyue7e304322016-10-12 05:00:55 -0700934bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
935 bool success = false;
936 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
937 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -0700938 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
939 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -0700940 }
941 });
942 return success;
943}
944
945void Channel::DisableAudioNetworkAdaptor() {
946 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
947 if (*encoder)
948 (*encoder)->DisableAudioNetworkAdaptor();
949 });
950}
951
952void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
953 int max_frame_length_ms) {
954 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
955 if (*encoder) {
956 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
957 max_frame_length_ms);
958 }
959 });
960}
961
solenberg1c239d42017-09-29 06:00:28 -0700962void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -0800963 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -0700964 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +0000965}
966
nisse657bab22017-02-21 06:28:10 -0800967void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -0800968 RTPHeader header;
969 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -0700970
971 // Store playout timestamp for the received RTP packet
972 UpdatePlayoutTimestamp(false);
973
974 header.payload_type_frequency =
975 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
976 if (header.payload_type_frequency >= 0) {
977 bool in_order = IsPacketInOrder(header);
978 rtp_receive_statistics_->IncomingPacket(
979 header, packet.size(), IsPacketRetransmitted(header, in_order));
980 rtp_payload_registry_->SetIncomingPayloadType(header);
981
Niels Möller22ec9522017-10-05 08:39:15 +0200982 ReceivePacket(packet.data(), packet.size(), header);
solenberg946d8862017-09-21 04:02:53 -0700983 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000984}
985
986bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000987 size_t packet_length,
Niels Möller22ec9522017-10-05 08:39:15 +0200988 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000989 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000990 assert(packet_length >= header.headerLength);
991 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +0200992 const auto pl =
993 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
994 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000995 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +0000996 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000997 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Niels Möller22ec9522017-10-05 08:39:15 +0200998 pl->typeSpecific);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000999}
1000
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001001bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1002 StreamStatistician* statistician =
1003 rtp_receive_statistics_->GetStatistician(header.ssrc);
1004 if (!statistician)
1005 return false;
1006 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001007}
1008
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001009bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1010 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001011 StreamStatistician* statistician =
1012 rtp_receive_statistics_->GetStatistician(header.ssrc);
1013 if (!statistician)
1014 return false;
1015 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001016 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001017 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001018 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001019}
1020
mflodman3d7db262016-04-29 00:57:13 -07001021int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001022 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001023 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001024
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001025 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001026 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001027
Minyue2013aec2015-05-13 14:14:42 +02001028 int64_t rtt = GetRTT(true);
1029 if (rtt == 0) {
1030 // Waiting for valid RTT.
1031 return 0;
1032 }
Erik Språng737336d2016-07-29 12:59:36 +02001033
1034 int64_t nack_window_ms = rtt;
1035 if (nack_window_ms < kMinRetransmissionWindowMs) {
1036 nack_window_ms = kMinRetransmissionWindowMs;
1037 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1038 nack_window_ms = kMaxRetransmissionWindowMs;
1039 }
1040 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1041
minyue7e304322016-10-12 05:00:55 -07001042 // Invoke audio encoders OnReceivedRtt().
1043 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1044 if (*encoder)
1045 (*encoder)->OnReceivedRtt(rtt);
1046 });
1047
Minyue2013aec2015-05-13 14:14:42 +02001048 uint32_t ntp_secs = 0;
1049 uint32_t ntp_frac = 0;
1050 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001051 if (0 !=
1052 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1053 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001054 // Waiting for RTCP.
1055 return 0;
1056 }
1057
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001058 {
tommi31fc21f2016-01-21 10:37:37 -08001059 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001060 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001061 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001062 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001063}
1064
solenberg8d73f8c2017-03-08 01:52:20 -08001065int Channel::GetSpeechOutputLevel() const {
1066 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001067}
1068
solenberg8d73f8c2017-03-08 01:52:20 -08001069int Channel::GetSpeechOutputLevelFullRange() const {
1070 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001071}
1072
zsteine76bd3a2017-07-14 12:17:49 -07001073double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001074 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001075}
1076
1077double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001078 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001079}
1080
solenberg8d73f8c2017-03-08 01:52:20 -08001081void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001082 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001083 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001084}
1085
solenberg1c2af8e2016-03-24 10:36:00 -07001086bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001087 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001088 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001089}
1090
solenberg8d73f8c2017-03-08 01:52:20 -08001091void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001092 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001093 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001094}
1095
solenberg8842c3e2016-03-11 03:06:41 -08001096int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001097 RTC_DCHECK_LE(0, event);
1098 RTC_DCHECK_GE(255, event);
1099 RTC_DCHECK_LE(0, duration_ms);
1100 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001101 if (!Sending()) {
1102 return -1;
1103 }
solenberg8842c3e2016-03-11 03:06:41 -08001104 if (_rtpRtcpModule->SendTelephoneEventOutband(
1105 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001106 RTC_LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001107 return -1;
1108 }
1109 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001110}
1111
solenbergffbbcac2016-11-17 05:25:37 -08001112int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1113 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001114 RTC_DCHECK_LE(0, payload_type);
1115 RTC_DCHECK_GE(127, payload_type);
1116 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001117 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001118 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001119 memcpy(codec.plname, "telephone-event", 16);
1120 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1121 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1122 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001123 RTC_LOG(LS_ERROR)
1124 << "SetSendTelephoneEventPayloadType() failed to register "
1125 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001126 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001127 }
kwiberg55b97fe2016-01-28 05:22:45 -08001128 }
kwiberg55b97fe2016-01-28 05:22:45 -08001129 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001130}
1131
kwiberg55b97fe2016-01-28 05:22:45 -08001132int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001133 if (channel_state_.Get().sending) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001134 RTC_LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001135 return -1;
1136 }
1137 _rtpRtcpModule->SetSSRC(ssrc);
1138 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001139}
1140
kwiberg55b97fe2016-01-28 05:22:45 -08001141int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1142 ssrc = rtp_receiver_->SSRC();
1143 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001144}
1145
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001146int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001147 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001148 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001149}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001150
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001151int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1152 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001153 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1154 if (enable &&
1155 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1156 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001157 return -1;
1158 }
1159 return 0;
1160}
1161
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001162void Channel::EnableSendTransportSequenceNumber(int id) {
1163 int ret =
1164 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1165 RTC_DCHECK_EQ(0, ret);
1166}
1167
stefan3313ec92016-01-21 06:32:43 -08001168void Channel::EnableReceiveTransportSequenceNumber(int id) {
1169 rtp_header_parser_->DeregisterRtpHeaderExtension(
1170 kRtpExtensionTransportSequenceNumber);
1171 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1172 kRtpExtensionTransportSequenceNumber, id);
1173 RTC_DCHECK(ret);
1174}
1175
stefanbba9dec2016-02-01 04:39:55 -08001176void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001177 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001178 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001179 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1180 TransportFeedbackObserver* transport_feedback_observer =
1181 transport->transport_feedback_observer();
1182 PacketRouter* packet_router = transport->packet_router();
1183
stefanbba9dec2016-02-01 04:39:55 -08001184 RTC_DCHECK(rtp_packet_sender);
1185 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001186 RTC_DCHECK(packet_router);
1187 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001188 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001189 feedback_observer_proxy_->SetTransportFeedbackObserver(
1190 transport_feedback_observer);
1191 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1192 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1193 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001194 constexpr bool remb_candidate = false;
1195 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001196 packet_router_ = packet_router;
1197}
1198
stefanbba9dec2016-02-01 04:39:55 -08001199void Channel::RegisterReceiverCongestionControlObjects(
1200 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001201 RTC_DCHECK(packet_router);
1202 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001203 constexpr bool remb_candidate = false;
1204 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001205 packet_router_ = packet_router;
1206}
1207
nissefdbfdc92017-03-31 05:44:52 -07001208void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001209 RTC_DCHECK(packet_router_);
1210 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001211 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001212 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1213 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001214 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001215 packet_router_ = nullptr;
1216 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1217}
1218
nissefdbfdc92017-03-31 05:44:52 -07001219void Channel::ResetReceiverCongestionControlObjects() {
1220 RTC_DCHECK(packet_router_);
1221 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1222 packet_router_ = nullptr;
1223}
1224
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001225void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001226 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001227}
1228
kwiberg55b97fe2016-01-28 05:22:45 -08001229int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001230 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001231 RTC_LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001232 return -1;
1233 }
1234 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001235}
1236
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001237int Channel::GetRemoteRTCPReportBlocks(
1238 std::vector<ReportBlock>* report_blocks) {
1239 if (report_blocks == NULL) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001240 RTC_LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001241 return -1;
1242 }
1243
1244 // Get the report blocks from the latest received RTCP Sender or Receiver
1245 // Report. Each element in the vector contains the sender's SSRC and a
1246 // report block according to RFC 3550.
1247 std::vector<RTCPReportBlock> rtcp_report_blocks;
1248 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001249 return -1;
1250 }
1251
1252 if (rtcp_report_blocks.empty())
1253 return 0;
1254
1255 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1256 for (; it != rtcp_report_blocks.end(); ++it) {
1257 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001258 report_block.sender_SSRC = it->sender_ssrc;
1259 report_block.source_SSRC = it->source_ssrc;
1260 report_block.fraction_lost = it->fraction_lost;
1261 report_block.cumulative_num_packets_lost = it->packets_lost;
1262 report_block.extended_highest_sequence_number =
1263 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001264 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001265 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1266 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001267 report_blocks->push_back(report_block);
1268 }
1269 return 0;
1270}
1271
kwiberg55b97fe2016-01-28 05:22:45 -08001272int Channel::GetRTPStatistics(CallStatistics& stats) {
1273 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001274
kwiberg55b97fe2016-01-28 05:22:45 -08001275 // The jitter statistics is updated for each received RTP packet and is
1276 // based on received packets.
1277 RtcpStatistics statistics;
1278 StreamStatistician* statistician =
1279 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001280 if (statistician) {
1281 statistician->GetStatistics(&statistics,
1282 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001283 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001284
kwiberg55b97fe2016-01-28 05:22:45 -08001285 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001286 stats.cumulativeLost = statistics.packets_lost;
1287 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001288 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001289
kwiberg55b97fe2016-01-28 05:22:45 -08001290 // --- RTT
1291 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001292
kwiberg55b97fe2016-01-28 05:22:45 -08001293 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001294
kwiberg55b97fe2016-01-28 05:22:45 -08001295 size_t bytesSent(0);
1296 uint32_t packetsSent(0);
1297 size_t bytesReceived(0);
1298 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001299
kwiberg55b97fe2016-01-28 05:22:45 -08001300 if (statistician) {
1301 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1302 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001303
kwiberg55b97fe2016-01-28 05:22:45 -08001304 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001305 RTC_LOG(LS_WARNING)
1306 << "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
Fredrik Solenberg2a877972017-12-15 16:42:15 +01001340void Channel::ProcessAndEncodeAudio(std::unique_ptr<AudioFrame> audio_frame) {
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 }
henrika45802172017-09-28 09:39:34 +02001346 // Profile time between when the audio frame is added to the task queue and
1347 // when the task is actually executed.
1348 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001349 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1350 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001351}
1352
henrikaec6fbd22017-03-31 05:43:36 -07001353void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1354 RTC_DCHECK_RUN_ON(encoder_queue_);
1355 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1356 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001357
henrika45802172017-09-28 09:39:34 +02001358 // Measure time between when the audio frame is added to the task queue and
1359 // when the task is actually executed. Goal is to keep track of unwanted
1360 // extra latency added by the task queue.
1361 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1362 audio_input->ElapsedProfileTimeMs());
1363
henrikaec6fbd22017-03-31 05:43:36 -07001364 bool is_muted = InputMute();
1365 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001366
kwiberg55b97fe2016-01-28 05:22:45 -08001367 if (_includeAudioLevelIndication) {
1368 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001369 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001370 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001371 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001372 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001373 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001374 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001375 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001376 }
kwiberg55b97fe2016-01-28 05:22:45 -08001377 }
solenberg1c2af8e2016-03-24 10:36:00 -07001378 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001379
henrikaec6fbd22017-03-31 05:43:36 -07001380 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001381
kwiberg55b97fe2016-01-28 05:22:45 -08001382 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001383 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001384 // This call will trigger AudioPacketizationCallback::SendData if encoding
1385 // is done and payload is ready for packetization and transmission.
1386 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001387 if (audio_coding_->Add10MsData(*audio_input) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001388 RTC_LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
henrikaec6fbd22017-03-31 05:43:36 -07001389 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001390 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001391
henrikaec6fbd22017-03-31 05:43:36 -07001392 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001393}
1394
solenberg7602aab2016-11-14 11:30:07 -08001395void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1396 RTC_DCHECK(!channel.channel() ||
1397 channel.channel()->ChannelId() != _channelId);
1398 rtc::CritScope lock(&assoc_send_channel_lock_);
1399 associate_send_channel_ = channel;
1400}
1401
Minyue2013aec2015-05-13 14:14:42 +02001402void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001403 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001404 Channel* channel = associate_send_channel_.channel();
1405 if (channel && channel->ChannelId() == channel_id) {
1406 // If this channel is associated with a send channel of the specified
1407 // Channel ID, disassociate with it.
1408 ChannelOwner ref(NULL);
1409 associate_send_channel_ = ref;
1410 }
1411}
1412
ivoc14d5dbe2016-07-04 07:06:55 -07001413void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1414 event_log_proxy_->SetEventLog(event_log);
1415}
1416
michaelt9332b7d2016-11-30 07:51:13 -08001417void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1418 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1419}
1420
nisse284542b2017-01-10 08:58:32 -08001421void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001422 size_t overhead_per_packet =
1423 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001424 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1425 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001426 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001427 }
1428 });
1429}
1430
1431void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001432 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001433 transport_overhead_per_packet_ = transport_overhead_per_packet;
1434 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001435}
1436
hbos3fd31fe2017-02-28 05:43:16 -08001437// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001438void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001439 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001440 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1441 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001442}
1443
kwiberg55b97fe2016-01-28 05:22:45 -08001444int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1445 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001446}
1447
wu@webrtc.org24301a62013-12-13 19:17:43 +00001448void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1449 audio_coding_->GetDecodingCallStatistics(stats);
1450}
1451
ivoce1198e02017-09-08 08:13:19 -07001452ANAStats Channel::GetANAStatistics() const {
1453 return audio_coding_->GetANAStats();
1454}
1455
solenberg358057b2015-11-27 10:46:42 -08001456uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001457 rtc::CritScope lock(&video_sync_lock_);
1458 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001459}
1460
kwiberg55b97fe2016-01-28 05:22:45 -08001461int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001462 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1463 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001464 RTC_LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001465 return -1;
1466 }
1467 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001468 RTC_LOG(LS_ERROR)
1469 << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001470 return -1;
1471 }
1472 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001473}
1474
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001475int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001476 uint32_t playout_timestamp_rtp = 0;
1477 {
tommi31fc21f2016-01-21 10:37:37 -08001478 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001479 playout_timestamp_rtp = playout_timestamp_rtp_;
1480 }
kwiberg55b97fe2016-01-28 05:22:45 -08001481 if (playout_timestamp_rtp == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001482 RTC_LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001483 return -1;
1484 }
deadbeef74375882015-08-13 12:09:10 -07001485 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001486 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001487}
1488
kwiberg55b97fe2016-01-28 05:22:45 -08001489int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1490 RtpReceiver** rtp_receiver) const {
1491 *rtpRtcpModule = _rtpRtcpModule.get();
1492 *rtp_receiver = rtp_receiver_.get();
1493 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001494}
1495
deadbeef74375882015-08-13 12:09:10 -07001496void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001497 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001498
henrik.lundin96bd5022016-04-06 04:13:56 -07001499 if (!jitter_buffer_playout_timestamp_) {
1500 // This can happen if this channel has not received any RTP packets. In
1501 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001502 return;
1503 }
1504
1505 uint16_t delay_ms = 0;
1506 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001507 RTC_LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1508 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001509 return;
1510 }
1511
henrik.lundin96bd5022016-04-06 04:13:56 -07001512 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1513 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001514
1515 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001516 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001517
deadbeef74375882015-08-13 12:09:10 -07001518 {
tommi31fc21f2016-01-21 10:37:37 -08001519 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001520 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001521 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001522 }
1523 playout_delay_ms_ = delay_ms;
1524 }
1525}
1526
kwiberg55b97fe2016-01-28 05:22:45 -08001527void Channel::RegisterReceiveCodecsToRTPModule() {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001528 // TODO(kwiberg): Iterate over the factory's supported codecs instead?
1529 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001530 for (int idx = 0; idx < nSupportedCodecs; idx++) {
Karl Wibergc62f6c72017-10-04 12:38:53 +02001531 CodecInst codec;
1532 if (audio_coding_->Codec(idx, &codec) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001533 RTC_LOG(LS_WARNING) << "Unable to register codec #" << idx
1534 << " for RTP/RTCP receiver.";
Karl Wibergc62f6c72017-10-04 12:38:53 +02001535 continue;
1536 }
1537 const SdpAudioFormat format = CodecInstToSdp(codec);
1538 if (!decoder_factory_->IsSupportedDecoder(format) ||
1539 rtp_receiver_->RegisterReceivePayload(codec.pltype, format) == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001540 RTC_LOG(LS_WARNING) << "Unable to register " << format
1541 << " for RTP/RTCP receiver.";
niklase@google.com470e71d2011-07-07 08:21:25 +00001542 }
kwiberg55b97fe2016-01-28 05:22:45 -08001543 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001544}
1545
kwiberg55b97fe2016-01-28 05:22:45 -08001546int Channel::SetSendRtpHeaderExtension(bool enable,
1547 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001548 unsigned char id) {
1549 int error = 0;
1550 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1551 if (enable) {
1552 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1553 }
1554 return error;
1555}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001556
ossue280cde2016-10-12 11:04:10 -07001557int Channel::GetRtpTimestampRateHz() const {
1558 const auto format = audio_coding_->ReceiveFormat();
1559 // Default to the playout frequency if we've not gotten any packets yet.
1560 // TODO(ossu): Zero clockrate can only happen if we've added an external
1561 // decoder for a format we don't support internally. Remove once that way of
1562 // adding decoders is gone!
1563 return (format && format->clockrate_hz != 0)
1564 ? format->clockrate_hz
1565 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001566}
1567
Minyue2013aec2015-05-13 14:14:42 +02001568int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001569 RtcpMode method = _rtpRtcpModule->RTCP();
1570 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001571 return 0;
1572 }
1573 std::vector<RTCPReportBlock> report_blocks;
1574 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001575
1576 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001577 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001578 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001579 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001580 Channel* channel = associate_send_channel_.channel();
1581 // Tries to get RTT from an associated channel. This is important for
1582 // receive-only channels.
1583 if (channel) {
1584 // To prevent infinite recursion and deadlock, calling GetRTT of
1585 // associate channel should always use "false" for argument:
1586 // |allow_associate_channel|.
1587 rtt = channel->GetRTT(false);
1588 }
1589 }
1590 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001591 }
1592
1593 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1594 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1595 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001596 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001597 break;
1598 }
1599 if (it == report_blocks.end()) {
1600 // We have not received packets with SSRC matching the report blocks.
1601 // To calculate RTT we try with the SSRC of the first report block.
1602 // This is very important for send-only channels where we don't know
1603 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001604 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001605 }
Minyue2013aec2015-05-13 14:14:42 +02001606
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001607 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001608 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001609 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001610 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1611 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001612 return 0;
1613 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001614 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001615}
1616
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001617} // namespace voe
1618} // namespace webrtc