blob: 875454a17d1321fc30e5bd90edbc0fff2ab3caf4 [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"
41#include "system_wrappers/include/trace.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "voice_engine/statistics.h"
43#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)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800449 _engineStatisticsPtr->SetLastError(
450 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
451 "Channel::SendData() failed to send data to RTP/RTCP module");
452 return -1;
453 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000454
kwiberg55b97fe2016-01-28 05:22:45 -0800455 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000456}
457
stefan1d8a5062015-10-02 03:39:33 -0700458bool Channel::SendRtp(const uint8_t* data,
459 size_t len,
460 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800461 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
462 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000463
kwiberg55b97fe2016-01-28 05:22:45 -0800464 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000465
kwiberg55b97fe2016-01-28 05:22:45 -0800466 if (_transportPtr == NULL) {
467 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
468 "Channel::SendPacket() failed to send RTP packet due to"
469 " invalid transport object");
470 return false;
471 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000472
kwiberg55b97fe2016-01-28 05:22:45 -0800473 uint8_t* bufferToSendPtr = (uint8_t*)data;
474 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000475
kwiberg55b97fe2016-01-28 05:22:45 -0800476 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
477 std::string transport_name =
478 _externalTransport ? "external transport" : "WebRtc sockets";
479 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
480 "Channel::SendPacket() RTP transmission using %s failed",
481 transport_name.c_str());
482 return false;
483 }
484 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000485}
486
kwiberg55b97fe2016-01-28 05:22:45 -0800487bool Channel::SendRtcp(const uint8_t* data, size_t len) {
488 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
489 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000490
kwiberg55b97fe2016-01-28 05:22:45 -0800491 rtc::CritScope cs(&_callbackCritSect);
492 if (_transportPtr == NULL) {
493 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
494 "Channel::SendRtcp() failed to send RTCP packet"
495 " due to invalid transport object");
496 return false;
497 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000498
kwiberg55b97fe2016-01-28 05:22:45 -0800499 uint8_t* bufferToSendPtr = (uint8_t*)data;
500 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000501
kwiberg55b97fe2016-01-28 05:22:45 -0800502 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
503 if (n < 0) {
504 std::string transport_name =
505 _externalTransport ? "external transport" : "WebRtc sockets";
506 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
507 "Channel::SendRtcp() transmission using %s failed",
508 transport_name.c_str());
509 return false;
510 }
511 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000512}
513
kwiberg55b97fe2016-01-28 05:22:45 -0800514void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
515 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
516 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000517
kwiberg55b97fe2016-01-28 05:22:45 -0800518 // Update ssrc so that NTP for AV sync can be updated.
519 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000520}
521
Peter Boströmac547a62015-09-17 23:03:57 +0200522void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
523 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
524 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
525 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000526}
527
Peter Boströmac547a62015-09-17 23:03:57 +0200528int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000529 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000530 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000531 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800532 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200533 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800534 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
535 "Channel::OnInitializeDecoder(payloadType=%d, "
536 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
537 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000538
kwiberg55b97fe2016-01-28 05:22:45 -0800539 CodecInst receiveCodec = {0};
540 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000541
kwiberg55b97fe2016-01-28 05:22:45 -0800542 receiveCodec.pltype = payloadType;
543 receiveCodec.plfreq = frequency;
544 receiveCodec.channels = channels;
545 receiveCodec.rate = rate;
546 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000547
kwiberg55b97fe2016-01-28 05:22:45 -0800548 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
549 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000550
kwiberg55b97fe2016-01-28 05:22:45 -0800551 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700552 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
553 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800554 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
555 "Channel::OnInitializeDecoder() invalid codec ("
556 "pt=%d, name=%s) received - 1",
557 payloadType, payloadName);
558 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
559 return -1;
560 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000561
kwiberg55b97fe2016-01-28 05:22:45 -0800562 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000563}
564
kwiberg55b97fe2016-01-28 05:22:45 -0800565int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
566 size_t payloadSize,
567 const WebRtcRTPHeader* rtpHeader) {
568 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
569 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
570 ","
571 " payloadType=%u, audioChannel=%" PRIuS ")",
572 payloadSize, rtpHeader->header.payloadType,
573 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000574
kwiberg55b97fe2016-01-28 05:22:45 -0800575 if (!channel_state_.Get().playing) {
576 // Avoid inserting into NetEQ when we are not playing. Count the
577 // packet as discarded.
578 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
579 "received packet is discarded since playing is not"
580 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000581 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800582 }
583
584 // Push the incoming payload (parsed and ready for decoding) into the ACM
585 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
586 0) {
587 _engineStatisticsPtr->SetLastError(
588 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
589 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
590 return -1;
591 }
592
kwiberg55b97fe2016-01-28 05:22:45 -0800593 int64_t round_trip_time = 0;
594 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
595 NULL);
596
597 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
598 if (!nack_list.empty()) {
599 // Can't use nack_list.data() since it's not supported by all
600 // compilers.
601 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
602 }
603 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000604}
605
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000606bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000607 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000608 RTPHeader header;
609 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
610 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
611 "IncomingPacket invalid RTP header");
612 return false;
613 }
614 header.payload_type_frequency =
615 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
616 if (header.payload_type_frequency < 0)
617 return false;
618 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
619}
620
solenberg2397b9a2017-09-22 06:48:10 -0700621AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
622 int sample_rate_hz,
623 AudioFrame* audio_frame) {
624 audio_frame->sample_rate_hz_ = sample_rate_hz;
625
ivoc14d5dbe2016-07-04 07:06:55 -0700626 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800627 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700628 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800629 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700630 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700631 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700632 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800633 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
634 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
635 // In all likelihood, the audio in this frame is garbage. We return an
636 // error so that the audio mixer module doesn't add it to the mix. As
637 // a result, it won't be played out and the actions skipped here are
638 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700639 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800640 }
henrik.lundina89ab962016-05-18 08:52:45 -0700641
642 if (muted) {
643 // TODO(henrik.lundin): We should be able to do better than this. But we
644 // will have to go through all the cases below where the audio samples may
645 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700646 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700647 }
kwiberg55b97fe2016-01-28 05:22:45 -0800648
kwiberg55b97fe2016-01-28 05:22:45 -0800649 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700650 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800651
kwiberg55b97fe2016-01-28 05:22:45 -0800652 {
653 // Pass the audio buffers to an optional sink callback, before applying
654 // scaling/panning, as that applies to the mix operation.
655 // External recipients of the audio (e.g. via AudioTrack), will do their
656 // own mixing/dynamic processing.
657 rtc::CritScope cs(&_callbackCritSect);
658 if (audio_sink_) {
659 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700660 audio_frame->data(), audio_frame->samples_per_channel_,
661 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
662 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800663 audio_sink_->OnData(data);
664 }
665 }
666
667 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800668 {
669 rtc::CritScope cs(&volume_settings_critsect_);
670 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800671 }
672
673 // Output volume scaling
674 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800675 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700676 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800677 }
678
kwiberg55b97fe2016-01-28 05:22:45 -0800679 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700680 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700681 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700682 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700683 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800684
solenberg2397b9a2017-09-22 06:48:10 -0700685 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800686 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700687 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800688 }
689
690 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700691 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800692
693 // Compute elapsed time.
694 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700695 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
696 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800697 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700698 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800699
niklase@google.com470e71d2011-07-07 08:21:25 +0000700 {
kwiberg55b97fe2016-01-28 05:22:45 -0800701 rtc::CritScope lock(&ts_stats_lock_);
702 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700703 audio_frame->ntp_time_ms_ =
704 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800705 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700706 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800707 // Compute |capture_start_ntp_time_ms_| so that
708 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
709 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700710 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000711 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000712 }
kwiberg55b97fe2016-01-28 05:22:45 -0800713 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000714
solenberg2397b9a2017-09-22 06:48:10 -0700715 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
716 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000717}
718
solenberg2397b9a2017-09-22 06:48:10 -0700719int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800720 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700721 return std::max(audio_coding_->ReceiveFrequency(),
722 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000723}
724
henrikaec6fbd22017-03-31 05:43:36 -0700725int32_t Channel::CreateChannel(Channel*& channel,
726 int32_t channelId,
727 uint32_t instanceId,
728 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800729 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
730 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
731 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000732
solenberg88499ec2016-09-07 07:34:41 -0700733 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800734 if (channel == NULL) {
735 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
736 "Channel::CreateChannel() unable to allocate memory for"
737 " channel");
738 return -1;
739 }
740 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000741}
742
pbos@webrtc.org92135212013-05-14 08:31:39 +0000743Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000744 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700745 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800746 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100747 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700748 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800749 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100750 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800751 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100752 rtp_receive_statistics_(
753 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
754 rtp_receiver_(
755 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100756 this,
757 this,
758 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700759 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100760 _outputAudioLevel(),
761 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100762 _timeStamp(0), // This is just an offset, RTP module will add it's own
763 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100764 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100765 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100766 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100767 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100768 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
769 capture_start_rtp_time_stamp_(-1),
770 capture_start_ntp_time_ms_(-1),
771 _engineStatisticsPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100772 _moduleProcessThreadPtr(NULL),
773 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100774 _callbackCritSectPtr(NULL),
775 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700776 input_mute_(false),
777 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100778 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100779 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800780 transport_overhead_per_packet_(0),
781 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100782 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100783 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100784 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700785 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800786 feedback_observer_proxy_(new TransportFeedbackProxy()),
787 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700788 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200789 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
790 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700791 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700792 use_twcc_plr_for_ana_(
793 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800794 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
795 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700796 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700797 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800798 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200799
kwiberg55b97fe2016-01-28 05:22:45 -0800800 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000801
kwiberg55b97fe2016-01-28 05:22:45 -0800802 RtpRtcp::Configuration configuration;
803 configuration.audio = true;
804 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800805 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800806 configuration.receive_statistics = rtp_receive_statistics_.get();
807 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800808 if (pacing_enabled_) {
809 configuration.paced_sender = rtp_packet_sender_proxy_.get();
810 configuration.transport_sequence_number_allocator =
811 seq_num_allocator_proxy_.get();
812 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
813 }
ivoc14d5dbe2016-07-04 07:06:55 -0700814 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800815 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200816 configuration.retransmission_rate_limiter =
817 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000818
kwiberg55b97fe2016-01-28 05:22:45 -0800819 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100820 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000821}
822
kwiberg55b97fe2016-01-28 05:22:45 -0800823Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700824 RTC_DCHECK(!channel_state_.Get().sending);
825 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000826}
827
kwiberg55b97fe2016-01-28 05:22:45 -0800828int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700829 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800830 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
831 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000832
kwiberg55b97fe2016-01-28 05:22:45 -0800833 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000834
kwiberg55b97fe2016-01-28 05:22:45 -0800835 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000836
kwiberg55b97fe2016-01-28 05:22:45 -0800837 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
838 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
839 "Channel::Init() must call SetEngineInformation() first");
840 return -1;
841 }
842
843 // --- Add modules to process thread (for periodic schedulation)
844
tommidea489f2017-03-03 03:20:24 -0800845 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800846
847 // --- ACM initialization
848
849 if (audio_coding_->InitializeReceiver() == -1) {
850 _engineStatisticsPtr->SetLastError(
851 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
852 "Channel::Init() unable to initialize the ACM - 1");
853 return -1;
854 }
855
856 // --- RTP/RTCP module initialization
857
858 // Ensure that RTCP is enabled by default for the created channel.
859 // Note that, the module will keep generating RTCP until it is explicitly
860 // disabled by the user.
861 // After StopListen (when no sockets exists), RTCP packets will no longer
862 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700863 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800864 // RTCP is enabled by default.
865 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
866 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800867 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800868 _engineStatisticsPtr->SetLastError(
869 VE_CANNOT_INIT_CHANNEL, kTraceError,
870 "Channel::Init() callbacks not registered");
871 return -1;
872 }
873
kwiberg1c07c702017-03-27 07:15:49 -0700874 return 0;
875}
876
tommi0a2391f2017-03-21 02:31:51 -0700877void Channel::Terminate() {
878 RTC_DCHECK(construction_thread_.CalledOnValidThread());
879 // Must be called on the same thread as Init().
880 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
881 "Channel::Terminate");
882
883 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
884
885 StopSend();
886 StopPlayout();
887
tommi0a2391f2017-03-21 02:31:51 -0700888 // The order to safely shutdown modules in a channel is:
889 // 1. De-register callbacks in modules
890 // 2. De-register modules in process thread
891 // 3. Destroy modules
892 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
893 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
894 "Terminate() failed to de-register transport callback"
895 " (Audio coding module)");
896 }
897
tommi0a2391f2017-03-21 02:31:51 -0700898 // De-register modules in process thread
899 if (_moduleProcessThreadPtr)
900 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
901
902 // End of modules shutdown
903}
904
kwiberg55b97fe2016-01-28 05:22:45 -0800905int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
kwiberg55b97fe2016-01-28 05:22:45 -0800906 ProcessThread& moduleProcessThread,
907 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700908 rtc::CriticalSection* callbackCritSect,
909 rtc::TaskQueue* encoder_queue) {
910 RTC_DCHECK(encoder_queue);
911 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800912 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
913 "Channel::SetEngineInformation()");
914 _engineStatisticsPtr = &engineStatistics;
kwiberg55b97fe2016-01-28 05:22:45 -0800915 _moduleProcessThreadPtr = &moduleProcessThread;
916 _audioDeviceModulePtr = &audioDeviceModule;
kwiberg55b97fe2016-01-28 05:22:45 -0800917 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -0700918 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800919 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000920}
921
kwibergb7f89d62016-02-17 10:04:18 -0800922void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800923 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800924 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100925}
926
ossu29b1a8d2016-06-13 07:34:51 -0700927const rtc::scoped_refptr<AudioDecoderFactory>&
928Channel::GetAudioDecoderFactory() const {
929 return decoder_factory_;
930}
931
kwiberg55b97fe2016-01-28 05:22:45 -0800932int32_t Channel::StartPlayout() {
933 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
934 "Channel::StartPlayout()");
935 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000936 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800937 }
938
kwiberg55b97fe2016-01-28 05:22:45 -0800939 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800940
941 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000942}
943
kwiberg55b97fe2016-01-28 05:22:45 -0800944int32_t Channel::StopPlayout() {
945 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
946 "Channel::StopPlayout()");
947 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000948 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800949 }
950
kwiberg55b97fe2016-01-28 05:22:45 -0800951 channel_state_.SetPlaying(false);
952 _outputAudioLevel.Clear();
953
954 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000955}
956
kwiberg55b97fe2016-01-28 05:22:45 -0800957int32_t Channel::StartSend() {
958 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
959 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -0800960 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000961 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800962 }
963 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700964 {
965 // It is now OK to start posting tasks to the encoder task queue.
966 rtc::CritScope cs(&encoder_queue_lock_);
967 encoder_queue_is_active_ = true;
968 }
solenberg08b19df2017-02-15 00:42:31 -0800969 // Resume the previous sequence number which was reset by StopSend(). This
970 // needs to be done before |sending| is set to true on the RTP/RTCP module.
971 if (send_sequence_number_) {
972 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
973 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100974 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800975 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
976 _engineStatisticsPtr->SetLastError(
977 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
978 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100979 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800980 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000981 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800982 return -1;
983 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000984
kwiberg55b97fe2016-01-28 05:22:45 -0800985 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000986}
987
henrikaec6fbd22017-03-31 05:43:36 -0700988void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800989 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
990 "Channel::StopSend()");
991 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700992 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800993 }
994 channel_state_.SetSending(false);
995
henrikaec6fbd22017-03-31 05:43:36 -0700996 // Post a task to the encoder thread which sets an event when the task is
997 // executed. We know that no more encoding tasks will be added to the task
998 // queue for this channel since sending is now deactivated. It means that,
999 // if we wait for the event to bet set, we know that no more pending tasks
1000 // exists and it is therfore guaranteed that the task queue will never try
1001 // to acccess and invalid channel object.
1002 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001003
henrikaec6fbd22017-03-31 05:43:36 -07001004 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001005 {
1006 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1007 // than this final "flush task" to be posted on the queue.
1008 rtc::CritScope cs(&encoder_queue_lock_);
1009 encoder_queue_is_active_ = false;
1010 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1011 }
henrikaec6fbd22017-03-31 05:43:36 -07001012 flush.Wait(rtc::Event::kForever);
1013
kwiberg55b97fe2016-01-28 05:22:45 -08001014 // Store the sequence number to be able to pick up the same sequence for
1015 // the next StartSend(). This is needed for restarting device, otherwise
1016 // it might cause libSRTP to complain about packets being replayed.
1017 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1018 // CL is landed. See issue
1019 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1020 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1021
1022 // Reset sending SSRC and sequence number and triggers direct transmission
1023 // of RTCP BYE
1024 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1025 _engineStatisticsPtr->SetLastError(
1026 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1027 "StartSend() RTP/RTCP failed to stop sending");
1028 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001029 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001030}
1031
ossu1ffbd6c2017-04-06 12:05:04 -07001032bool Channel::SetEncoder(int payload_type,
1033 std::unique_ptr<AudioEncoder> encoder) {
1034 RTC_DCHECK_GE(payload_type, 0);
1035 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001036 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1037 // one for for us to keep track of sample rate and number of channels, etc.
1038
1039 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1040 // as well as some other things, so we collect this info and send it along.
1041 CodecInst rtp_codec;
1042 rtp_codec.pltype = payload_type;
1043 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1044 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001045 // Seems unclear if it should be clock rate or sample rate. CodecInst
1046 // supposedly carries the sample rate, but only clock rate seems sensible to
1047 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001048 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1049 rtp_codec.pacsize = rtc::CheckedDivExact(
1050 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1051 100);
1052 rtp_codec.channels = encoder->NumChannels();
1053 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001054
ossu76d29f92017-06-09 07:30:13 -07001055 // For audio encoding we need, instead, the actual sample rate of the codec.
1056 // The rest of the information should be the same.
1057 CodecInst send_codec = rtp_codec;
1058 send_codec.plfreq = encoder->SampleRateHz();
1059 cached_send_codec_.emplace(send_codec);
1060
1061 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001062 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001063 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001064 WEBRTC_TRACE(
1065 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1066 "SetEncoder() failed to register codec to RTP/RTCP module");
1067 return false;
1068 }
1069 }
1070
1071 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001072 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001073 return true;
1074}
1075
ossu20a4b3f2017-04-27 02:08:52 -07001076void Channel::ModifyEncoder(
1077 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1078 audio_coding_->ModifyEncoder(modifier);
1079}
1080
kwiberg55b97fe2016-01-28 05:22:45 -08001081int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001082 if (cached_send_codec_) {
1083 codec = *cached_send_codec_;
1084 return 0;
1085 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001086 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1087 if (send_codec) {
1088 codec = *send_codec;
1089 return 0;
1090 }
1091 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001092 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001093}
1094
kwiberg55b97fe2016-01-28 05:22:45 -08001095int32_t Channel::GetRecCodec(CodecInst& codec) {
1096 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001097}
1098
kwiberg55b97fe2016-01-28 05:22:45 -08001099int32_t Channel::SetSendCodec(const CodecInst& codec) {
1100 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1101 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001102
kwibergc8d071e2016-04-06 12:22:38 -07001103 if (!codec_manager_.RegisterEncoder(codec) ||
1104 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001105 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1106 "SetSendCodec() failed to register codec to ACM");
1107 return -1;
1108 }
1109
1110 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1111 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1112 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1113 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1114 "SetSendCodec() failed to register codec to"
1115 " RTP/RTCP module");
1116 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001117 }
kwiberg55b97fe2016-01-28 05:22:45 -08001118 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001119
ossu76d29f92017-06-09 07:30:13 -07001120 cached_send_codec_.reset();
1121
kwiberg55b97fe2016-01-28 05:22:45 -08001122 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001123}
1124
minyue78b4d562016-11-30 04:47:39 -08001125void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001126 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1127 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001128 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001129 if (*encoder) {
1130 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001131 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001132 }
1133 });
michaelt566d8202017-01-12 10:17:38 -08001134 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001135}
1136
elad.alond12a8e12017-03-23 11:04:48 -07001137void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1138 if (!use_twcc_plr_for_ana_)
1139 return;
minyue7e304322016-10-12 05:00:55 -07001140 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001141 if (*encoder) {
1142 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1143 }
1144 });
1145}
1146
elad.alondadb4dc2017-03-23 15:29:50 -07001147void Channel::OnRecoverableUplinkPacketLossRate(
1148 float recoverable_packet_loss_rate) {
1149 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1150 if (*encoder) {
1151 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1152 recoverable_packet_loss_rate);
1153 }
1154 });
1155}
1156
elad.alond12a8e12017-03-23 11:04:48 -07001157void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1158 if (use_twcc_plr_for_ana_)
1159 return;
1160 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1161 if (*encoder) {
1162 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1163 }
minyue7e304322016-10-12 05:00:55 -07001164 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001165}
1166
kwiberg1c07c702017-03-27 07:15:49 -07001167void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1168 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1169 audio_coding_->SetReceiveCodecs(codecs);
1170}
1171
minyue7e304322016-10-12 05:00:55 -07001172bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1173 bool success = false;
1174 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1175 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001176 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1177 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001178 }
1179 });
1180 return success;
1181}
1182
1183void Channel::DisableAudioNetworkAdaptor() {
1184 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1185 if (*encoder)
1186 (*encoder)->DisableAudioNetworkAdaptor();
1187 });
1188}
1189
1190void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1191 int max_frame_length_ms) {
1192 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1193 if (*encoder) {
1194 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1195 max_frame_length_ms);
1196 }
1197 });
1198}
1199
mflodman3d7db262016-04-29 00:57:13 -07001200int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001201 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001202 "Channel::RegisterExternalTransport()");
1203
kwiberg55b97fe2016-01-28 05:22:45 -08001204 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001205 if (_externalTransport) {
1206 _engineStatisticsPtr->SetLastError(
1207 VE_INVALID_OPERATION, kTraceError,
1208 "RegisterExternalTransport() external transport already enabled");
1209 return -1;
1210 }
1211 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001212 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001213 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001214}
1215
kwiberg55b97fe2016-01-28 05:22:45 -08001216int32_t Channel::DeRegisterExternalTransport() {
1217 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1218 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001219
kwiberg55b97fe2016-01-28 05:22:45 -08001220 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001221 if (_transportPtr) {
1222 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1223 "DeRegisterExternalTransport() all transport is disabled");
1224 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001225 _engineStatisticsPtr->SetLastError(
1226 VE_INVALID_OPERATION, kTraceWarning,
1227 "DeRegisterExternalTransport() external transport already "
1228 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001229 }
1230 _externalTransport = false;
1231 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001232 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001233}
1234
nisse657bab22017-02-21 06:28:10 -08001235void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1236 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg946d8862017-09-21 04:02:53 -07001237 "Channel::OnRtpPacket()");
nisse657bab22017-02-21 06:28:10 -08001238
1239 RTPHeader header;
1240 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -07001241
1242 // Store playout timestamp for the received RTP packet
1243 UpdatePlayoutTimestamp(false);
1244
1245 header.payload_type_frequency =
1246 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1247 if (header.payload_type_frequency >= 0) {
1248 bool in_order = IsPacketInOrder(header);
1249 rtp_receive_statistics_->IncomingPacket(
1250 header, packet.size(), IsPacketRetransmitted(header, in_order));
1251 rtp_payload_registry_->SetIncomingPayloadType(header);
1252
1253 ReceivePacket(packet.data(), packet.size(), header, in_order);
1254 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001255}
1256
1257bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001258 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001259 const RTPHeader& header,
1260 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001261 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001262 assert(packet_length >= header.headerLength);
1263 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001264 const auto pl =
1265 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1266 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001267 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001268 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001269 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Karl Wiberg73b60b82017-09-21 15:00:58 +02001270 pl->typeSpecific, in_order);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001271}
1272
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001273bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1274 StreamStatistician* statistician =
1275 rtp_receive_statistics_->GetStatistician(header.ssrc);
1276 if (!statistician)
1277 return false;
1278 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001279}
1280
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001281bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1282 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001283 StreamStatistician* statistician =
1284 rtp_receive_statistics_->GetStatistician(header.ssrc);
1285 if (!statistician)
1286 return false;
1287 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001288 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001289 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001290 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001291}
1292
mflodman3d7db262016-04-29 00:57:13 -07001293int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001294 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001295 "Channel::ReceivedRTCPPacket()");
1296 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001297 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001298
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001299 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001300 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001301
Minyue2013aec2015-05-13 14:14:42 +02001302 int64_t rtt = GetRTT(true);
1303 if (rtt == 0) {
1304 // Waiting for valid RTT.
1305 return 0;
1306 }
Erik Språng737336d2016-07-29 12:59:36 +02001307
1308 int64_t nack_window_ms = rtt;
1309 if (nack_window_ms < kMinRetransmissionWindowMs) {
1310 nack_window_ms = kMinRetransmissionWindowMs;
1311 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1312 nack_window_ms = kMaxRetransmissionWindowMs;
1313 }
1314 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1315
minyue7e304322016-10-12 05:00:55 -07001316 // Invoke audio encoders OnReceivedRtt().
1317 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1318 if (*encoder)
1319 (*encoder)->OnReceivedRtt(rtt);
1320 });
1321
Minyue2013aec2015-05-13 14:14:42 +02001322 uint32_t ntp_secs = 0;
1323 uint32_t ntp_frac = 0;
1324 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001325 if (0 !=
1326 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1327 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001328 // Waiting for RTCP.
1329 return 0;
1330 }
1331
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001332 {
tommi31fc21f2016-01-21 10:37:37 -08001333 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001334 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001335 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001336 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001337}
1338
solenberg8d73f8c2017-03-08 01:52:20 -08001339int Channel::GetSpeechOutputLevel() const {
1340 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001341}
1342
solenberg8d73f8c2017-03-08 01:52:20 -08001343int Channel::GetSpeechOutputLevelFullRange() const {
1344 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001345}
1346
zsteine76bd3a2017-07-14 12:17:49 -07001347double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001348 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001349}
1350
1351double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001352 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001353}
1354
solenberg8d73f8c2017-03-08 01:52:20 -08001355void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001356 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001357 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001358}
1359
solenberg1c2af8e2016-03-24 10:36:00 -07001360bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001361 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001362 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001363}
1364
solenberg8d73f8c2017-03-08 01:52:20 -08001365void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001366 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001367 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001368}
1369
solenberg8842c3e2016-03-11 03:06:41 -08001370int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001371 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001372 "Channel::SendTelephoneEventOutband(...)");
1373 RTC_DCHECK_LE(0, event);
1374 RTC_DCHECK_GE(255, event);
1375 RTC_DCHECK_LE(0, duration_ms);
1376 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001377 if (!Sending()) {
1378 return -1;
1379 }
solenberg8842c3e2016-03-11 03:06:41 -08001380 if (_rtpRtcpModule->SendTelephoneEventOutband(
1381 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001382 _engineStatisticsPtr->SetLastError(
1383 VE_SEND_DTMF_FAILED, kTraceWarning,
1384 "SendTelephoneEventOutband() failed to send event");
1385 return -1;
1386 }
1387 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001388}
1389
solenbergffbbcac2016-11-17 05:25:37 -08001390int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1391 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001392 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001393 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001394 RTC_DCHECK_LE(0, payload_type);
1395 RTC_DCHECK_GE(127, payload_type);
1396 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001397 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001398 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001399 memcpy(codec.plname, "telephone-event", 16);
1400 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1401 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1402 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1403 _engineStatisticsPtr->SetLastError(
1404 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1405 "SetSendTelephoneEventPayloadType() failed to register send"
1406 "payload type");
1407 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001408 }
kwiberg55b97fe2016-01-28 05:22:45 -08001409 }
kwiberg55b97fe2016-01-28 05:22:45 -08001410 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001411}
1412
kwiberg55b97fe2016-01-28 05:22:45 -08001413int Channel::SetLocalSSRC(unsigned int ssrc) {
1414 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1415 "Channel::SetLocalSSRC()");
1416 if (channel_state_.Get().sending) {
1417 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
1418 "SetLocalSSRC() already sending");
1419 return -1;
1420 }
1421 _rtpRtcpModule->SetSSRC(ssrc);
1422 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001423}
1424
kwiberg55b97fe2016-01-28 05:22:45 -08001425int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1426 ssrc = rtp_receiver_->SSRC();
1427 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001428}
1429
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001430int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001431 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001432 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001433}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001434
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001435int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1436 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001437 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1438 if (enable &&
1439 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1440 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001441 return -1;
1442 }
1443 return 0;
1444}
1445
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001446void Channel::EnableSendTransportSequenceNumber(int id) {
1447 int ret =
1448 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1449 RTC_DCHECK_EQ(0, ret);
1450}
1451
stefan3313ec92016-01-21 06:32:43 -08001452void Channel::EnableReceiveTransportSequenceNumber(int id) {
1453 rtp_header_parser_->DeregisterRtpHeaderExtension(
1454 kRtpExtensionTransportSequenceNumber);
1455 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1456 kRtpExtensionTransportSequenceNumber, id);
1457 RTC_DCHECK(ret);
1458}
1459
stefanbba9dec2016-02-01 04:39:55 -08001460void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001461 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001462 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001463 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1464 TransportFeedbackObserver* transport_feedback_observer =
1465 transport->transport_feedback_observer();
1466 PacketRouter* packet_router = transport->packet_router();
1467
stefanbba9dec2016-02-01 04:39:55 -08001468 RTC_DCHECK(rtp_packet_sender);
1469 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001470 RTC_DCHECK(packet_router);
1471 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001472 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001473 feedback_observer_proxy_->SetTransportFeedbackObserver(
1474 transport_feedback_observer);
1475 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1476 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1477 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001478 constexpr bool remb_candidate = false;
1479 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001480 packet_router_ = packet_router;
1481}
1482
stefanbba9dec2016-02-01 04:39:55 -08001483void Channel::RegisterReceiverCongestionControlObjects(
1484 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001485 RTC_DCHECK(packet_router);
1486 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001487 constexpr bool remb_candidate = false;
1488 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001489 packet_router_ = packet_router;
1490}
1491
nissefdbfdc92017-03-31 05:44:52 -07001492void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001493 RTC_DCHECK(packet_router_);
1494 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001495 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001496 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1497 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001498 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001499 packet_router_ = nullptr;
1500 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1501}
1502
nissefdbfdc92017-03-31 05:44:52 -07001503void Channel::ResetReceiverCongestionControlObjects() {
1504 RTC_DCHECK(packet_router_);
1505 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1506 packet_router_ = nullptr;
1507}
1508
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001509void Channel::SetRTCPStatus(bool enable) {
1510 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1511 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001512 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001513}
1514
kwiberg55b97fe2016-01-28 05:22:45 -08001515int Channel::SetRTCP_CNAME(const char cName[256]) {
1516 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1517 "Channel::SetRTCP_CNAME()");
1518 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
1519 _engineStatisticsPtr->SetLastError(
1520 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1521 "SetRTCP_CNAME() failed to set RTCP CNAME");
1522 return -1;
1523 }
1524 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001525}
1526
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001527int Channel::GetRemoteRTCPReportBlocks(
1528 std::vector<ReportBlock>* report_blocks) {
1529 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08001530 _engineStatisticsPtr->SetLastError(
1531 VE_INVALID_ARGUMENT, kTraceError,
1532 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001533 return -1;
1534 }
1535
1536 // Get the report blocks from the latest received RTCP Sender or Receiver
1537 // Report. Each element in the vector contains the sender's SSRC and a
1538 // report block according to RFC 3550.
1539 std::vector<RTCPReportBlock> rtcp_report_blocks;
1540 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001541 return -1;
1542 }
1543
1544 if (rtcp_report_blocks.empty())
1545 return 0;
1546
1547 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1548 for (; it != rtcp_report_blocks.end(); ++it) {
1549 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001550 report_block.sender_SSRC = it->sender_ssrc;
1551 report_block.source_SSRC = it->source_ssrc;
1552 report_block.fraction_lost = it->fraction_lost;
1553 report_block.cumulative_num_packets_lost = it->packets_lost;
1554 report_block.extended_highest_sequence_number =
1555 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001556 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001557 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1558 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001559 report_blocks->push_back(report_block);
1560 }
1561 return 0;
1562}
1563
kwiberg55b97fe2016-01-28 05:22:45 -08001564int Channel::GetRTPStatistics(CallStatistics& stats) {
1565 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001566
kwiberg55b97fe2016-01-28 05:22:45 -08001567 // The jitter statistics is updated for each received RTP packet and is
1568 // based on received packets.
1569 RtcpStatistics statistics;
1570 StreamStatistician* statistician =
1571 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001572 if (statistician) {
1573 statistician->GetStatistics(&statistics,
1574 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001575 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001576
kwiberg55b97fe2016-01-28 05:22:45 -08001577 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001578 stats.cumulativeLost = statistics.packets_lost;
1579 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001580 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001581
kwiberg55b97fe2016-01-28 05:22:45 -08001582 // --- RTT
1583 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001584
kwiberg55b97fe2016-01-28 05:22:45 -08001585 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001586
kwiberg55b97fe2016-01-28 05:22:45 -08001587 size_t bytesSent(0);
1588 uint32_t packetsSent(0);
1589 size_t bytesReceived(0);
1590 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001591
kwiberg55b97fe2016-01-28 05:22:45 -08001592 if (statistician) {
1593 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1594 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001595
kwiberg55b97fe2016-01-28 05:22:45 -08001596 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
1597 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1598 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
1599 " output will not be complete");
1600 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001601
kwiberg55b97fe2016-01-28 05:22:45 -08001602 stats.bytesSent = bytesSent;
1603 stats.packetsSent = packetsSent;
1604 stats.bytesReceived = bytesReceived;
1605 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001606
kwiberg55b97fe2016-01-28 05:22:45 -08001607 // --- Timestamps
1608 {
1609 rtc::CritScope lock(&ts_stats_lock_);
1610 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1611 }
1612 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001613}
1614
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001615void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1616 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001617 // If pacing is enabled we always store packets.
1618 if (!pacing_enabled_)
1619 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001620 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001621 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001622 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001623 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001624 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001625}
1626
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001627// Called when we are missing one or more packets.
1628int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001629 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1630}
1631
henrikaec6fbd22017-03-31 05:43:36 -07001632void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001633 // Avoid posting any new tasks if sending was already stopped in StopSend().
1634 rtc::CritScope cs(&encoder_queue_lock_);
1635 if (!encoder_queue_is_active_) {
1636 return;
1637 }
henrikaec6fbd22017-03-31 05:43:36 -07001638 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1639 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1640 // either into pool of frames or into the task itself.
1641 audio_frame->CopyFrom(audio_input);
henrikaec6fbd22017-03-31 05:43:36 -07001642 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1643 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001644}
1645
henrikaec6fbd22017-03-31 05:43:36 -07001646void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1647 int sample_rate,
1648 size_t number_of_frames,
1649 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001650 // Avoid posting as new task if sending was already stopped in StopSend().
1651 rtc::CritScope cs(&encoder_queue_lock_);
1652 if (!encoder_queue_is_active_) {
1653 return;
1654 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001655 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001656 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001657 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
ossu950c1c92017-07-11 08:19:31 -07001658 // TODO(ossu): Investigate how this could happen. b/62909493
1659 if (result == 0) {
1660 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1661 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1662 } else {
1663 audio_frame->sample_rate_hz_ = sample_rate;
1664 audio_frame->num_channels_ = number_of_channels;
1665 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1666 RTC_NOTREACHED();
1667 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001668 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001669 sample_rate, &input_resampler_, audio_frame.get());
1670 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1671 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001672}
1673
henrikaec6fbd22017-03-31 05:43:36 -07001674void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1675 RTC_DCHECK_RUN_ON(encoder_queue_);
1676 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1677 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001678
henrikaec6fbd22017-03-31 05:43:36 -07001679 bool is_muted = InputMute();
1680 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001681
kwiberg55b97fe2016-01-28 05:22:45 -08001682 if (_includeAudioLevelIndication) {
1683 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001684 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001685 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001686 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001687 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001688 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001689 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001690 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001691 }
kwiberg55b97fe2016-01-28 05:22:45 -08001692 }
solenberg1c2af8e2016-03-24 10:36:00 -07001693 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001694
henrikaec6fbd22017-03-31 05:43:36 -07001695 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001696
kwiberg55b97fe2016-01-28 05:22:45 -08001697 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001698 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001699 // This call will trigger AudioPacketizationCallback::SendData if encoding
1700 // is done and payload is ready for packetization and transmission.
1701 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001702 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1703 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1704 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001705 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001706
henrikaec6fbd22017-03-31 05:43:36 -07001707 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001708}
1709
solenberg7602aab2016-11-14 11:30:07 -08001710void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1711 RTC_DCHECK(!channel.channel() ||
1712 channel.channel()->ChannelId() != _channelId);
1713 rtc::CritScope lock(&assoc_send_channel_lock_);
1714 associate_send_channel_ = channel;
1715}
1716
Minyue2013aec2015-05-13 14:14:42 +02001717void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001718 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001719 Channel* channel = associate_send_channel_.channel();
1720 if (channel && channel->ChannelId() == channel_id) {
1721 // If this channel is associated with a send channel of the specified
1722 // Channel ID, disassociate with it.
1723 ChannelOwner ref(NULL);
1724 associate_send_channel_ = ref;
1725 }
1726}
1727
ivoc14d5dbe2016-07-04 07:06:55 -07001728void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1729 event_log_proxy_->SetEventLog(event_log);
1730}
1731
michaelt9332b7d2016-11-30 07:51:13 -08001732void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1733 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1734}
1735
nisse284542b2017-01-10 08:58:32 -08001736void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001737 size_t overhead_per_packet =
1738 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001739 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1740 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001741 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001742 }
1743 });
1744}
1745
1746void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001747 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001748 transport_overhead_per_packet_ = transport_overhead_per_packet;
1749 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001750}
1751
hbos3fd31fe2017-02-28 05:43:16 -08001752// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001753void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001754 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001755 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1756 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001757}
1758
kwiberg55b97fe2016-01-28 05:22:45 -08001759int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1760 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001761}
1762
wu@webrtc.org24301a62013-12-13 19:17:43 +00001763void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1764 audio_coding_->GetDecodingCallStatistics(stats);
1765}
1766
ivoce1198e02017-09-08 08:13:19 -07001767ANAStats Channel::GetANAStatistics() const {
1768 return audio_coding_->GetANAStats();
1769}
1770
solenberg358057b2015-11-27 10:46:42 -08001771uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001772 rtc::CritScope lock(&video_sync_lock_);
1773 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001774}
1775
kwiberg55b97fe2016-01-28 05:22:45 -08001776int Channel::SetMinimumPlayoutDelay(int delayMs) {
1777 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1778 "Channel::SetMinimumPlayoutDelay()");
1779 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1780 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
1781 _engineStatisticsPtr->SetLastError(
1782 VE_INVALID_ARGUMENT, kTraceError,
1783 "SetMinimumPlayoutDelay() invalid min delay");
1784 return -1;
1785 }
1786 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
1787 _engineStatisticsPtr->SetLastError(
1788 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1789 "SetMinimumPlayoutDelay() failed to set min playout delay");
1790 return -1;
1791 }
1792 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001793}
1794
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001795int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001796 uint32_t playout_timestamp_rtp = 0;
1797 {
tommi31fc21f2016-01-21 10:37:37 -08001798 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001799 playout_timestamp_rtp = playout_timestamp_rtp_;
1800 }
kwiberg55b97fe2016-01-28 05:22:45 -08001801 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001802 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07001803 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001804 "GetPlayoutTimestamp() failed to retrieve timestamp");
1805 return -1;
1806 }
deadbeef74375882015-08-13 12:09:10 -07001807 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001808 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001809}
1810
kwiberg55b97fe2016-01-28 05:22:45 -08001811int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1812 RtpReceiver** rtp_receiver) const {
1813 *rtpRtcpModule = _rtpRtcpModule.get();
1814 *rtp_receiver = rtp_receiver_.get();
1815 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001816}
1817
deadbeef74375882015-08-13 12:09:10 -07001818void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001819 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001820
henrik.lundin96bd5022016-04-06 04:13:56 -07001821 if (!jitter_buffer_playout_timestamp_) {
1822 // This can happen if this channel has not received any RTP packets. In
1823 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001824 return;
1825 }
1826
1827 uint16_t delay_ms = 0;
1828 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001829 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001830 "Channel::UpdatePlayoutTimestamp() failed to read playout"
1831 " delay from the ADM");
1832 _engineStatisticsPtr->SetLastError(
1833 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
1834 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
1835 return;
1836 }
1837
henrik.lundin96bd5022016-04-06 04:13:56 -07001838 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1839 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001840
1841 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001842 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001843
kwiberg55b97fe2016-01-28 05:22:45 -08001844 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001845 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07001846 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07001847
1848 {
tommi31fc21f2016-01-21 10:37:37 -08001849 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001850 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001851 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001852 }
1853 playout_delay_ms_ = delay_ms;
1854 }
1855}
1856
kwiberg55b97fe2016-01-28 05:22:45 -08001857void Channel::RegisterReceiveCodecsToRTPModule() {
1858 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1859 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001860
kwiberg55b97fe2016-01-28 05:22:45 -08001861 CodecInst codec;
1862 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00001863
kwiberg55b97fe2016-01-28 05:22:45 -08001864 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1865 // Open up the RTP/RTCP receiver for all supported codecs
1866 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001867 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001868 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1869 "Channel::RegisterReceiveCodecsToRTPModule() unable"
1870 " to register %s (%d/%d/%" PRIuS
1871 "/%d) to RTP/RTCP "
1872 "receiver",
1873 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1874 codec.rate);
1875 } else {
1876 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1877 "Channel::RegisterReceiveCodecsToRTPModule() %s "
1878 "(%d/%d/%" PRIuS
1879 "/%d) has been added to the RTP/RTCP "
1880 "receiver",
1881 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1882 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001883 }
kwiberg55b97fe2016-01-28 05:22:45 -08001884 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001885}
1886
kwiberg55b97fe2016-01-28 05:22:45 -08001887int Channel::SetSendRtpHeaderExtension(bool enable,
1888 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001889 unsigned char id) {
1890 int error = 0;
1891 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1892 if (enable) {
1893 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1894 }
1895 return error;
1896}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001897
ossue280cde2016-10-12 11:04:10 -07001898int Channel::GetRtpTimestampRateHz() const {
1899 const auto format = audio_coding_->ReceiveFormat();
1900 // Default to the playout frequency if we've not gotten any packets yet.
1901 // TODO(ossu): Zero clockrate can only happen if we've added an external
1902 // decoder for a format we don't support internally. Remove once that way of
1903 // adding decoders is gone!
1904 return (format && format->clockrate_hz != 0)
1905 ? format->clockrate_hz
1906 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001907}
1908
Minyue2013aec2015-05-13 14:14:42 +02001909int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001910 RtcpMode method = _rtpRtcpModule->RTCP();
1911 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001912 return 0;
1913 }
1914 std::vector<RTCPReportBlock> report_blocks;
1915 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001916
1917 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001918 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001919 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001920 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001921 Channel* channel = associate_send_channel_.channel();
1922 // Tries to get RTT from an associated channel. This is important for
1923 // receive-only channels.
1924 if (channel) {
1925 // To prevent infinite recursion and deadlock, calling GetRTT of
1926 // associate channel should always use "false" for argument:
1927 // |allow_associate_channel|.
1928 rtt = channel->GetRTT(false);
1929 }
1930 }
1931 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001932 }
1933
1934 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1935 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1936 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001937 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001938 break;
1939 }
1940 if (it == report_blocks.end()) {
1941 // We have not received packets with SSRC matching the report blocks.
1942 // To calculate RTT we try with the SSRC of the first report block.
1943 // This is very important for send-only channels where we don't know
1944 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001945 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001946 }
Minyue2013aec2015-05-13 14:14:42 +02001947
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001948 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001949 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001950 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001951 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1952 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001953 return 0;
1954 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001955 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001956}
1957
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001958} // namespace voe
1959} // namespace webrtc