blob: 5fa7973b497f324bd94e0c85e6a45f65ece58ff6 [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>
Tommif888bb52015-12-12 01:37:01 +010014#include <utility>
Henrik Lundin64dad832015-05-11 12:44:23 +020015
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "api/array_view.h"
17#include "audio/utility/audio_frame_operations.h"
18#include "call/rtp_transport_controller_send_interface.h"
19#include "logging/rtc_event_log/rtc_event_log.h"
20#include "modules/audio_coding/codecs/audio_format_conversion.h"
21#include "modules/audio_device/include/audio_device.h"
22#include "modules/audio_processing/include/audio_processing.h"
23#include "modules/include/module_common_types.h"
24#include "modules/pacing/packet_router.h"
25#include "modules/rtp_rtcp/include/receive_statistics.h"
26#include "modules/rtp_rtcp/include/rtp_payload_registry.h"
27#include "modules/rtp_rtcp/include/rtp_receiver.h"
28#include "modules/rtp_rtcp/source/rtp_packet_received.h"
29#include "modules/rtp_rtcp/source/rtp_receiver_strategy.h"
30#include "modules/utility/include/process_thread.h"
31#include "rtc_base/checks.h"
32#include "rtc_base/criticalsection.h"
33#include "rtc_base/format_macros.h"
34#include "rtc_base/location.h"
35#include "rtc_base/logging.h"
36#include "rtc_base/rate_limiter.h"
37#include "rtc_base/task_queue.h"
38#include "rtc_base/thread_checker.h"
39#include "rtc_base/timeutils.h"
40#include "system_wrappers/include/field_trial.h"
henrika45802172017-09-28 09:39:34 +020041#include "system_wrappers/include/metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "system_wrappers/include/trace.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000044
andrew@webrtc.org50419b02012-11-14 19:07:54 +000045namespace webrtc {
46namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000047
kwibergc8d071e2016-04-06 12:22:38 -070048namespace {
49
zsteine76bd3a2017-07-14 12:17:49 -070050constexpr double kAudioSampleDurationSeconds = 0.01;
Erik Språng737336d2016-07-29 12:59:36 +020051constexpr int64_t kMaxRetransmissionWindowMs = 1000;
52constexpr int64_t kMinRetransmissionWindowMs = 30;
53
kwibergc8d071e2016-04-06 12:22:38 -070054} // namespace
55
solenberg8842c3e2016-03-11 03:06:41 -080056const int kTelephoneEventAttenuationdB = 10;
57
ivoc14d5dbe2016-07-04 07:06:55 -070058class RtcEventLogProxy final : public webrtc::RtcEventLog {
59 public:
60 RtcEventLogProxy() : event_log_(nullptr) {}
61
62 bool StartLogging(const std::string& file_name,
63 int64_t max_size_bytes) override {
64 RTC_NOTREACHED();
65 return false;
66 }
67
68 bool StartLogging(rtc::PlatformFile log_file,
69 int64_t max_size_bytes) override {
70 RTC_NOTREACHED();
71 return false;
72 }
73
74 void StopLogging() override { RTC_NOTREACHED(); }
75
76 void LogVideoReceiveStreamConfig(
perkj09e71da2017-05-22 03:26:49 -070077 const webrtc::rtclog::StreamConfig&) override {
78 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070079 }
80
perkjc0876aa2017-05-22 04:08:28 -070081 void LogVideoSendStreamConfig(const webrtc::rtclog::StreamConfig&) override {
82 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070083 }
84
ivoce0928d82016-10-10 05:12:51 -070085 void LogAudioReceiveStreamConfig(
perkjac8f52d2017-05-22 09:36:28 -070086 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070087 rtc::CritScope lock(&crit_);
88 if (event_log_) {
89 event_log_->LogAudioReceiveStreamConfig(config);
90 }
91 }
92
93 void LogAudioSendStreamConfig(
perkjf4726992017-05-22 10:12:26 -070094 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070095 rtc::CritScope lock(&crit_);
96 if (event_log_) {
97 event_log_->LogAudioSendStreamConfig(config);
98 }
99 }
100
ivoc14d5dbe2016-07-04 07:06:55 -0700101 void LogRtpHeader(webrtc::PacketDirection direction,
ivoc14d5dbe2016-07-04 07:06:55 -0700102 const uint8_t* header,
103 size_t packet_length) override {
perkj77cd58e2017-05-30 03:52:10 -0700104 LogRtpHeader(direction, header, packet_length, PacedPacketInfo::kNotAProbe);
philipel32d00102017-02-27 02:18:46 -0800105 }
106
107 void LogRtpHeader(webrtc::PacketDirection direction,
philipel32d00102017-02-27 02:18:46 -0800108 const uint8_t* header,
109 size_t packet_length,
110 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700111 rtc::CritScope lock(&crit_);
112 if (event_log_) {
perkj77cd58e2017-05-30 03:52:10 -0700113 event_log_->LogRtpHeader(direction, header, packet_length,
philipel32d00102017-02-27 02:18:46 -0800114 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700115 }
116 }
117
118 void LogRtcpPacket(webrtc::PacketDirection direction,
ivoc14d5dbe2016-07-04 07:06:55 -0700119 const uint8_t* packet,
120 size_t length) override {
121 rtc::CritScope lock(&crit_);
122 if (event_log_) {
perkj77cd58e2017-05-30 03:52:10 -0700123 event_log_->LogRtcpPacket(direction, packet, length);
ivoc14d5dbe2016-07-04 07:06:55 -0700124 }
125 }
126
127 void LogAudioPlayout(uint32_t ssrc) override {
128 rtc::CritScope lock(&crit_);
129 if (event_log_) {
130 event_log_->LogAudioPlayout(ssrc);
131 }
132 }
133
terelius424e6cf2017-02-20 05:14:41 -0800134 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700135 uint8_t fraction_loss,
136 int32_t total_packets) override {
137 rtc::CritScope lock(&crit_);
138 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800139 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
140 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700141 }
142 }
143
terelius424e6cf2017-02-20 05:14:41 -0800144 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800145 BandwidthUsage detector_state) override {
146 rtc::CritScope lock(&crit_);
147 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800148 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800149 }
150 }
151
minyue4b7c9522017-01-24 04:54:59 -0800152 void LogAudioNetworkAdaptation(
michaeltcde46b72017-04-06 05:59:10 -0700153 const AudioEncoderRuntimeConfig& config) override {
minyue4b7c9522017-01-24 04:54:59 -0800154 rtc::CritScope lock(&crit_);
155 if (event_log_) {
156 event_log_->LogAudioNetworkAdaptation(config);
157 }
158 }
159
philipel32d00102017-02-27 02:18:46 -0800160 void LogProbeClusterCreated(int id,
161 int bitrate_bps,
162 int min_probes,
163 int min_bytes) override {
164 rtc::CritScope lock(&crit_);
165 if (event_log_) {
166 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
167 min_bytes);
168 }
169 };
170
171 void LogProbeResultSuccess(int id, int bitrate_bps) override {
172 rtc::CritScope lock(&crit_);
173 if (event_log_) {
174 event_log_->LogProbeResultSuccess(id, bitrate_bps);
175 }
176 };
177
178 void LogProbeResultFailure(int id,
179 ProbeFailureReason failure_reason) override {
180 rtc::CritScope lock(&crit_);
181 if (event_log_) {
182 event_log_->LogProbeResultFailure(id, failure_reason);
183 }
184 };
185
ivoc14d5dbe2016-07-04 07:06:55 -0700186 void SetEventLog(RtcEventLog* event_log) {
187 rtc::CritScope lock(&crit_);
188 event_log_ = event_log;
189 }
190
191 private:
192 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700193 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -0700194 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
195};
196
michaelt9332b7d2016-11-30 07:51:13 -0800197class RtcpRttStatsProxy final : public RtcpRttStats {
198 public:
199 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
200
201 void OnRttUpdate(int64_t rtt) override {
202 rtc::CritScope lock(&crit_);
203 if (rtcp_rtt_stats_)
204 rtcp_rtt_stats_->OnRttUpdate(rtt);
205 }
206
207 int64_t LastProcessedRtt() const override {
208 rtc::CritScope lock(&crit_);
209 if (!rtcp_rtt_stats_)
210 return 0;
211 return rtcp_rtt_stats_->LastProcessedRtt();
212 }
213
214 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
215 rtc::CritScope lock(&crit_);
216 rtcp_rtt_stats_ = rtcp_rtt_stats;
217 }
218
219 private:
220 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700221 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800222 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
223};
224
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100225class TransportFeedbackProxy : public TransportFeedbackObserver {
226 public:
227 TransportFeedbackProxy() : feedback_observer_(nullptr) {
228 pacer_thread_.DetachFromThread();
229 network_thread_.DetachFromThread();
230 }
231
232 void SetTransportFeedbackObserver(
233 TransportFeedbackObserver* feedback_observer) {
234 RTC_DCHECK(thread_checker_.CalledOnValidThread());
235 rtc::CritScope lock(&crit_);
236 feedback_observer_ = feedback_observer;
237 }
238
239 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700240 void AddPacket(uint32_t ssrc,
241 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100242 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800243 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100244 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
245 rtc::CritScope lock(&crit_);
246 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700247 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100248 }
philipel8aadd502017-02-23 02:56:13 -0800249
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100250 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
251 RTC_DCHECK(network_thread_.CalledOnValidThread());
252 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700253 if (feedback_observer_)
254 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200255 }
elad.alonf9490002017-03-06 05:32:21 -0800256 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200257 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800258 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100259 }
260
261 private:
262 rtc::CriticalSection crit_;
263 rtc::ThreadChecker thread_checker_;
264 rtc::ThreadChecker pacer_thread_;
265 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700266 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100267};
268
269class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
270 public:
271 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
272 pacer_thread_.DetachFromThread();
273 }
274
275 void SetSequenceNumberAllocator(
276 TransportSequenceNumberAllocator* seq_num_allocator) {
277 RTC_DCHECK(thread_checker_.CalledOnValidThread());
278 rtc::CritScope lock(&crit_);
279 seq_num_allocator_ = seq_num_allocator;
280 }
281
282 // Implements TransportSequenceNumberAllocator.
283 uint16_t AllocateSequenceNumber() override {
284 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
285 rtc::CritScope lock(&crit_);
286 if (!seq_num_allocator_)
287 return 0;
288 return seq_num_allocator_->AllocateSequenceNumber();
289 }
290
291 private:
292 rtc::CriticalSection crit_;
293 rtc::ThreadChecker thread_checker_;
294 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700295 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100296};
297
298class RtpPacketSenderProxy : public RtpPacketSender {
299 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800300 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100301
302 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
303 RTC_DCHECK(thread_checker_.CalledOnValidThread());
304 rtc::CritScope lock(&crit_);
305 rtp_packet_sender_ = rtp_packet_sender;
306 }
307
308 // Implements RtpPacketSender.
309 void InsertPacket(Priority priority,
310 uint32_t ssrc,
311 uint16_t sequence_number,
312 int64_t capture_time_ms,
313 size_t bytes,
314 bool retransmission) override {
315 rtc::CritScope lock(&crit_);
316 if (rtp_packet_sender_) {
317 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
318 capture_time_ms, bytes, retransmission);
319 }
320 }
321
322 private:
323 rtc::ThreadChecker thread_checker_;
324 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700325 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100326};
327
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000328class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000329 public:
stefan7de8d642017-02-07 07:14:08 -0800330 explicit VoERtcpObserver(Channel* owner)
331 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000332 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000333
stefan7de8d642017-02-07 07:14:08 -0800334 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
335 rtc::CritScope lock(&crit_);
336 bandwidth_observer_ = bandwidth_observer;
337 }
338
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000339 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800340 rtc::CritScope lock(&crit_);
341 if (bandwidth_observer_) {
342 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
343 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000344 }
345
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000346 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
347 int64_t rtt,
348 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800349 {
350 rtc::CritScope lock(&crit_);
351 if (bandwidth_observer_) {
352 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
353 now_ms);
354 }
355 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000356 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
357 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
358 // report for VoiceEngine?
359 if (report_blocks.empty())
360 return;
361
362 int fraction_lost_aggregate = 0;
363 int total_number_of_packets = 0;
364
365 // If receiving multiple report blocks, calculate the weighted average based
366 // on the number of packets a report refers to.
367 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
368 block_it != report_blocks.end(); ++block_it) {
369 // Find the previous extended high sequence number for this remote SSRC,
370 // to calculate the number of RTP packets this report refers to. Ignore if
371 // we haven't seen this SSRC before.
372 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700373 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000374 int number_of_packets = 0;
375 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700376 number_of_packets =
377 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000378 }
srte3e69e5c2017-08-09 06:13:45 -0700379 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000380 total_number_of_packets += number_of_packets;
381
srte3e69e5c2017-08-09 06:13:45 -0700382 extended_max_sequence_number_[block_it->source_ssrc] =
383 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000384 }
385 int weighted_fraction_lost = 0;
386 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800387 weighted_fraction_lost =
388 (fraction_lost_aggregate + total_number_of_packets / 2) /
389 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000390 }
elad.alond12a8e12017-03-23 11:04:48 -0700391 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000392 }
393
394 private:
395 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000396 // Maps remote side ssrc to extended highest sequence number received.
397 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800398 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700399 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000400};
401
henrikaec6fbd22017-03-31 05:43:36 -0700402class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
403 public:
404 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
405 Channel* channel)
406 : audio_frame_(std::move(audio_frame)), channel_(channel) {
407 RTC_DCHECK(channel_);
408 }
409
410 private:
411 bool Run() override {
412 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
413 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
414 return true;
415 }
416
417 std::unique_ptr<AudioFrame> audio_frame_;
418 Channel* const channel_;
419};
420
kwiberg55b97fe2016-01-28 05:22:45 -0800421int32_t Channel::SendData(FrameType frameType,
422 uint8_t payloadType,
423 uint32_t timeStamp,
424 const uint8_t* payloadData,
425 size_t payloadSize,
426 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700427 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800428 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
429 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
430 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
431 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000432
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 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
461 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000462
kwiberg55b97fe2016-01-28 05:22:45 -0800463 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000464
kwiberg55b97fe2016-01-28 05:22:45 -0800465 if (_transportPtr == NULL) {
466 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
467 "Channel::SendPacket() failed to send RTP packet due to"
468 " invalid transport object");
469 return false;
470 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000471
kwiberg55b97fe2016-01-28 05:22:45 -0800472 uint8_t* bufferToSendPtr = (uint8_t*)data;
473 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000474
kwiberg55b97fe2016-01-28 05:22:45 -0800475 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
solenberg1c239d42017-09-29 06:00:28 -0700476 LOG(LS_ERROR) << "Channel::SendPacket() RTP transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800477 return false;
478 }
479 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000480}
481
kwiberg55b97fe2016-01-28 05:22:45 -0800482bool Channel::SendRtcp(const uint8_t* data, size_t len) {
483 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
484 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000485
kwiberg55b97fe2016-01-28 05:22:45 -0800486 rtc::CritScope cs(&_callbackCritSect);
487 if (_transportPtr == NULL) {
488 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
489 "Channel::SendRtcp() failed to send RTCP packet"
490 " due to invalid transport object");
491 return false;
492 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000493
kwiberg55b97fe2016-01-28 05:22:45 -0800494 uint8_t* bufferToSendPtr = (uint8_t*)data;
495 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000496
kwiberg55b97fe2016-01-28 05:22:45 -0800497 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
498 if (n < 0) {
solenberg1c239d42017-09-29 06:00:28 -0700499 LOG(LS_ERROR) << "Channel::SendRtcp() transmission failed";
kwiberg55b97fe2016-01-28 05:22:45 -0800500 return false;
501 }
502 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000503}
504
kwiberg55b97fe2016-01-28 05:22:45 -0800505void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
506 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
507 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000508
kwiberg55b97fe2016-01-28 05:22:45 -0800509 // Update ssrc so that NTP for AV sync can be updated.
510 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000511}
512
Peter Boströmac547a62015-09-17 23:03:57 +0200513void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
514 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
515 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
516 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000517}
518
Peter Boströmac547a62015-09-17 23:03:57 +0200519int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000520 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000521 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000522 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800523 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200524 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800525 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
526 "Channel::OnInitializeDecoder(payloadType=%d, "
527 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
528 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000529
kwiberg55b97fe2016-01-28 05:22:45 -0800530 CodecInst receiveCodec = {0};
531 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000532
kwiberg55b97fe2016-01-28 05:22:45 -0800533 receiveCodec.pltype = payloadType;
534 receiveCodec.plfreq = frequency;
535 receiveCodec.channels = channels;
536 receiveCodec.rate = rate;
537 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000538
kwiberg55b97fe2016-01-28 05:22:45 -0800539 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
540 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000541
kwiberg55b97fe2016-01-28 05:22:45 -0800542 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700543 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
544 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800545 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
546 "Channel::OnInitializeDecoder() invalid codec ("
547 "pt=%d, name=%s) received - 1",
548 payloadType, payloadName);
kwiberg55b97fe2016-01-28 05:22:45 -0800549 return -1;
550 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000551
kwiberg55b97fe2016-01-28 05:22:45 -0800552 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000553}
554
kwiberg55b97fe2016-01-28 05:22:45 -0800555int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
556 size_t payloadSize,
557 const WebRtcRTPHeader* rtpHeader) {
558 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
559 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
560 ","
561 " payloadType=%u, audioChannel=%" PRIuS ")",
562 payloadSize, rtpHeader->header.payloadType,
563 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000564
kwiberg55b97fe2016-01-28 05:22:45 -0800565 if (!channel_state_.Get().playing) {
566 // Avoid inserting into NetEQ when we are not playing. Count the
567 // packet as discarded.
568 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
569 "received packet is discarded since playing is not"
570 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000571 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800572 }
573
574 // Push the incoming payload (parsed and ready for decoding) into the ACM
575 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
576 0) {
solenberg1c239d42017-09-29 06:00:28 -0700577 LOG(LS_ERROR) <<
578 "Channel::OnReceivedPayloadData() unable to push data to the ACM";
kwiberg55b97fe2016-01-28 05:22:45 -0800579 return -1;
580 }
581
kwiberg55b97fe2016-01-28 05:22:45 -0800582 int64_t round_trip_time = 0;
583 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
584 NULL);
585
586 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
587 if (!nack_list.empty()) {
588 // Can't use nack_list.data() since it's not supported by all
589 // compilers.
590 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
591 }
592 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000593}
594
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000595bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000596 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000597 RTPHeader header;
598 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
599 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
600 "IncomingPacket invalid RTP header");
601 return false;
602 }
603 header.payload_type_frequency =
604 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
605 if (header.payload_type_frequency < 0)
606 return false;
607 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
608}
609
solenberg2397b9a2017-09-22 06:48:10 -0700610AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
611 int sample_rate_hz,
612 AudioFrame* audio_frame) {
613 audio_frame->sample_rate_hz_ = sample_rate_hz;
614
ivoc14d5dbe2016-07-04 07:06:55 -0700615 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800616 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700617 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800618 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700619 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700620 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700621 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800622 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
623 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
624 // In all likelihood, the audio in this frame is garbage. We return an
625 // error so that the audio mixer module doesn't add it to the mix. As
626 // a result, it won't be played out and the actions skipped here are
627 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700628 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800629 }
henrik.lundina89ab962016-05-18 08:52:45 -0700630
631 if (muted) {
632 // TODO(henrik.lundin): We should be able to do better than this. But we
633 // will have to go through all the cases below where the audio samples may
634 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700635 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700636 }
kwiberg55b97fe2016-01-28 05:22:45 -0800637
kwiberg55b97fe2016-01-28 05:22:45 -0800638 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700639 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800640
kwiberg55b97fe2016-01-28 05:22:45 -0800641 {
642 // Pass the audio buffers to an optional sink callback, before applying
643 // scaling/panning, as that applies to the mix operation.
644 // External recipients of the audio (e.g. via AudioTrack), will do their
645 // own mixing/dynamic processing.
646 rtc::CritScope cs(&_callbackCritSect);
647 if (audio_sink_) {
648 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700649 audio_frame->data(), audio_frame->samples_per_channel_,
650 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
651 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800652 audio_sink_->OnData(data);
653 }
654 }
655
656 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800657 {
658 rtc::CritScope cs(&volume_settings_critsect_);
659 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800660 }
661
662 // Output volume scaling
663 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800664 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700665 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800666 }
667
kwiberg55b97fe2016-01-28 05:22:45 -0800668 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700669 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700670 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700671 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700672 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800673
solenberg2397b9a2017-09-22 06:48:10 -0700674 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800675 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700676 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800677 }
678
679 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700680 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800681
682 // Compute elapsed time.
683 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700684 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
685 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800686 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700687 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800688
niklase@google.com470e71d2011-07-07 08:21:25 +0000689 {
kwiberg55b97fe2016-01-28 05:22:45 -0800690 rtc::CritScope lock(&ts_stats_lock_);
691 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700692 audio_frame->ntp_time_ms_ =
693 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800694 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700695 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800696 // Compute |capture_start_ntp_time_ms_| so that
697 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
698 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700699 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000700 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000701 }
kwiberg55b97fe2016-01-28 05:22:45 -0800702 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000703
solenberg2397b9a2017-09-22 06:48:10 -0700704 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
705 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000706}
707
solenberg2397b9a2017-09-22 06:48:10 -0700708int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800709 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700710 return std::max(audio_coding_->ReceiveFrequency(),
711 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000712}
713
henrikaec6fbd22017-03-31 05:43:36 -0700714int32_t Channel::CreateChannel(Channel*& channel,
715 int32_t channelId,
716 uint32_t instanceId,
717 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800718 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
719 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
720 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000721
solenberg88499ec2016-09-07 07:34:41 -0700722 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800723 if (channel == NULL) {
724 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
725 "Channel::CreateChannel() unable to allocate memory for"
726 " channel");
727 return -1;
728 }
729 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000730}
731
pbos@webrtc.org92135212013-05-14 08:31:39 +0000732Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000733 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700734 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800735 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100736 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700737 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800738 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100739 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800740 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100741 rtp_receive_statistics_(
742 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
743 rtp_receiver_(
744 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100745 this,
746 this,
747 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700748 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100749 _outputAudioLevel(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100750 _timeStamp(0), // This is just an offset, RTP module will add it's own
751 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100752 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100753 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100754 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100755 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100756 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
757 capture_start_rtp_time_stamp_(-1),
758 capture_start_ntp_time_ms_(-1),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100759 _moduleProcessThreadPtr(NULL),
760 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100761 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700762 input_mute_(false),
763 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100764 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100765 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800766 transport_overhead_per_packet_(0),
767 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100768 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100769 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100770 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700771 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800772 feedback_observer_proxy_(new TransportFeedbackProxy()),
773 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700774 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200775 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
776 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700777 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700778 use_twcc_plr_for_ana_(
779 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800780 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
781 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700782 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700783 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800784 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200785
kwiberg55b97fe2016-01-28 05:22:45 -0800786 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000787
kwiberg55b97fe2016-01-28 05:22:45 -0800788 RtpRtcp::Configuration configuration;
789 configuration.audio = true;
790 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800791 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800792 configuration.receive_statistics = rtp_receive_statistics_.get();
793 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800794 if (pacing_enabled_) {
795 configuration.paced_sender = rtp_packet_sender_proxy_.get();
796 configuration.transport_sequence_number_allocator =
797 seq_num_allocator_proxy_.get();
798 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
799 }
ivoc14d5dbe2016-07-04 07:06:55 -0700800 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800801 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200802 configuration.retransmission_rate_limiter =
803 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000804
kwiberg55b97fe2016-01-28 05:22:45 -0800805 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100806 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000807}
808
kwiberg55b97fe2016-01-28 05:22:45 -0800809Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700810 RTC_DCHECK(!channel_state_.Get().sending);
811 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000812}
813
kwiberg55b97fe2016-01-28 05:22:45 -0800814int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700815 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800816 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
817 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000818
kwiberg55b97fe2016-01-28 05:22:45 -0800819 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000820
kwiberg55b97fe2016-01-28 05:22:45 -0800821 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000822
solenberg1c239d42017-09-29 06:00:28 -0700823 if (_moduleProcessThreadPtr == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -0800824 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
825 "Channel::Init() must call SetEngineInformation() first");
826 return -1;
827 }
828
829 // --- Add modules to process thread (for periodic schedulation)
830
tommidea489f2017-03-03 03:20:24 -0800831 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800832
833 // --- ACM initialization
834
835 if (audio_coding_->InitializeReceiver() == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700836 LOG(LS_ERROR) << "Channel::Init() unable to initialize the ACM - 1";
kwiberg55b97fe2016-01-28 05:22:45 -0800837 return -1;
838 }
839
840 // --- RTP/RTCP module initialization
841
842 // Ensure that RTCP is enabled by default for the created channel.
843 // Note that, the module will keep generating RTCP until it is explicitly
844 // disabled by the user.
845 // After StopListen (when no sockets exists), RTCP packets will no longer
846 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700847 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800848 // RTCP is enabled by default.
849 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
850 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800851 if (audio_coding_->RegisterTransportCallback(this) == -1) {
solenberg1c239d42017-09-29 06:00:28 -0700852 LOG(LS_ERROR) << "Channel::Init() callbacks not registered";
kwiberg55b97fe2016-01-28 05:22:45 -0800853 return -1;
854 }
855
kwiberg1c07c702017-03-27 07:15:49 -0700856 return 0;
857}
858
tommi0a2391f2017-03-21 02:31:51 -0700859void Channel::Terminate() {
860 RTC_DCHECK(construction_thread_.CalledOnValidThread());
861 // Must be called on the same thread as Init().
862 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
863 "Channel::Terminate");
864
865 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
866
867 StopSend();
868 StopPlayout();
869
tommi0a2391f2017-03-21 02:31:51 -0700870 // The order to safely shutdown modules in a channel is:
871 // 1. De-register callbacks in modules
872 // 2. De-register modules in process thread
873 // 3. Destroy modules
874 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
875 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
876 "Terminate() failed to de-register transport callback"
877 " (Audio coding module)");
878 }
879
tommi0a2391f2017-03-21 02:31:51 -0700880 // De-register modules in process thread
881 if (_moduleProcessThreadPtr)
882 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
883
884 // End of modules shutdown
885}
886
solenberg1c239d42017-09-29 06:00:28 -0700887int32_t Channel::SetEngineInformation(ProcessThread& moduleProcessThread,
kwiberg55b97fe2016-01-28 05:22:45 -0800888 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700889 rtc::TaskQueue* encoder_queue) {
890 RTC_DCHECK(encoder_queue);
891 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800892 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
893 "Channel::SetEngineInformation()");
kwiberg55b97fe2016-01-28 05:22:45 -0800894 _moduleProcessThreadPtr = &moduleProcessThread;
895 _audioDeviceModulePtr = &audioDeviceModule;
henrikaec6fbd22017-03-31 05:43:36 -0700896 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800897 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000898}
899
kwibergb7f89d62016-02-17 10:04:18 -0800900void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800901 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800902 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100903}
904
ossu29b1a8d2016-06-13 07:34:51 -0700905const rtc::scoped_refptr<AudioDecoderFactory>&
906Channel::GetAudioDecoderFactory() const {
907 return decoder_factory_;
908}
909
kwiberg55b97fe2016-01-28 05:22:45 -0800910int32_t Channel::StartPlayout() {
911 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
912 "Channel::StartPlayout()");
913 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000914 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800915 }
916
kwiberg55b97fe2016-01-28 05:22:45 -0800917 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800918
919 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000920}
921
kwiberg55b97fe2016-01-28 05:22:45 -0800922int32_t Channel::StopPlayout() {
923 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
924 "Channel::StopPlayout()");
925 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000926 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800927 }
928
kwiberg55b97fe2016-01-28 05:22:45 -0800929 channel_state_.SetPlaying(false);
930 _outputAudioLevel.Clear();
931
932 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000933}
934
kwiberg55b97fe2016-01-28 05:22:45 -0800935int32_t Channel::StartSend() {
936 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
937 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -0800938 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000939 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800940 }
941 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700942 {
943 // It is now OK to start posting tasks to the encoder task queue.
944 rtc::CritScope cs(&encoder_queue_lock_);
945 encoder_queue_is_active_ = true;
946 }
solenberg08b19df2017-02-15 00:42:31 -0800947 // Resume the previous sequence number which was reset by StopSend(). This
948 // needs to be done before |sending| is set to true on the RTP/RTCP module.
949 if (send_sequence_number_) {
950 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
951 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100952 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800953 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
solenberg1c239d42017-09-29 06:00:28 -0700954 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending";
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100955 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800956 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000957 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800958 return -1;
959 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000960
kwiberg55b97fe2016-01-28 05:22:45 -0800961 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000962}
963
henrikaec6fbd22017-03-31 05:43:36 -0700964void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800965 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
966 "Channel::StopSend()");
967 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700968 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800969 }
970 channel_state_.SetSending(false);
971
henrikaec6fbd22017-03-31 05:43:36 -0700972 // Post a task to the encoder thread which sets an event when the task is
973 // executed. We know that no more encoding tasks will be added to the task
974 // queue for this channel since sending is now deactivated. It means that,
975 // if we wait for the event to bet set, we know that no more pending tasks
976 // exists and it is therfore guaranteed that the task queue will never try
977 // to acccess and invalid channel object.
978 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -0700979
henrikaec6fbd22017-03-31 05:43:36 -0700980 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -0700981 {
982 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
983 // than this final "flush task" to be posted on the queue.
984 rtc::CritScope cs(&encoder_queue_lock_);
985 encoder_queue_is_active_ = false;
986 encoder_queue_->PostTask([&flush]() { flush.Set(); });
987 }
henrikaec6fbd22017-03-31 05:43:36 -0700988 flush.Wait(rtc::Event::kForever);
989
kwiberg55b97fe2016-01-28 05:22:45 -0800990 // Store the sequence number to be able to pick up the same sequence for
991 // the next StartSend(). This is needed for restarting device, otherwise
992 // it might cause libSRTP to complain about packets being replayed.
993 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
994 // CL is landed. See issue
995 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
996 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
997
998 // Reset sending SSRC and sequence number and triggers direct transmission
999 // of RTCP BYE
1000 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
solenberg1c239d42017-09-29 06:00:28 -07001001 LOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001002 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001003 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001004}
1005
ossu1ffbd6c2017-04-06 12:05:04 -07001006bool Channel::SetEncoder(int payload_type,
1007 std::unique_ptr<AudioEncoder> encoder) {
1008 RTC_DCHECK_GE(payload_type, 0);
1009 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001010 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1011 // one for for us to keep track of sample rate and number of channels, etc.
1012
1013 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1014 // as well as some other things, so we collect this info and send it along.
1015 CodecInst rtp_codec;
1016 rtp_codec.pltype = payload_type;
1017 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1018 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001019 // Seems unclear if it should be clock rate or sample rate. CodecInst
1020 // supposedly carries the sample rate, but only clock rate seems sensible to
1021 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001022 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1023 rtp_codec.pacsize = rtc::CheckedDivExact(
1024 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1025 100);
1026 rtp_codec.channels = encoder->NumChannels();
1027 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001028
ossu76d29f92017-06-09 07:30:13 -07001029 // For audio encoding we need, instead, the actual sample rate of the codec.
1030 // The rest of the information should be the same.
1031 CodecInst send_codec = rtp_codec;
1032 send_codec.plfreq = encoder->SampleRateHz();
1033 cached_send_codec_.emplace(send_codec);
1034
1035 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001036 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001037 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001038 WEBRTC_TRACE(
1039 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1040 "SetEncoder() failed to register codec to RTP/RTCP module");
1041 return false;
1042 }
1043 }
1044
1045 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001046 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001047 return true;
1048}
1049
ossu20a4b3f2017-04-27 02:08:52 -07001050void Channel::ModifyEncoder(
1051 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1052 audio_coding_->ModifyEncoder(modifier);
1053}
1054
kwiberg55b97fe2016-01-28 05:22:45 -08001055int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001056 if (cached_send_codec_) {
1057 codec = *cached_send_codec_;
1058 return 0;
1059 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001060 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1061 if (send_codec) {
1062 codec = *send_codec;
1063 return 0;
1064 }
1065 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001066 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001067}
1068
kwiberg55b97fe2016-01-28 05:22:45 -08001069int32_t Channel::GetRecCodec(CodecInst& codec) {
1070 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001071}
1072
kwiberg55b97fe2016-01-28 05:22:45 -08001073int32_t Channel::SetSendCodec(const CodecInst& codec) {
1074 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1075 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001076
kwibergc8d071e2016-04-06 12:22:38 -07001077 if (!codec_manager_.RegisterEncoder(codec) ||
1078 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001079 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1080 "SetSendCodec() failed to register codec to ACM");
1081 return -1;
1082 }
1083
1084 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1085 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1086 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1087 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1088 "SetSendCodec() failed to register codec to"
1089 " RTP/RTCP module");
1090 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001091 }
kwiberg55b97fe2016-01-28 05:22:45 -08001092 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001093
ossu76d29f92017-06-09 07:30:13 -07001094 cached_send_codec_.reset();
1095
kwiberg55b97fe2016-01-28 05:22:45 -08001096 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001097}
1098
minyue78b4d562016-11-30 04:47:39 -08001099void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001100 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1101 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001102 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001103 if (*encoder) {
1104 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001105 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001106 }
1107 });
michaelt566d8202017-01-12 10:17:38 -08001108 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001109}
1110
elad.alond12a8e12017-03-23 11:04:48 -07001111void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1112 if (!use_twcc_plr_for_ana_)
1113 return;
minyue7e304322016-10-12 05:00:55 -07001114 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001115 if (*encoder) {
1116 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1117 }
1118 });
1119}
1120
elad.alondadb4dc2017-03-23 15:29:50 -07001121void Channel::OnRecoverableUplinkPacketLossRate(
1122 float recoverable_packet_loss_rate) {
1123 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1124 if (*encoder) {
1125 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1126 recoverable_packet_loss_rate);
1127 }
1128 });
1129}
1130
elad.alond12a8e12017-03-23 11:04:48 -07001131void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1132 if (use_twcc_plr_for_ana_)
1133 return;
1134 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1135 if (*encoder) {
1136 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1137 }
minyue7e304322016-10-12 05:00:55 -07001138 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001139}
1140
kwiberg1c07c702017-03-27 07:15:49 -07001141void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1142 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1143 audio_coding_->SetReceiveCodecs(codecs);
1144}
1145
minyue7e304322016-10-12 05:00:55 -07001146bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1147 bool success = false;
1148 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1149 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001150 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1151 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001152 }
1153 });
1154 return success;
1155}
1156
1157void Channel::DisableAudioNetworkAdaptor() {
1158 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1159 if (*encoder)
1160 (*encoder)->DisableAudioNetworkAdaptor();
1161 });
1162}
1163
1164void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1165 int max_frame_length_ms) {
1166 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1167 if (*encoder) {
1168 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1169 max_frame_length_ms);
1170 }
1171 });
1172}
1173
solenberg1c239d42017-09-29 06:00:28 -07001174void Channel::RegisterTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001175 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001176 _transportPtr = transport;
niklase@google.com470e71d2011-07-07 08:21:25 +00001177}
1178
nisse657bab22017-02-21 06:28:10 -08001179void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1180 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg946d8862017-09-21 04:02:53 -07001181 "Channel::OnRtpPacket()");
nisse657bab22017-02-21 06:28:10 -08001182
1183 RTPHeader header;
1184 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -07001185
1186 // Store playout timestamp for the received RTP packet
1187 UpdatePlayoutTimestamp(false);
1188
1189 header.payload_type_frequency =
1190 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1191 if (header.payload_type_frequency >= 0) {
1192 bool in_order = IsPacketInOrder(header);
1193 rtp_receive_statistics_->IncomingPacket(
1194 header, packet.size(), IsPacketRetransmitted(header, in_order));
1195 rtp_payload_registry_->SetIncomingPayloadType(header);
1196
1197 ReceivePacket(packet.data(), packet.size(), header, in_order);
1198 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001199}
1200
1201bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001202 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001203 const RTPHeader& header,
1204 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001205 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001206 assert(packet_length >= header.headerLength);
1207 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001208 const auto pl =
1209 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1210 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001211 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001212 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001213 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Karl Wiberg73b60b82017-09-21 15:00:58 +02001214 pl->typeSpecific, in_order);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001215}
1216
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001217bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1218 StreamStatistician* statistician =
1219 rtp_receive_statistics_->GetStatistician(header.ssrc);
1220 if (!statistician)
1221 return false;
1222 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001223}
1224
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001225bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1226 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001227 StreamStatistician* statistician =
1228 rtp_receive_statistics_->GetStatistician(header.ssrc);
1229 if (!statistician)
1230 return false;
1231 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001232 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001233 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001234 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001235}
1236
mflodman3d7db262016-04-29 00:57:13 -07001237int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001238 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001239 "Channel::ReceivedRTCPPacket()");
1240 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001241 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001242
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001243 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001244 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001245
Minyue2013aec2015-05-13 14:14:42 +02001246 int64_t rtt = GetRTT(true);
1247 if (rtt == 0) {
1248 // Waiting for valid RTT.
1249 return 0;
1250 }
Erik Språng737336d2016-07-29 12:59:36 +02001251
1252 int64_t nack_window_ms = rtt;
1253 if (nack_window_ms < kMinRetransmissionWindowMs) {
1254 nack_window_ms = kMinRetransmissionWindowMs;
1255 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1256 nack_window_ms = kMaxRetransmissionWindowMs;
1257 }
1258 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1259
minyue7e304322016-10-12 05:00:55 -07001260 // Invoke audio encoders OnReceivedRtt().
1261 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1262 if (*encoder)
1263 (*encoder)->OnReceivedRtt(rtt);
1264 });
1265
Minyue2013aec2015-05-13 14:14:42 +02001266 uint32_t ntp_secs = 0;
1267 uint32_t ntp_frac = 0;
1268 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001269 if (0 !=
1270 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1271 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001272 // Waiting for RTCP.
1273 return 0;
1274 }
1275
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001276 {
tommi31fc21f2016-01-21 10:37:37 -08001277 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001278 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001279 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001280 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001281}
1282
solenberg8d73f8c2017-03-08 01:52:20 -08001283int Channel::GetSpeechOutputLevel() const {
1284 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001285}
1286
solenberg8d73f8c2017-03-08 01:52:20 -08001287int Channel::GetSpeechOutputLevelFullRange() const {
1288 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001289}
1290
zsteine76bd3a2017-07-14 12:17:49 -07001291double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001292 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001293}
1294
1295double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001296 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001297}
1298
solenberg8d73f8c2017-03-08 01:52:20 -08001299void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001300 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001301 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001302}
1303
solenberg1c2af8e2016-03-24 10:36:00 -07001304bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001305 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001306 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001307}
1308
solenberg8d73f8c2017-03-08 01:52:20 -08001309void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001310 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001311 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001312}
1313
solenberg8842c3e2016-03-11 03:06:41 -08001314int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001315 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001316 "Channel::SendTelephoneEventOutband(...)");
1317 RTC_DCHECK_LE(0, event);
1318 RTC_DCHECK_GE(255, event);
1319 RTC_DCHECK_LE(0, duration_ms);
1320 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001321 if (!Sending()) {
1322 return -1;
1323 }
solenberg8842c3e2016-03-11 03:06:41 -08001324 if (_rtpRtcpModule->SendTelephoneEventOutband(
1325 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001326 LOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event";
kwiberg55b97fe2016-01-28 05:22:45 -08001327 return -1;
1328 }
1329 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001330}
1331
solenbergffbbcac2016-11-17 05:25:37 -08001332int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1333 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001334 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001335 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001336 RTC_DCHECK_LE(0, payload_type);
1337 RTC_DCHECK_GE(127, payload_type);
1338 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001339 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001340 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001341 memcpy(codec.plname, "telephone-event", 16);
1342 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1343 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1344 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001345 LOG(LS_ERROR) << "SetSendTelephoneEventPayloadType() failed to register "
1346 "send payload type";
kwiberg55b97fe2016-01-28 05:22:45 -08001347 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001348 }
kwiberg55b97fe2016-01-28 05:22:45 -08001349 }
kwiberg55b97fe2016-01-28 05:22:45 -08001350 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001351}
1352
kwiberg55b97fe2016-01-28 05:22:45 -08001353int Channel::SetLocalSSRC(unsigned int ssrc) {
1354 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1355 "Channel::SetLocalSSRC()");
1356 if (channel_state_.Get().sending) {
solenberg1c239d42017-09-29 06:00:28 -07001357 LOG(LS_ERROR) << "SetLocalSSRC() already sending";
kwiberg55b97fe2016-01-28 05:22:45 -08001358 return -1;
1359 }
1360 _rtpRtcpModule->SetSSRC(ssrc);
1361 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001362}
1363
kwiberg55b97fe2016-01-28 05:22:45 -08001364int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1365 ssrc = rtp_receiver_->SSRC();
1366 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001367}
1368
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001369int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001370 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001371 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001372}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001373
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001374int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1375 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001376 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1377 if (enable &&
1378 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1379 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001380 return -1;
1381 }
1382 return 0;
1383}
1384
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001385void Channel::EnableSendTransportSequenceNumber(int id) {
1386 int ret =
1387 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1388 RTC_DCHECK_EQ(0, ret);
1389}
1390
stefan3313ec92016-01-21 06:32:43 -08001391void Channel::EnableReceiveTransportSequenceNumber(int id) {
1392 rtp_header_parser_->DeregisterRtpHeaderExtension(
1393 kRtpExtensionTransportSequenceNumber);
1394 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1395 kRtpExtensionTransportSequenceNumber, id);
1396 RTC_DCHECK(ret);
1397}
1398
stefanbba9dec2016-02-01 04:39:55 -08001399void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001400 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001401 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001402 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1403 TransportFeedbackObserver* transport_feedback_observer =
1404 transport->transport_feedback_observer();
1405 PacketRouter* packet_router = transport->packet_router();
1406
stefanbba9dec2016-02-01 04:39:55 -08001407 RTC_DCHECK(rtp_packet_sender);
1408 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001409 RTC_DCHECK(packet_router);
1410 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001411 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001412 feedback_observer_proxy_->SetTransportFeedbackObserver(
1413 transport_feedback_observer);
1414 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1415 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1416 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001417 constexpr bool remb_candidate = false;
1418 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001419 packet_router_ = packet_router;
1420}
1421
stefanbba9dec2016-02-01 04:39:55 -08001422void Channel::RegisterReceiverCongestionControlObjects(
1423 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001424 RTC_DCHECK(packet_router);
1425 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001426 constexpr bool remb_candidate = false;
1427 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001428 packet_router_ = packet_router;
1429}
1430
nissefdbfdc92017-03-31 05:44:52 -07001431void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001432 RTC_DCHECK(packet_router_);
1433 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001434 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001435 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1436 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001437 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001438 packet_router_ = nullptr;
1439 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1440}
1441
nissefdbfdc92017-03-31 05:44:52 -07001442void Channel::ResetReceiverCongestionControlObjects() {
1443 RTC_DCHECK(packet_router_);
1444 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1445 packet_router_ = nullptr;
1446}
1447
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001448void Channel::SetRTCPStatus(bool enable) {
1449 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1450 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001451 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001452}
1453
kwiberg55b97fe2016-01-28 05:22:45 -08001454int Channel::SetRTCP_CNAME(const char cName[256]) {
1455 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1456 "Channel::SetRTCP_CNAME()");
1457 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001458 LOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME";
kwiberg55b97fe2016-01-28 05:22:45 -08001459 return -1;
1460 }
1461 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001462}
1463
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001464int Channel::GetRemoteRTCPReportBlocks(
1465 std::vector<ReportBlock>* report_blocks) {
1466 if (report_blocks == NULL) {
solenberg1c239d42017-09-29 06:00:28 -07001467 LOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks.";
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001468 return -1;
1469 }
1470
1471 // Get the report blocks from the latest received RTCP Sender or Receiver
1472 // Report. Each element in the vector contains the sender's SSRC and a
1473 // report block according to RFC 3550.
1474 std::vector<RTCPReportBlock> rtcp_report_blocks;
1475 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001476 return -1;
1477 }
1478
1479 if (rtcp_report_blocks.empty())
1480 return 0;
1481
1482 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1483 for (; it != rtcp_report_blocks.end(); ++it) {
1484 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001485 report_block.sender_SSRC = it->sender_ssrc;
1486 report_block.source_SSRC = it->source_ssrc;
1487 report_block.fraction_lost = it->fraction_lost;
1488 report_block.cumulative_num_packets_lost = it->packets_lost;
1489 report_block.extended_highest_sequence_number =
1490 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001491 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001492 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1493 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001494 report_blocks->push_back(report_block);
1495 }
1496 return 0;
1497}
1498
kwiberg55b97fe2016-01-28 05:22:45 -08001499int Channel::GetRTPStatistics(CallStatistics& stats) {
1500 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001501
kwiberg55b97fe2016-01-28 05:22:45 -08001502 // The jitter statistics is updated for each received RTP packet and is
1503 // based on received packets.
1504 RtcpStatistics statistics;
1505 StreamStatistician* statistician =
1506 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001507 if (statistician) {
1508 statistician->GetStatistics(&statistics,
1509 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001510 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001511
kwiberg55b97fe2016-01-28 05:22:45 -08001512 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001513 stats.cumulativeLost = statistics.packets_lost;
1514 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001515 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001516
kwiberg55b97fe2016-01-28 05:22:45 -08001517 // --- RTT
1518 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001519
kwiberg55b97fe2016-01-28 05:22:45 -08001520 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001521
kwiberg55b97fe2016-01-28 05:22:45 -08001522 size_t bytesSent(0);
1523 uint32_t packetsSent(0);
1524 size_t bytesReceived(0);
1525 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001526
kwiberg55b97fe2016-01-28 05:22:45 -08001527 if (statistician) {
1528 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1529 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001530
kwiberg55b97fe2016-01-28 05:22:45 -08001531 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
1532 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1533 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
1534 " output will not be complete");
1535 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001536
kwiberg55b97fe2016-01-28 05:22:45 -08001537 stats.bytesSent = bytesSent;
1538 stats.packetsSent = packetsSent;
1539 stats.bytesReceived = bytesReceived;
1540 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001541
kwiberg55b97fe2016-01-28 05:22:45 -08001542 // --- Timestamps
1543 {
1544 rtc::CritScope lock(&ts_stats_lock_);
1545 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1546 }
1547 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001548}
1549
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001550void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1551 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001552 // If pacing is enabled we always store packets.
1553 if (!pacing_enabled_)
1554 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001555 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001556 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001557 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001558 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001559 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001560}
1561
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001562// Called when we are missing one or more packets.
1563int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001564 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1565}
1566
henrikaec6fbd22017-03-31 05:43:36 -07001567void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001568 // Avoid posting any new tasks if sending was already stopped in StopSend().
1569 rtc::CritScope cs(&encoder_queue_lock_);
1570 if (!encoder_queue_is_active_) {
1571 return;
1572 }
henrikaec6fbd22017-03-31 05:43:36 -07001573 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1574 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1575 // either into pool of frames or into the task itself.
1576 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001577 // Profile time between when the audio frame is added to the task queue and
1578 // when the task is actually executed.
1579 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001580 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1581 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001582}
1583
henrikaec6fbd22017-03-31 05:43:36 -07001584void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1585 int sample_rate,
1586 size_t number_of_frames,
1587 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001588 // Avoid posting as new task if sending was already stopped in StopSend().
1589 rtc::CritScope cs(&encoder_queue_lock_);
1590 if (!encoder_queue_is_active_) {
1591 return;
1592 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001593 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001594 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001595 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
ossu950c1c92017-07-11 08:19:31 -07001596 // TODO(ossu): Investigate how this could happen. b/62909493
1597 if (result == 0) {
1598 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1599 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1600 } else {
1601 audio_frame->sample_rate_hz_ = sample_rate;
1602 audio_frame->num_channels_ = number_of_channels;
1603 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1604 RTC_NOTREACHED();
1605 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001606 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001607 sample_rate, &input_resampler_, audio_frame.get());
1608 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1609 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001610}
1611
henrikaec6fbd22017-03-31 05:43:36 -07001612void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1613 RTC_DCHECK_RUN_ON(encoder_queue_);
1614 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1615 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001616
henrika45802172017-09-28 09:39:34 +02001617 // Measure time between when the audio frame is added to the task queue and
1618 // when the task is actually executed. Goal is to keep track of unwanted
1619 // extra latency added by the task queue.
1620 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1621 audio_input->ElapsedProfileTimeMs());
1622
henrikaec6fbd22017-03-31 05:43:36 -07001623 bool is_muted = InputMute();
1624 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001625
kwiberg55b97fe2016-01-28 05:22:45 -08001626 if (_includeAudioLevelIndication) {
1627 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001628 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001629 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001630 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001631 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001632 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001633 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001634 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001635 }
kwiberg55b97fe2016-01-28 05:22:45 -08001636 }
solenberg1c2af8e2016-03-24 10:36:00 -07001637 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001638
henrikaec6fbd22017-03-31 05:43:36 -07001639 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001640
kwiberg55b97fe2016-01-28 05:22:45 -08001641 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001642 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001643 // This call will trigger AudioPacketizationCallback::SendData if encoding
1644 // is done and payload is ready for packetization and transmission.
1645 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001646 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1647 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1648 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001649 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001650
henrikaec6fbd22017-03-31 05:43:36 -07001651 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001652}
1653
solenberg7602aab2016-11-14 11:30:07 -08001654void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1655 RTC_DCHECK(!channel.channel() ||
1656 channel.channel()->ChannelId() != _channelId);
1657 rtc::CritScope lock(&assoc_send_channel_lock_);
1658 associate_send_channel_ = channel;
1659}
1660
Minyue2013aec2015-05-13 14:14:42 +02001661void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001662 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001663 Channel* channel = associate_send_channel_.channel();
1664 if (channel && channel->ChannelId() == channel_id) {
1665 // If this channel is associated with a send channel of the specified
1666 // Channel ID, disassociate with it.
1667 ChannelOwner ref(NULL);
1668 associate_send_channel_ = ref;
1669 }
1670}
1671
ivoc14d5dbe2016-07-04 07:06:55 -07001672void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1673 event_log_proxy_->SetEventLog(event_log);
1674}
1675
michaelt9332b7d2016-11-30 07:51:13 -08001676void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1677 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1678}
1679
nisse284542b2017-01-10 08:58:32 -08001680void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001681 size_t overhead_per_packet =
1682 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001683 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1684 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001685 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001686 }
1687 });
1688}
1689
1690void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001691 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001692 transport_overhead_per_packet_ = transport_overhead_per_packet;
1693 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001694}
1695
hbos3fd31fe2017-02-28 05:43:16 -08001696// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001697void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001698 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001699 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1700 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001701}
1702
kwiberg55b97fe2016-01-28 05:22:45 -08001703int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1704 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001705}
1706
wu@webrtc.org24301a62013-12-13 19:17:43 +00001707void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1708 audio_coding_->GetDecodingCallStatistics(stats);
1709}
1710
ivoce1198e02017-09-08 08:13:19 -07001711ANAStats Channel::GetANAStatistics() const {
1712 return audio_coding_->GetANAStats();
1713}
1714
solenberg358057b2015-11-27 10:46:42 -08001715uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001716 rtc::CritScope lock(&video_sync_lock_);
1717 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001718}
1719
kwiberg55b97fe2016-01-28 05:22:45 -08001720int Channel::SetMinimumPlayoutDelay(int delayMs) {
1721 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1722 "Channel::SetMinimumPlayoutDelay()");
1723 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1724 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
solenberg1c239d42017-09-29 06:00:28 -07001725 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001726 return -1;
1727 }
1728 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
solenberg1c239d42017-09-29 06:00:28 -07001729 LOG(LS_ERROR) << "SetMinimumPlayoutDelay() failed to set min playout delay";
kwiberg55b97fe2016-01-28 05:22:45 -08001730 return -1;
1731 }
1732 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001733}
1734
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001735int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001736 uint32_t playout_timestamp_rtp = 0;
1737 {
tommi31fc21f2016-01-21 10:37:37 -08001738 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001739 playout_timestamp_rtp = playout_timestamp_rtp_;
1740 }
kwiberg55b97fe2016-01-28 05:22:45 -08001741 if (playout_timestamp_rtp == 0) {
solenberg1c239d42017-09-29 06:00:28 -07001742 LOG(LS_ERROR) << "GetPlayoutTimestamp() failed to retrieve timestamp";
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001743 return -1;
1744 }
deadbeef74375882015-08-13 12:09:10 -07001745 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001746 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001747}
1748
kwiberg55b97fe2016-01-28 05:22:45 -08001749int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1750 RtpReceiver** rtp_receiver) const {
1751 *rtpRtcpModule = _rtpRtcpModule.get();
1752 *rtp_receiver = rtp_receiver_.get();
1753 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001754}
1755
deadbeef74375882015-08-13 12:09:10 -07001756void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001757 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001758
henrik.lundin96bd5022016-04-06 04:13:56 -07001759 if (!jitter_buffer_playout_timestamp_) {
1760 // This can happen if this channel has not received any RTP packets. In
1761 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001762 return;
1763 }
1764
1765 uint16_t delay_ms = 0;
1766 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001767 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001768 "Channel::UpdatePlayoutTimestamp() failed to read playout"
1769 " delay from the ADM");
deadbeef74375882015-08-13 12:09:10 -07001770 return;
1771 }
1772
henrik.lundin96bd5022016-04-06 04:13:56 -07001773 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1774 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001775
1776 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001777 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001778
kwiberg55b97fe2016-01-28 05:22:45 -08001779 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001780 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07001781 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07001782
1783 {
tommi31fc21f2016-01-21 10:37:37 -08001784 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001785 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001786 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001787 }
1788 playout_delay_ms_ = delay_ms;
1789 }
1790}
1791
kwiberg55b97fe2016-01-28 05:22:45 -08001792void Channel::RegisterReceiveCodecsToRTPModule() {
1793 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1794 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001795
kwiberg55b97fe2016-01-28 05:22:45 -08001796 CodecInst codec;
1797 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00001798
kwiberg55b97fe2016-01-28 05:22:45 -08001799 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1800 // Open up the RTP/RTCP receiver for all supported codecs
1801 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001802 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001803 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1804 "Channel::RegisterReceiveCodecsToRTPModule() unable"
1805 " to register %s (%d/%d/%" PRIuS
1806 "/%d) to RTP/RTCP "
1807 "receiver",
1808 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1809 codec.rate);
1810 } else {
1811 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1812 "Channel::RegisterReceiveCodecsToRTPModule() %s "
1813 "(%d/%d/%" PRIuS
1814 "/%d) has been added to the RTP/RTCP "
1815 "receiver",
1816 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1817 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001818 }
kwiberg55b97fe2016-01-28 05:22:45 -08001819 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001820}
1821
kwiberg55b97fe2016-01-28 05:22:45 -08001822int Channel::SetSendRtpHeaderExtension(bool enable,
1823 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001824 unsigned char id) {
1825 int error = 0;
1826 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1827 if (enable) {
1828 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1829 }
1830 return error;
1831}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001832
ossue280cde2016-10-12 11:04:10 -07001833int Channel::GetRtpTimestampRateHz() const {
1834 const auto format = audio_coding_->ReceiveFormat();
1835 // Default to the playout frequency if we've not gotten any packets yet.
1836 // TODO(ossu): Zero clockrate can only happen if we've added an external
1837 // decoder for a format we don't support internally. Remove once that way of
1838 // adding decoders is gone!
1839 return (format && format->clockrate_hz != 0)
1840 ? format->clockrate_hz
1841 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001842}
1843
Minyue2013aec2015-05-13 14:14:42 +02001844int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001845 RtcpMode method = _rtpRtcpModule->RTCP();
1846 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001847 return 0;
1848 }
1849 std::vector<RTCPReportBlock> report_blocks;
1850 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001851
1852 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001853 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001854 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001855 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001856 Channel* channel = associate_send_channel_.channel();
1857 // Tries to get RTT from an associated channel. This is important for
1858 // receive-only channels.
1859 if (channel) {
1860 // To prevent infinite recursion and deadlock, calling GetRTT of
1861 // associate channel should always use "false" for argument:
1862 // |allow_associate_channel|.
1863 rtt = channel->GetRTT(false);
1864 }
1865 }
1866 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001867 }
1868
1869 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1870 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1871 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001872 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001873 break;
1874 }
1875 if (it == report_blocks.end()) {
1876 // We have not received packets with SSRC matching the report blocks.
1877 // To calculate RTT we try with the SSRC of the first report block.
1878 // This is very important for send-only channels where we don't know
1879 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001880 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001881 }
Minyue2013aec2015-05-13 14:14:42 +02001882
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001883 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001884 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001885 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001886 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1887 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001888 return 0;
1889 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001890 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001891}
1892
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001893} // namespace voe
1894} // namespace webrtc