blob: 73da3d14bd08e84e37b73e73d62ff85037e681f9 [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>
15#include <string>
Tommif888bb52015-12-12 01:37:01 +010016#include <utility>
Bjorn Terelius440216f2017-09-29 21:01:42 +020017#include <vector>
Henrik Lundin64dad832015-05-11 12:44:23 +020018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/array_view.h"
20#include "audio/utility/audio_frame_operations.h"
21#include "call/rtp_transport_controller_send_interface.h"
22#include "logging/rtc_event_log/rtc_event_log.h"
23#include "modules/audio_coding/codecs/audio_format_conversion.h"
24#include "modules/audio_device/include/audio_device.h"
25#include "modules/audio_processing/include/audio_processing.h"
26#include "modules/include/module_common_types.h"
27#include "modules/pacing/packet_router.h"
28#include "modules/rtp_rtcp/include/receive_statistics.h"
29#include "modules/rtp_rtcp/include/rtp_payload_registry.h"
30#include "modules/rtp_rtcp/include/rtp_receiver.h"
31#include "modules/rtp_rtcp/source/rtp_packet_received.h"
32#include "modules/rtp_rtcp/source/rtp_receiver_strategy.h"
33#include "modules/utility/include/process_thread.h"
34#include "rtc_base/checks.h"
35#include "rtc_base/criticalsection.h"
36#include "rtc_base/format_macros.h"
37#include "rtc_base/location.h"
38#include "rtc_base/logging.h"
39#include "rtc_base/rate_limiter.h"
40#include "rtc_base/task_queue.h"
41#include "rtc_base/thread_checker.h"
42#include "rtc_base/timeutils.h"
43#include "system_wrappers/include/field_trial.h"
henrika45802172017-09-28 09:39:34 +020044#include "system_wrappers/include/metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000046
andrew@webrtc.org50419b02012-11-14 19:07:54 +000047namespace webrtc {
48namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000049
kwibergc8d071e2016-04-06 12:22:38 -070050namespace {
51
zsteine76bd3a2017-07-14 12:17:49 -070052constexpr double kAudioSampleDurationSeconds = 0.01;
Erik Språng737336d2016-07-29 12:59:36 +020053constexpr int64_t kMaxRetransmissionWindowMs = 1000;
54constexpr int64_t kMinRetransmissionWindowMs = 30;
55
kwibergc8d071e2016-04-06 12:22:38 -070056} // namespace
57
solenberg8842c3e2016-03-11 03:06:41 -080058const int kTelephoneEventAttenuationdB = 10;
59
ivoc14d5dbe2016-07-04 07:06:55 -070060class RtcEventLogProxy final : public webrtc::RtcEventLog {
61 public:
62 RtcEventLogProxy() : event_log_(nullptr) {}
63
64 bool StartLogging(const std::string& file_name,
65 int64_t max_size_bytes) override {
66 RTC_NOTREACHED();
67 return false;
68 }
69
70 bool StartLogging(rtc::PlatformFile log_file,
71 int64_t max_size_bytes) override {
72 RTC_NOTREACHED();
73 return false;
74 }
75
76 void StopLogging() override { RTC_NOTREACHED(); }
77
78 void LogVideoReceiveStreamConfig(
perkj09e71da2017-05-22 03:26:49 -070079 const webrtc::rtclog::StreamConfig&) override {
80 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070081 }
82
perkjc0876aa2017-05-22 04:08:28 -070083 void LogVideoSendStreamConfig(const webrtc::rtclog::StreamConfig&) override {
84 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070085 }
86
ivoce0928d82016-10-10 05:12:51 -070087 void LogAudioReceiveStreamConfig(
perkjac8f52d2017-05-22 09:36:28 -070088 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070089 rtc::CritScope lock(&crit_);
90 if (event_log_) {
91 event_log_->LogAudioReceiveStreamConfig(config);
92 }
93 }
94
95 void LogAudioSendStreamConfig(
perkjf4726992017-05-22 10:12:26 -070096 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070097 rtc::CritScope lock(&crit_);
98 if (event_log_) {
99 event_log_->LogAudioSendStreamConfig(config);
100 }
101 }
102
Bjorn Terelius440216f2017-09-29 21:01:42 +0200103 void LogIncomingRtpHeader(const RtpPacketReceived& packet) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700104 rtc::CritScope lock(&crit_);
105 if (event_log_) {
Bjorn Terelius440216f2017-09-29 21:01:42 +0200106 event_log_->LogIncomingRtpHeader(packet);
ivoc14d5dbe2016-07-04 07:06:55 -0700107 }
108 }
109
Bjorn Terelius440216f2017-09-29 21:01:42 +0200110 void LogOutgoingRtpHeader(const RtpPacketToSend& packet,
111 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700112 rtc::CritScope lock(&crit_);
113 if (event_log_) {
Bjorn Terelius440216f2017-09-29 21:01:42 +0200114 event_log_->LogOutgoingRtpHeader(packet, probe_cluster_id);
115 }
116 }
117
118 void LogIncomingRtcpPacket(rtc::ArrayView<const uint8_t> packet) override {
119 rtc::CritScope lock(&crit_);
120 if (event_log_) {
121 event_log_->LogIncomingRtcpPacket(packet);
122 }
123 }
124
125 void LogOutgoingRtcpPacket(rtc::ArrayView<const uint8_t> packet) override {
126 rtc::CritScope lock(&crit_);
127 if (event_log_) {
128 event_log_->LogOutgoingRtcpPacket(packet);
ivoc14d5dbe2016-07-04 07:06:55 -0700129 }
130 }
131
132 void LogAudioPlayout(uint32_t ssrc) override {
133 rtc::CritScope lock(&crit_);
134 if (event_log_) {
135 event_log_->LogAudioPlayout(ssrc);
136 }
137 }
138
terelius424e6cf2017-02-20 05:14:41 -0800139 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700140 uint8_t fraction_loss,
141 int32_t total_packets) override {
142 rtc::CritScope lock(&crit_);
143 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800144 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
145 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700146 }
147 }
148
terelius424e6cf2017-02-20 05:14:41 -0800149 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800150 BandwidthUsage detector_state) override {
151 rtc::CritScope lock(&crit_);
152 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800153 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800154 }
155 }
156
minyue4b7c9522017-01-24 04:54:59 -0800157 void LogAudioNetworkAdaptation(
michaeltcde46b72017-04-06 05:59:10 -0700158 const AudioEncoderRuntimeConfig& config) override {
minyue4b7c9522017-01-24 04:54:59 -0800159 rtc::CritScope lock(&crit_);
160 if (event_log_) {
161 event_log_->LogAudioNetworkAdaptation(config);
162 }
163 }
164
philipel32d00102017-02-27 02:18:46 -0800165 void LogProbeClusterCreated(int id,
166 int bitrate_bps,
167 int min_probes,
168 int min_bytes) override {
169 rtc::CritScope lock(&crit_);
170 if (event_log_) {
171 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
172 min_bytes);
173 }
174 };
175
176 void LogProbeResultSuccess(int id, int bitrate_bps) override {
177 rtc::CritScope lock(&crit_);
178 if (event_log_) {
179 event_log_->LogProbeResultSuccess(id, bitrate_bps);
180 }
181 };
182
183 void LogProbeResultFailure(int id,
184 ProbeFailureReason failure_reason) override {
185 rtc::CritScope lock(&crit_);
186 if (event_log_) {
187 event_log_->LogProbeResultFailure(id, failure_reason);
188 }
189 };
190
ivoc14d5dbe2016-07-04 07:06:55 -0700191 void SetEventLog(RtcEventLog* event_log) {
192 rtc::CritScope lock(&crit_);
193 event_log_ = event_log;
194 }
195
196 private:
197 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700198 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -0700199 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
200};
201
michaelt9332b7d2016-11-30 07:51:13 -0800202class RtcpRttStatsProxy final : public RtcpRttStats {
203 public:
204 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
205
206 void OnRttUpdate(int64_t rtt) override {
207 rtc::CritScope lock(&crit_);
208 if (rtcp_rtt_stats_)
209 rtcp_rtt_stats_->OnRttUpdate(rtt);
210 }
211
212 int64_t LastProcessedRtt() const override {
213 rtc::CritScope lock(&crit_);
214 if (!rtcp_rtt_stats_)
215 return 0;
216 return rtcp_rtt_stats_->LastProcessedRtt();
217 }
218
219 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
220 rtc::CritScope lock(&crit_);
221 rtcp_rtt_stats_ = rtcp_rtt_stats;
222 }
223
224 private:
225 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700226 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800227 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
228};
229
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100230class TransportFeedbackProxy : public TransportFeedbackObserver {
231 public:
232 TransportFeedbackProxy() : feedback_observer_(nullptr) {
233 pacer_thread_.DetachFromThread();
234 network_thread_.DetachFromThread();
235 }
236
237 void SetTransportFeedbackObserver(
238 TransportFeedbackObserver* feedback_observer) {
239 RTC_DCHECK(thread_checker_.CalledOnValidThread());
240 rtc::CritScope lock(&crit_);
241 feedback_observer_ = feedback_observer;
242 }
243
244 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700245 void AddPacket(uint32_t ssrc,
246 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100247 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800248 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100249 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
250 rtc::CritScope lock(&crit_);
251 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700252 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100253 }
philipel8aadd502017-02-23 02:56:13 -0800254
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100255 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
256 RTC_DCHECK(network_thread_.CalledOnValidThread());
257 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700258 if (feedback_observer_)
259 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200260 }
elad.alonf9490002017-03-06 05:32:21 -0800261 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200262 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800263 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100264 }
265
266 private:
267 rtc::CriticalSection crit_;
268 rtc::ThreadChecker thread_checker_;
269 rtc::ThreadChecker pacer_thread_;
270 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700271 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100272};
273
274class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
275 public:
276 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
277 pacer_thread_.DetachFromThread();
278 }
279
280 void SetSequenceNumberAllocator(
281 TransportSequenceNumberAllocator* seq_num_allocator) {
282 RTC_DCHECK(thread_checker_.CalledOnValidThread());
283 rtc::CritScope lock(&crit_);
284 seq_num_allocator_ = seq_num_allocator;
285 }
286
287 // Implements TransportSequenceNumberAllocator.
288 uint16_t AllocateSequenceNumber() override {
289 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
290 rtc::CritScope lock(&crit_);
291 if (!seq_num_allocator_)
292 return 0;
293 return seq_num_allocator_->AllocateSequenceNumber();
294 }
295
296 private:
297 rtc::CriticalSection crit_;
298 rtc::ThreadChecker thread_checker_;
299 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700300 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100301};
302
303class RtpPacketSenderProxy : public RtpPacketSender {
304 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800305 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100306
307 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
308 RTC_DCHECK(thread_checker_.CalledOnValidThread());
309 rtc::CritScope lock(&crit_);
310 rtp_packet_sender_ = rtp_packet_sender;
311 }
312
313 // Implements RtpPacketSender.
314 void InsertPacket(Priority priority,
315 uint32_t ssrc,
316 uint16_t sequence_number,
317 int64_t capture_time_ms,
318 size_t bytes,
319 bool retransmission) override {
320 rtc::CritScope lock(&crit_);
321 if (rtp_packet_sender_) {
322 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
323 capture_time_ms, bytes, retransmission);
324 }
325 }
326
327 private:
328 rtc::ThreadChecker thread_checker_;
329 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700330 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100331};
332
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000333class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000334 public:
stefan7de8d642017-02-07 07:14:08 -0800335 explicit VoERtcpObserver(Channel* owner)
336 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000337 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000338
stefan7de8d642017-02-07 07:14:08 -0800339 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
340 rtc::CritScope lock(&crit_);
341 bandwidth_observer_ = bandwidth_observer;
342 }
343
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000344 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800345 rtc::CritScope lock(&crit_);
346 if (bandwidth_observer_) {
347 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
348 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000349 }
350
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000351 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
352 int64_t rtt,
353 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800354 {
355 rtc::CritScope lock(&crit_);
356 if (bandwidth_observer_) {
357 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
358 now_ms);
359 }
360 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000361 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
362 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
363 // report for VoiceEngine?
364 if (report_blocks.empty())
365 return;
366
367 int fraction_lost_aggregate = 0;
368 int total_number_of_packets = 0;
369
370 // If receiving multiple report blocks, calculate the weighted average based
371 // on the number of packets a report refers to.
372 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
373 block_it != report_blocks.end(); ++block_it) {
374 // Find the previous extended high sequence number for this remote SSRC,
375 // to calculate the number of RTP packets this report refers to. Ignore if
376 // we haven't seen this SSRC before.
377 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700378 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000379 int number_of_packets = 0;
380 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700381 number_of_packets =
382 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000383 }
srte3e69e5c2017-08-09 06:13:45 -0700384 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000385 total_number_of_packets += number_of_packets;
386
srte3e69e5c2017-08-09 06:13:45 -0700387 extended_max_sequence_number_[block_it->source_ssrc] =
388 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000389 }
390 int weighted_fraction_lost = 0;
391 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800392 weighted_fraction_lost =
393 (fraction_lost_aggregate + total_number_of_packets / 2) /
394 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000395 }
elad.alond12a8e12017-03-23 11:04:48 -0700396 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000397 }
398
399 private:
400 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000401 // Maps remote side ssrc to extended highest sequence number received.
402 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800403 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700404 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000405};
406
henrikaec6fbd22017-03-31 05:43:36 -0700407class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
408 public:
409 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
410 Channel* channel)
411 : audio_frame_(std::move(audio_frame)), channel_(channel) {
412 RTC_DCHECK(channel_);
413 }
414
415 private:
416 bool Run() override {
417 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
418 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
419 return true;
420 }
421
422 std::unique_ptr<AudioFrame> audio_frame_;
423 Channel* const channel_;
424};
425
kwiberg55b97fe2016-01-28 05:22:45 -0800426int32_t Channel::SendData(FrameType frameType,
427 uint8_t payloadType,
428 uint32_t timeStamp,
429 const uint8_t* payloadData,
430 size_t payloadSize,
431 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700432 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800433 if (_includeAudioLevelIndication) {
434 // Store current audio level in the RTP/RTCP module.
435 // The level will be used in combination with voice-activity state
436 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800437 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800438 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000439
kwiberg55b97fe2016-01-28 05:22:45 -0800440 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
441 // packetization.
442 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700443 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800444 (FrameType&)frameType, payloadType, timeStamp,
445 // Leaving the time when this frame was
446 // received from the capture device as
447 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700448 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
solenberg1c239d42017-09-29 06:00:28 -0700449 LOG(LS_ERROR) <<
450 "Channel::SendData() failed to send data to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -0800451 return -1;
452 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000453
kwiberg55b97fe2016-01-28 05:22:45 -0800454 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000455}
456
stefan1d8a5062015-10-02 03:39:33 -0700457bool Channel::SendRtp(const uint8_t* data,
458 size_t len,
459 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800460 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000461
kwiberg55b97fe2016-01-28 05:22:45 -0800462 if (_transportPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200463 LOG(LS_ERROR) << "Channel::SendPacket() failed to send RTP packet due to"
464 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800465 return false;
466 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000467
kwiberg55b97fe2016-01-28 05:22:45 -0800468 uint8_t* bufferToSendPtr = (uint8_t*)data;
469 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000470
kwiberg55b97fe2016-01-28 05:22:45 -0800471 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
solenberg1c239d42017-09-29 06:00:28 -0700472 LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800473 return false;
474 }
475 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000476}
477
kwiberg55b97fe2016-01-28 05:22:45 -0800478bool Channel::SendRtcp(const uint8_t* data, size_t len) {
kwiberg55b97fe2016-01-28 05:22:45 -0800479 rtc::CritScope cs(&_callbackCritSect);
480 if (_transportPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200481 LOG(LS_ERROR) << "Channel::SendRtcp() failed to send RTCP packet due to"
482 << " invalid transport object";
kwiberg55b97fe2016-01-28 05:22:45 -0800483 return false;
484 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000485
kwiberg55b97fe2016-01-28 05:22:45 -0800486 uint8_t* bufferToSendPtr = (uint8_t*)data;
487 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000488
kwiberg55b97fe2016-01-28 05:22:45 -0800489 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
490 if (n < 0) {
solenberg1c239d42017-09-29 06:00:28 -0700491 LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800492 return false;
493 }
494 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000495}
496
kwiberg55b97fe2016-01-28 05:22:45 -0800497void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -0800498 // Update ssrc so that NTP for AV sync can be updated.
499 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000500}
501
Peter Boströmac547a62015-09-17 23:03:57 +0200502void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200503 // TODO(saza): remove.
niklase@google.com470e71d2011-07-07 08:21:25 +0000504}
505
Peter Boströmac547a62015-09-17 23:03:57 +0200506int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000507 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000508 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000509 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800510 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200511 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800512 CodecInst receiveCodec = {0};
513 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000514
kwiberg55b97fe2016-01-28 05:22:45 -0800515 receiveCodec.pltype = payloadType;
516 receiveCodec.plfreq = frequency;
517 receiveCodec.channels = channels;
518 receiveCodec.rate = rate;
519 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000520
kwiberg55b97fe2016-01-28 05:22:45 -0800521 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
522 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000523
kwiberg55b97fe2016-01-28 05:22:45 -0800524 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700525 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
526 CodecInstToSdp(receiveCodec))) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200527 LOG(LS_WARNING) << "Channel::OnInitializeDecoder() invalid codec (pt="
528 << payloadType << ", name=" << payloadName
529 << ") received - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800530 return -1;
531 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000532
kwiberg55b97fe2016-01-28 05:22:45 -0800533 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000534}
535
kwiberg55b97fe2016-01-28 05:22:45 -0800536int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
537 size_t payloadSize,
538 const WebRtcRTPHeader* rtpHeader) {
kwiberg55b97fe2016-01-28 05:22:45 -0800539 if (!channel_state_.Get().playing) {
540 // Avoid inserting into NetEQ when we are not playing. Count the
541 // packet as discarded.
niklase@google.com470e71d2011-07-07 08:21:25 +0000542 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800543 }
544
545 // Push the incoming payload (parsed and ready for decoding) into the ACM
546 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
547 0) {
solenberg1c239d42017-09-29 06:00:28 -0700548 LOG(LS_ERROR) <<
549 "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800550 return -1;
551 }
552
kwiberg55b97fe2016-01-28 05:22:45 -0800553 int64_t round_trip_time = 0;
554 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
555 NULL);
556
557 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
558 if (!nack_list.empty()) {
559 // Can't use nack_list.data() since it's not supported by all
560 // compilers.
561 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
562 }
563 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000564}
565
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000566bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000567 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000568 RTPHeader header;
569 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200570 LOG(LS_WARNING) << "IncomingPacket invalid RTP header";
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000571 return false;
572 }
573 header.payload_type_frequency =
574 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
575 if (header.payload_type_frequency < 0)
576 return false;
577 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
578}
579
solenberg2397b9a2017-09-22 06:48:10 -0700580AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
581 int sample_rate_hz,
582 AudioFrame* audio_frame) {
583 audio_frame->sample_rate_hz_ = sample_rate_hz;
584
ivoc14d5dbe2016-07-04 07:06:55 -0700585 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800586 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700587 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800588 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700589 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700590 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700591 &muted) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200592 LOG(LS_ERROR) << "Channel::GetAudioFrame() PlayoutData10Ms() failed!";
kwiberg55b97fe2016-01-28 05:22:45 -0800593 // In all likelihood, the audio in this frame is garbage. We return an
594 // error so that the audio mixer module doesn't add it to the mix. As
595 // a result, it won't be played out and the actions skipped here are
596 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700597 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800598 }
henrik.lundina89ab962016-05-18 08:52:45 -0700599
600 if (muted) {
601 // TODO(henrik.lundin): We should be able to do better than this. But we
602 // will have to go through all the cases below where the audio samples may
603 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700604 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700605 }
kwiberg55b97fe2016-01-28 05:22:45 -0800606
kwiberg55b97fe2016-01-28 05:22:45 -0800607 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700608 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800609
kwiberg55b97fe2016-01-28 05:22:45 -0800610 {
611 // Pass the audio buffers to an optional sink callback, before applying
612 // scaling/panning, as that applies to the mix operation.
613 // External recipients of the audio (e.g. via AudioTrack), will do their
614 // own mixing/dynamic processing.
615 rtc::CritScope cs(&_callbackCritSect);
616 if (audio_sink_) {
617 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700618 audio_frame->data(), audio_frame->samples_per_channel_,
619 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
620 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800621 audio_sink_->OnData(data);
622 }
623 }
624
625 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800626 {
627 rtc::CritScope cs(&volume_settings_critsect_);
628 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800629 }
630
631 // Output volume scaling
632 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800633 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700634 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800635 }
636
kwiberg55b97fe2016-01-28 05:22:45 -0800637 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700638 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700639 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700640 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700641 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800642
solenberg2397b9a2017-09-22 06:48:10 -0700643 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800644 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700645 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800646 }
647
648 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700649 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800650
651 // Compute elapsed time.
652 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700653 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
654 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800655 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700656 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800657
niklase@google.com470e71d2011-07-07 08:21:25 +0000658 {
kwiberg55b97fe2016-01-28 05:22:45 -0800659 rtc::CritScope lock(&ts_stats_lock_);
660 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700661 audio_frame->ntp_time_ms_ =
662 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800663 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700664 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800665 // Compute |capture_start_ntp_time_ms_| so that
666 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
667 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700668 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000669 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000670 }
kwiberg55b97fe2016-01-28 05:22:45 -0800671 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000672
solenberg2397b9a2017-09-22 06:48:10 -0700673 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
674 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000675}
676
solenberg2397b9a2017-09-22 06:48:10 -0700677int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800678 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700679 return std::max(audio_coding_->ReceiveFrequency(),
680 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000681}
682
henrikaec6fbd22017-03-31 05:43:36 -0700683int32_t Channel::CreateChannel(Channel*& channel,
684 int32_t channelId,
685 uint32_t instanceId,
686 const VoEBase::ChannelConfig& config) {
solenberg88499ec2016-09-07 07:34:41 -0700687 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800688 if (channel == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200689 LOG(LS_ERROR) << "unable to allocate memory for new channel";
kwiberg55b97fe2016-01-28 05:22:45 -0800690 return -1;
691 }
692 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000693}
694
pbos@webrtc.org92135212013-05-14 08:31:39 +0000695Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000696 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700697 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800698 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100699 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700700 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800701 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100702 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800703 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100704 rtp_receive_statistics_(
705 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
706 rtp_receiver_(
707 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100708 this,
709 this,
710 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700711 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100712 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100713 _timeStamp(0), // This is just an offset, RTP module will add it's own
714 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100715 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100716 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100717 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100718 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100719 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
720 capture_start_rtp_time_stamp_(-1),
721 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100722 _moduleProcessThreadPtr(NULL),
723 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100724 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700725 input_mute_(false),
726 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100727 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100728 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800729 transport_overhead_per_packet_(0),
730 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100731 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100732 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100733 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700734 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800735 feedback_observer_proxy_(new TransportFeedbackProxy()),
736 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700737 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200738 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
739 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700740 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700741 use_twcc_plr_for_ana_(
742 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
solenberg88499ec2016-09-07 07:34:41 -0700743 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700744 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800745 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200746
kwiberg55b97fe2016-01-28 05:22:45 -0800747 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000748
kwiberg55b97fe2016-01-28 05:22:45 -0800749 RtpRtcp::Configuration configuration;
750 configuration.audio = true;
751 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800752 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800753 configuration.receive_statistics = rtp_receive_statistics_.get();
754 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800755 if (pacing_enabled_) {
756 configuration.paced_sender = rtp_packet_sender_proxy_.get();
757 configuration.transport_sequence_number_allocator =
758 seq_num_allocator_proxy_.get();
759 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
760 }
ivoc14d5dbe2016-07-04 07:06:55 -0700761 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800762 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200763 configuration.retransmission_rate_limiter =
764 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000765
kwiberg55b97fe2016-01-28 05:22:45 -0800766 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100767 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000768}
769
kwiberg55b97fe2016-01-28 05:22:45 -0800770Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700771 RTC_DCHECK(!channel_state_.Get().sending);
772 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000773}
774
kwiberg55b97fe2016-01-28 05:22:45 -0800775int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700776 RTC_DCHECK(construction_thread_.CalledOnValidThread());
niklase@google.com470e71d2011-07-07 08:21:25 +0000777
kwiberg55b97fe2016-01-28 05:22:45 -0800778 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000779
kwiberg55b97fe2016-01-28 05:22:45 -0800780 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000781
solenberg1c239d42017-09-29 06:00:28 -0700782 if (_moduleProcessThreadPtr == NULL) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200783 LOG(LS_ERROR) << "Channel::Init() must call SetEngineInformation() first";
kwiberg55b97fe2016-01-28 05:22:45 -0800784 return -1;
785 }
786
787 // --- Add modules to process thread (for periodic schedulation)
788
tommidea489f2017-03-03 03:20:24 -0800789 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800790
791 // --- ACM initialization
792
793 if (audio_coding_->InitializeReceiver() == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700794 LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800795 return -1;
796 }
797
798 // --- RTP/RTCP module initialization
799
800 // Ensure that RTCP is enabled by default for the created channel.
801 // Note that, the module will keep generating RTCP until it is explicitly
802 // disabled by the user.
803 // After StopListen (when no sockets exists), RTCP packets will no longer
804 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700805 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800806 // RTCP is enabled by default.
807 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
808 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800809 if (audio_coding_->RegisterTransportCallback(this) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700810 LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800811 return -1;
812 }
813
kwiberg1c07c702017-03-27 07:15:49 -0700814 return 0;
815}
816
tommi0a2391f2017-03-21 02:31:51 -0700817void Channel::Terminate() {
818 RTC_DCHECK(construction_thread_.CalledOnValidThread());
819 // Must be called on the same thread as Init().
tommi0a2391f2017-03-21 02:31:51 -0700820 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
821
822 StopSend();
823 StopPlayout();
824
tommi0a2391f2017-03-21 02:31:51 -0700825 // The order to safely shutdown modules in a channel is:
826 // 1. De-register callbacks in modules
827 // 2. De-register modules in process thread
828 // 3. Destroy modules
829 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200830 LOG(LS_WARNING) << "Terminate() failed to de-register transport callback"
831 << " (Audio coding module)";
tommi0a2391f2017-03-21 02:31:51 -0700832 }
833
tommi0a2391f2017-03-21 02:31:51 -0700834 // De-register modules in process thread
835 if (_moduleProcessThreadPtr)
836 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
837
838 // End of modules shutdown
839}
840
solenberg1c239d42017-09-29 06:00:28 -0700841int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800842 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700843 rtc::TaskQueue* encoder_queue) {
844 RTC_DCHECK(encoder_queue);
845 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800846 _moduleProcessThreadPtr = &moduleProcessThread;
847 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700848 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800849 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000850}
851
kwibergb7f89d62016-02-17 10:04:18 -0800852void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800853 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800854 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100855}
856
ossu29b1a8d2016-06-13 07:34:51 -0700857const rtc::scoped_refptr<AudioDecoderFactory>&
858Channel::GetAudioDecoderFactory() const {
859 return decoder_factory_;
860}
861
kwiberg55b97fe2016-01-28 05:22:45 -0800862int32_t Channel::StartPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800863 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000864 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800865 }
866
kwiberg55b97fe2016-01-28 05:22:45 -0800867 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800868
869 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000870}
871
kwiberg55b97fe2016-01-28 05:22:45 -0800872int32_t Channel::StopPlayout() {
kwiberg55b97fe2016-01-28 05:22:45 -0800873 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000874 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800875 }
876
kwiberg55b97fe2016-01-28 05:22:45 -0800877 channel_state_.SetPlaying(false);
878 _outputAudioLevel.Clear();
879
880 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000881}
882
kwiberg55b97fe2016-01-28 05:22:45 -0800883int32_t Channel::StartSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800884 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000885 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800886 }
887 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700888 {
889 // It is now OK to start posting tasks to the encoder task queue.
890 rtc::CritScope cs(&encoder_queue_lock_);
891 encoder_queue_is_active_ = true;
892 }
solenberg08b19df2017-02-15 00:42:31 -0800893 // Resume the previous sequence number which was reset by StopSend(). This
894 // needs to be done before |sending| is set to true on the RTP/RTCP module.
895 if (send_sequence_number_) {
896 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
897 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100898 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800899 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
solenberg1c239d42017-09-29 06:00:28 -0700900 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100901 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800902 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000903 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800904 return -1;
905 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000906
kwiberg55b97fe2016-01-28 05:22:45 -0800907 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000908}
909
henrikaec6fbd22017-03-31 05:43:36 -0700910void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800911 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700912 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800913 }
914 channel_state_.SetSending(false);
915
henrikaec6fbd22017-03-31 05:43:36 -0700916 // Post a task to the encoder thread which sets an event when the task is
917 // executed. We know that no more encoding tasks will be added to the task
918 // queue for this channel since sending is now deactivated. It means that,
919 // if we wait for the event to bet set, we know that no more pending tasks
920 // exists and it is therfore guaranteed that the task queue will never try
921 // to acccess and invalid channel object.
922 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700923
henrikaec6fbd22017-03-31 05:43:36 -0700924 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700925 {
926 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
927 // than this final "flush task" to be posted on the queue.
928 rtc::CritScope cs(&encoder_queue_lock_);
929 encoder_queue_is_active_ = false;
930 encoder_queue_->PostTask([&flush]() { flush.Set(); });
931 }
henrikaec6fbd22017-03-31 05:43:36 -0700932 flush.Wait(rtc::Event::kForever);
933
kwiberg55b97fe2016-01-28 05:22:45 -0800934 // Store the sequence number to be able to pick up the same sequence for
935 // the next StartSend(). This is needed for restarting device, otherwise
936 // it might cause libSRTP to complain about packets being replayed.
937 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
938 // CL is landed. See issue
939 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
940 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
941
942 // Reset sending SSRC and sequence number and triggers direct transmission
943 // of RTCP BYE
944 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700945 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -0800946 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100947 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000948}
949
ossu1ffbd6c2017-04-06 12:05:04 -0700950bool Channel::SetEncoder(int payload_type,
951 std::unique_ptr<AudioEncoder> encoder) {
952 RTC_DCHECK_GE(payload_type, 0);
953 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -0700954 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
955 // one for for us to keep track of sample rate and number of channels, etc.
956
957 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
958 // as well as some other things, so we collect this info and send it along.
959 CodecInst rtp_codec;
960 rtp_codec.pltype = payload_type;
961 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
962 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700963 // Seems unclear if it should be clock rate or sample rate. CodecInst
964 // supposedly carries the sample rate, but only clock rate seems sensible to
965 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -0700966 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
967 rtp_codec.pacsize = rtc::CheckedDivExact(
968 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
969 100);
970 rtp_codec.channels = encoder->NumChannels();
971 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -0700972
ossu76d29f92017-06-09 07:30:13 -0700973 // For audio encoding we need, instead, the actual sample rate of the codec.
974 // The rest of the information should be the same.
975 CodecInst send_codec = rtp_codec;
976 send_codec.plfreq = encoder->SampleRateHz();
977 cached_send_codec_.emplace(send_codec);
978
979 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -0700980 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -0700981 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +0200982 LOG(LS_ERROR)
983 << "SetEncoder() failed to register codec to RTP/RTCP module";
ossu1ffbd6c2017-04-06 12:05:04 -0700984 return false;
985 }
986 }
987
988 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -0700989 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -0700990 return true;
991}
992
ossu20a4b3f2017-04-27 02:08:52 -0700993void Channel::ModifyEncoder(
994 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
995 audio_coding_->ModifyEncoder(modifier);
996}
997
kwiberg55b97fe2016-01-28 05:22:45 -0800998int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -0700999 if (cached_send_codec_) {
1000 codec = *cached_send_codec_;
1001 return 0;
1002 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001003 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1004 if (send_codec) {
1005 codec = *send_codec;
1006 return 0;
1007 }
1008 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001009 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001010}
1011
kwiberg55b97fe2016-01-28 05:22:45 -08001012int32_t Channel::GetRecCodec(CodecInst& codec) {
1013 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001014}
1015
kwiberg55b97fe2016-01-28 05:22:45 -08001016int32_t Channel::SetSendCodec(const CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001017 if (!codec_manager_.RegisterEncoder(codec) ||
1018 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001019 LOG(LS_ERROR) << "SetSendCodec() failed to register codec to ACM";
kwiberg55b97fe2016-01-28 05:22:45 -08001020 return -1;
1021 }
1022
1023 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1024 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1025 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001026 LOG(LS_ERROR)
1027 << "SetSendCodec() failed to register codec to RTP/RTCP module";
kwiberg55b97fe2016-01-28 05:22:45 -08001028 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001029 }
kwiberg55b97fe2016-01-28 05:22:45 -08001030 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001031
ossu76d29f92017-06-09 07:30:13 -07001032 cached_send_codec_.reset();
1033
kwiberg55b97fe2016-01-28 05:22:45 -08001034 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001035}
1036
minyue78b4d562016-11-30 04:47:39 -08001037void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
minyue7e304322016-10-12 05:00:55 -07001038 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001039 if (*encoder) {
1040 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001041 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001042 }
1043 });
michaelt566d8202017-01-12 10:17:38 -08001044 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001045}
1046
elad.alond12a8e12017-03-23 11:04:48 -07001047void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1048 if (!use_twcc_plr_for_ana_)
1049 return;
minyue7e304322016-10-12 05:00:55 -07001050 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001051 if (*encoder) {
1052 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1053 }
1054 });
1055}
1056
elad.alondadb4dc2017-03-23 15:29:50 -07001057void Channel::OnRecoverableUplinkPacketLossRate(
1058 float recoverable_packet_loss_rate) {
1059 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1060 if (*encoder) {
1061 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1062 recoverable_packet_loss_rate);
1063 }
1064 });
1065}
1066
elad.alond12a8e12017-03-23 11:04:48 -07001067void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1068 if (use_twcc_plr_for_ana_)
1069 return;
1070 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1071 if (*encoder) {
1072 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1073 }
minyue7e304322016-10-12 05:00:55 -07001074 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001075}
1076
kwiberg1c07c702017-03-27 07:15:49 -07001077void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1078 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1079 audio_coding_->SetReceiveCodecs(codecs);
1080}
1081
minyue7e304322016-10-12 05:00:55 -07001082bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1083 bool success = false;
1084 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1085 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001086 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1087 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001088 }
1089 });
1090 return success;
1091}
1092
1093void Channel::DisableAudioNetworkAdaptor() {
1094 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1095 if (*encoder)
1096 (*encoder)->DisableAudioNetworkAdaptor();
1097 });
1098}
1099
1100void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1101 int max_frame_length_ms) {
1102 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1103 if (*encoder) {
1104 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1105 max_frame_length_ms);
1106 }
1107 });
1108}
1109
solenberg1c239d42017-09-29 06:00:28 -07001110void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001111 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001112 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +00001113}
1114
nisse657bab22017-02-21 06:28:10 -08001115void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
nisse657bab22017-02-21 06:28:10 -08001116 RTPHeader header;
1117 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -07001118
1119 // Store playout timestamp for the received RTP packet
1120 UpdatePlayoutTimestamp(false);
1121
1122 header.payload_type_frequency =
1123 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1124 if (header.payload_type_frequency >= 0) {
1125 bool in_order = IsPacketInOrder(header);
1126 rtp_receive_statistics_->IncomingPacket(
1127 header, packet.size(), IsPacketRetransmitted(header, in_order));
1128 rtp_payload_registry_->SetIncomingPayloadType(header);
1129
1130 ReceivePacket(packet.data(), packet.size(), header, in_order);
1131 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001132}
1133
1134bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001135 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001136 const RTPHeader& header,
1137 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001138 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001139 assert(packet_length >= header.headerLength);
1140 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001141 const auto pl =
1142 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1143 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001144 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001145 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001146 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Karl Wiberg73b60b82017-09-21 15:00:58 +02001147 pl->typeSpecific, in_order);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001148}
1149
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001150bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1151 StreamStatistician* statistician =
1152 rtp_receive_statistics_->GetStatistician(header.ssrc);
1153 if (!statistician)
1154 return false;
1155 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001156}
1157
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001158bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1159 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001160 StreamStatistician* statistician =
1161 rtp_receive_statistics_->GetStatistician(header.ssrc);
1162 if (!statistician)
1163 return false;
1164 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001165 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001166 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001167 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001168}
1169
mflodman3d7db262016-04-29 00:57:13 -07001170int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001171 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001172 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001173
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001174 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001175 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001176
Minyue2013aec2015-05-13 14:14:42 +02001177 int64_t rtt = GetRTT(true);
1178 if (rtt == 0) {
1179 // Waiting for valid RTT.
1180 return 0;
1181 }
Erik Språng737336d2016-07-29 12:59:36 +02001182
1183 int64_t nack_window_ms = rtt;
1184 if (nack_window_ms < kMinRetransmissionWindowMs) {
1185 nack_window_ms = kMinRetransmissionWindowMs;
1186 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1187 nack_window_ms = kMaxRetransmissionWindowMs;
1188 }
1189 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1190
minyue7e304322016-10-12 05:00:55 -07001191 // Invoke audio encoders OnReceivedRtt().
1192 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1193 if (*encoder)
1194 (*encoder)->OnReceivedRtt(rtt);
1195 });
1196
Minyue2013aec2015-05-13 14:14:42 +02001197 uint32_t ntp_secs = 0;
1198 uint32_t ntp_frac = 0;
1199 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001200 if (0 !=
1201 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1202 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001203 // Waiting for RTCP.
1204 return 0;
1205 }
1206
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001207 {
tommi31fc21f2016-01-21 10:37:37 -08001208 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001209 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001210 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001211 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001212}
1213
solenberg8d73f8c2017-03-08 01:52:20 -08001214int Channel::GetSpeechOutputLevel() const {
1215 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001216}
1217
solenberg8d73f8c2017-03-08 01:52:20 -08001218int Channel::GetSpeechOutputLevelFullRange() const {
1219 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001220}
1221
zsteine76bd3a2017-07-14 12:17:49 -07001222double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001223 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001224}
1225
1226double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001227 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001228}
1229
solenberg8d73f8c2017-03-08 01:52:20 -08001230void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001231 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001232 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001233}
1234
solenberg1c2af8e2016-03-24 10:36:00 -07001235bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001236 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001237 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001238}
1239
solenberg8d73f8c2017-03-08 01:52:20 -08001240void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001241 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001242 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001243}
1244
solenberg8842c3e2016-03-11 03:06:41 -08001245int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
solenberg8842c3e2016-03-11 03:06:41 -08001246 RTC_DCHECK_LE(0, event);
1247 RTC_DCHECK_GE(255, event);
1248 RTC_DCHECK_LE(0, duration_ms);
1249 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001250 if (!Sending()) {
1251 return -1;
1252 }
solenberg8842c3e2016-03-11 03:06:41 -08001253 if (_rtpRtcpModule->SendTelephoneEventOutband(
1254 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001255 LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001256 return -1;
1257 }
1258 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001259}
1260
solenbergffbbcac2016-11-17 05:25:37 -08001261int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1262 int payload_frequency) {
solenberg31642aa2016-03-14 08:00:37 -07001263 RTC_DCHECK_LE(0, payload_type);
1264 RTC_DCHECK_GE(127, payload_type);
1265 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001266 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001267 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001268 memcpy(codec.plname, "telephone-event", 16);
1269 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1270 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1271 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001272 LOG(LS_ERROR) << "SetSendTelephoneEventPayloadType() failed to register "
1273 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001274 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001275 }
kwiberg55b97fe2016-01-28 05:22:45 -08001276 }
kwiberg55b97fe2016-01-28 05:22:45 -08001277 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001278}
1279
kwiberg55b97fe2016-01-28 05:22:45 -08001280int Channel::SetLocalSSRC(unsigned int ssrc) {
kwiberg55b97fe2016-01-28 05:22:45 -08001281 if (channel_state_.Get().sending) {
solenberg1c239d42017-09-29 06:00:28 -07001282 LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001283 return -1;
1284 }
1285 _rtpRtcpModule->SetSSRC(ssrc);
1286 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001287}
1288
kwiberg55b97fe2016-01-28 05:22:45 -08001289int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1290 ssrc = rtp_receiver_->SSRC();
1291 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001292}
1293
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001294int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001295 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001296 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001297}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001298
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001299int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1300 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001301 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1302 if (enable &&
1303 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1304 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001305 return -1;
1306 }
1307 return 0;
1308}
1309
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001310void Channel::EnableSendTransportSequenceNumber(int id) {
1311 int ret =
1312 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1313 RTC_DCHECK_EQ(0, ret);
1314}
1315
stefan3313ec92016-01-21 06:32:43 -08001316void Channel::EnableReceiveTransportSequenceNumber(int id) {
1317 rtp_header_parser_->DeregisterRtpHeaderExtension(
1318 kRtpExtensionTransportSequenceNumber);
1319 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1320 kRtpExtensionTransportSequenceNumber, id);
1321 RTC_DCHECK(ret);
1322}
1323
stefanbba9dec2016-02-01 04:39:55 -08001324void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001325 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001326 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001327 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1328 TransportFeedbackObserver* transport_feedback_observer =
1329 transport->transport_feedback_observer();
1330 PacketRouter* packet_router = transport->packet_router();
1331
stefanbba9dec2016-02-01 04:39:55 -08001332 RTC_DCHECK(rtp_packet_sender);
1333 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001334 RTC_DCHECK(packet_router);
1335 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001336 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001337 feedback_observer_proxy_->SetTransportFeedbackObserver(
1338 transport_feedback_observer);
1339 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1340 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1341 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001342 constexpr bool remb_candidate = false;
1343 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001344 packet_router_ = packet_router;
1345}
1346
stefanbba9dec2016-02-01 04:39:55 -08001347void Channel::RegisterReceiverCongestionControlObjects(
1348 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001349 RTC_DCHECK(packet_router);
1350 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001351 constexpr bool remb_candidate = false;
1352 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001353 packet_router_ = packet_router;
1354}
1355
nissefdbfdc92017-03-31 05:44:52 -07001356void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001357 RTC_DCHECK(packet_router_);
1358 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001359 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001360 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1361 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001362 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001363 packet_router_ = nullptr;
1364 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1365}
1366
nissefdbfdc92017-03-31 05:44:52 -07001367void Channel::ResetReceiverCongestionControlObjects() {
1368 RTC_DCHECK(packet_router_);
1369 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1370 packet_router_ = nullptr;
1371}
1372
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001373void Channel::SetRTCPStatus(bool enable) {
pbosda903ea2015-10-02 02:36:56 -07001374 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001375}
1376
kwiberg55b97fe2016-01-28 05:22:45 -08001377int Channel::SetRTCP_CNAME(const char cName[256]) {
kwiberg55b97fe2016-01-28 05:22:45 -08001378 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001379 LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001380 return -1;
1381 }
1382 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001383}
1384
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001385int Channel::GetRemoteRTCPReportBlocks(
1386 std::vector<ReportBlock>* report_blocks) {
1387 if (report_blocks == NULL) {
solenberg1c239d42017-09-29 06:00:28 -07001388 LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001389 return -1;
1390 }
1391
1392 // Get the report blocks from the latest received RTCP Sender or Receiver
1393 // Report. Each element in the vector contains the sender's SSRC and a
1394 // report block according to RFC 3550.
1395 std::vector<RTCPReportBlock> rtcp_report_blocks;
1396 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001397 return -1;
1398 }
1399
1400 if (rtcp_report_blocks.empty())
1401 return 0;
1402
1403 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1404 for (; it != rtcp_report_blocks.end(); ++it) {
1405 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001406 report_block.sender_SSRC = it->sender_ssrc;
1407 report_block.source_SSRC = it->source_ssrc;
1408 report_block.fraction_lost = it->fraction_lost;
1409 report_block.cumulative_num_packets_lost = it->packets_lost;
1410 report_block.extended_highest_sequence_number =
1411 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001412 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001413 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1414 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001415 report_blocks->push_back(report_block);
1416 }
1417 return 0;
1418}
1419
kwiberg55b97fe2016-01-28 05:22:45 -08001420int Channel::GetRTPStatistics(CallStatistics& stats) {
1421 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001422
kwiberg55b97fe2016-01-28 05:22:45 -08001423 // The jitter statistics is updated for each received RTP packet and is
1424 // based on received packets.
1425 RtcpStatistics statistics;
1426 StreamStatistician* statistician =
1427 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001428 if (statistician) {
1429 statistician->GetStatistics(&statistics,
1430 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001431 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001432
kwiberg55b97fe2016-01-28 05:22:45 -08001433 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001434 stats.cumulativeLost = statistics.packets_lost;
1435 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001436 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001437
kwiberg55b97fe2016-01-28 05:22:45 -08001438 // --- RTT
1439 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001440
kwiberg55b97fe2016-01-28 05:22:45 -08001441 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001442
kwiberg55b97fe2016-01-28 05:22:45 -08001443 size_t bytesSent(0);
1444 uint32_t packetsSent(0);
1445 size_t bytesReceived(0);
1446 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001447
kwiberg55b97fe2016-01-28 05:22:45 -08001448 if (statistician) {
1449 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1450 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001451
kwiberg55b97fe2016-01-28 05:22:45 -08001452 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001453 LOG(LS_WARNING) << "GetRTPStatistics() failed to retrieve RTP datacounters"
1454 << " => output will not be complete";
kwiberg55b97fe2016-01-28 05:22:45 -08001455 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001456
kwiberg55b97fe2016-01-28 05:22:45 -08001457 stats.bytesSent = bytesSent;
1458 stats.packetsSent = packetsSent;
1459 stats.bytesReceived = bytesReceived;
1460 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001461
kwiberg55b97fe2016-01-28 05:22:45 -08001462 // --- Timestamps
1463 {
1464 rtc::CritScope lock(&ts_stats_lock_);
1465 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1466 }
1467 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001468}
1469
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001470void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1471 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001472 // If pacing is enabled we always store packets.
1473 if (!pacing_enabled_)
1474 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001475 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001476 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001477 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001478 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001479 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001480}
1481
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001482// Called when we are missing one or more packets.
1483int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001484 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1485}
1486
henrikaec6fbd22017-03-31 05:43:36 -07001487void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001488 // Avoid posting any new tasks if sending was already stopped in StopSend().
1489 rtc::CritScope cs(&encoder_queue_lock_);
1490 if (!encoder_queue_is_active_) {
1491 return;
1492 }
henrikaec6fbd22017-03-31 05:43:36 -07001493 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1494 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1495 // either into pool of frames or into the task itself.
1496 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001497 // Profile time between when the audio frame is added to the task queue and
1498 // when the task is actually executed.
1499 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001500 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1501 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001502}
1503
henrikaec6fbd22017-03-31 05:43:36 -07001504void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1505 int sample_rate,
1506 size_t number_of_frames,
1507 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001508 // Avoid posting as new task if sending was already stopped in StopSend().
1509 rtc::CritScope cs(&encoder_queue_lock_);
1510 if (!encoder_queue_is_active_) {
1511 return;
1512 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001513 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001514 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001515 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
ossu950c1c92017-07-11 08:19:31 -07001516 // TODO(ossu): Investigate how this could happen. b/62909493
1517 if (result == 0) {
1518 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1519 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1520 } else {
1521 audio_frame->sample_rate_hz_ = sample_rate;
1522 audio_frame->num_channels_ = number_of_channels;
1523 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1524 RTC_NOTREACHED();
1525 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001526 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001527 sample_rate, &input_resampler_, audio_frame.get());
1528 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1529 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001530}
1531
henrikaec6fbd22017-03-31 05:43:36 -07001532void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1533 RTC_DCHECK_RUN_ON(encoder_queue_);
1534 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1535 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001536
henrika45802172017-09-28 09:39:34 +02001537 // Measure time between when the audio frame is added to the task queue and
1538 // when the task is actually executed. Goal is to keep track of unwanted
1539 // extra latency added by the task queue.
1540 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1541 audio_input->ElapsedProfileTimeMs());
1542
henrikaec6fbd22017-03-31 05:43:36 -07001543 bool is_muted = InputMute();
1544 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001545
kwiberg55b97fe2016-01-28 05:22:45 -08001546 if (_includeAudioLevelIndication) {
1547 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001548 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001549 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001550 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001551 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001552 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001553 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001554 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001555 }
kwiberg55b97fe2016-01-28 05:22:45 -08001556 }
solenberg1c2af8e2016-03-24 10:36:00 -07001557 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001558
henrikaec6fbd22017-03-31 05:43:36 -07001559 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001560
kwiberg55b97fe2016-01-28 05:22:45 -08001561 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001562 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001563 // This call will trigger AudioPacketizationCallback::SendData if encoding
1564 // is done and payload is ready for packetization and transmission.
1565 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001566 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1567 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1568 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001569 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001570
henrikaec6fbd22017-03-31 05:43:36 -07001571 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001572}
1573
solenberg7602aab2016-11-14 11:30:07 -08001574void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1575 RTC_DCHECK(!channel.channel() ||
1576 channel.channel()->ChannelId() != _channelId);
1577 rtc::CritScope lock(&assoc_send_channel_lock_);
1578 associate_send_channel_ = channel;
1579}
1580
Minyue2013aec2015-05-13 14:14:42 +02001581void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001582 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001583 Channel* channel = associate_send_channel_.channel();
1584 if (channel && channel->ChannelId() == channel_id) {
1585 // If this channel is associated with a send channel of the specified
1586 // Channel ID, disassociate with it.
1587 ChannelOwner ref(NULL);
1588 associate_send_channel_ = ref;
1589 }
1590}
1591
ivoc14d5dbe2016-07-04 07:06:55 -07001592void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1593 event_log_proxy_->SetEventLog(event_log);
1594}
1595
michaelt9332b7d2016-11-30 07:51:13 -08001596void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1597 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1598}
1599
nisse284542b2017-01-10 08:58:32 -08001600void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001601 size_t overhead_per_packet =
1602 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001603 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1604 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001605 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001606 }
1607 });
1608}
1609
1610void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001611 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001612 transport_overhead_per_packet_ = transport_overhead_per_packet;
1613 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001614}
1615
hbos3fd31fe2017-02-28 05:43:16 -08001616// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001617void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001618 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001619 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1620 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001621}
1622
kwiberg55b97fe2016-01-28 05:22:45 -08001623int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1624 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001625}
1626
wu@webrtc.org24301a62013-12-13 19:17:43 +00001627void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1628 audio_coding_->GetDecodingCallStatistics(stats);
1629}
1630
ivoce1198e02017-09-08 08:13:19 -07001631ANAStats Channel::GetANAStatistics() const {
1632 return audio_coding_->GetANAStats();
1633}
1634
solenberg358057b2015-11-27 10:46:42 -08001635uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001636 rtc::CritScope lock(&video_sync_lock_);
1637 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001638}
1639
kwiberg55b97fe2016-01-28 05:22:45 -08001640int Channel::SetMinimumPlayoutDelay(int delayMs) {
kwiberg55b97fe2016-01-28 05:22:45 -08001641 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1642 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
solenberg1c239d42017-09-29 06:00:28 -07001643 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001644 return -1;
1645 }
1646 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001647 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001648 return -1;
1649 }
1650 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001651}
1652
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001653int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001654 uint32_t playout_timestamp_rtp = 0;
1655 {
tommi31fc21f2016-01-21 10:37:37 -08001656 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001657 playout_timestamp_rtp = playout_timestamp_rtp_;
1658 }
kwiberg55b97fe2016-01-28 05:22:45 -08001659 if (playout_timestamp_rtp == 0) {
solenberg1c239d42017-09-29 06:00:28 -07001660 LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001661 return -1;
1662 }
deadbeef74375882015-08-13 12:09:10 -07001663 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001664 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001665}
1666
kwiberg55b97fe2016-01-28 05:22:45 -08001667int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1668 RtpReceiver** rtp_receiver) const {
1669 *rtpRtcpModule = _rtpRtcpModule.get();
1670 *rtp_receiver = rtp_receiver_.get();
1671 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001672}
1673
deadbeef74375882015-08-13 12:09:10 -07001674void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001675 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001676
henrik.lundin96bd5022016-04-06 04:13:56 -07001677 if (!jitter_buffer_playout_timestamp_) {
1678 // This can happen if this channel has not received any RTP packets. In
1679 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001680 return;
1681 }
1682
1683 uint16_t delay_ms = 0;
1684 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001685 LOG(LS_WARNING) << "Channel::UpdatePlayoutTimestamp() failed to read"
1686 << " playout delay from the ADM";
deadbeef74375882015-08-13 12:09:10 -07001687 return;
1688 }
1689
henrik.lundin96bd5022016-04-06 04:13:56 -07001690 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1691 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001692
1693 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001694 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001695
deadbeef74375882015-08-13 12:09:10 -07001696 {
tommi31fc21f2016-01-21 10:37:37 -08001697 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001698 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001699 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001700 }
1701 playout_delay_ms_ = delay_ms;
1702 }
1703}
1704
kwiberg55b97fe2016-01-28 05:22:45 -08001705void Channel::RegisterReceiveCodecsToRTPModule() {
kwiberg55b97fe2016-01-28 05:22:45 -08001706 CodecInst codec;
1707 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00001708
kwiberg55b97fe2016-01-28 05:22:45 -08001709 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1710 // Open up the RTP/RTCP receiver for all supported codecs
1711 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001712 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
Sam Zackrissonecc51e92017-10-02 14:32:33 +02001713 LOG(LS_WARNING) << "Channel::RegisterReceiveCodecsToRTPModule() unable"
1714 << " to register " << codec.plname << " (" << codec.pltype
1715 << "/" << codec.plfreq << "/" << codec.channels << "/"
1716 << codec.rate << ") to RTP/RTCP receiver";
niklase@google.com470e71d2011-07-07 08:21:25 +00001717 }
kwiberg55b97fe2016-01-28 05:22:45 -08001718 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001719}
1720
kwiberg55b97fe2016-01-28 05:22:45 -08001721int Channel::SetSendRtpHeaderExtension(bool enable,
1722 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001723 unsigned char id) {
1724 int error = 0;
1725 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1726 if (enable) {
1727 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1728 }
1729 return error;
1730}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001731
ossue280cde2016-10-12 11:04:10 -07001732int Channel::GetRtpTimestampRateHz() const {
1733 const auto format = audio_coding_->ReceiveFormat();
1734 // Default to the playout frequency if we've not gotten any packets yet.
1735 // TODO(ossu): Zero clockrate can only happen if we've added an external
1736 // decoder for a format we don't support internally. Remove once that way of
1737 // adding decoders is gone!
1738 return (format && format->clockrate_hz != 0)
1739 ? format->clockrate_hz
1740 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001741}
1742
Minyue2013aec2015-05-13 14:14:42 +02001743int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001744 RtcpMode method = _rtpRtcpModule->RTCP();
1745 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001746 return 0;
1747 }
1748 std::vector<RTCPReportBlock> report_blocks;
1749 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001750
1751 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001752 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001753 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001754 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001755 Channel* channel = associate_send_channel_.channel();
1756 // Tries to get RTT from an associated channel. This is important for
1757 // receive-only channels.
1758 if (channel) {
1759 // To prevent infinite recursion and deadlock, calling GetRTT of
1760 // associate channel should always use "false" for argument:
1761 // |allow_associate_channel|.
1762 rtt = channel->GetRTT(false);
1763 }
1764 }
1765 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001766 }
1767
1768 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1769 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1770 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001771 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001772 break;
1773 }
1774 if (it == report_blocks.end()) {
1775 // We have not received packets with SSRC matching the report blocks.
1776 // To calculate RTT we try with the SSRC of the first report block.
1777 // This is very important for send-only channels where we don't know
1778 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001779 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001780 }
Minyue2013aec2015-05-13 14:14:42 +02001781
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001782 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001783 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001784 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001785 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1786 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001787 return 0;
1788 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001789 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001790}
1791
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001792} // namespace voe
1793} // namespace webrtc