blob: aaca65a36dd65a63384d8e93e32c21af4fd1637d [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 // Convert module ID to internal VoE channel ID
solenberg2397b9a2017-09-22 06:48:10 -0700650 audio_frame->id_ = VoEChannelId(audio_frame->id_);
kwiberg55b97fe2016-01-28 05:22:45 -0800651 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700652 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800653
kwiberg55b97fe2016-01-28 05:22:45 -0800654 {
655 // Pass the audio buffers to an optional sink callback, before applying
656 // scaling/panning, as that applies to the mix operation.
657 // External recipients of the audio (e.g. via AudioTrack), will do their
658 // own mixing/dynamic processing.
659 rtc::CritScope cs(&_callbackCritSect);
660 if (audio_sink_) {
661 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700662 audio_frame->data(), audio_frame->samples_per_channel_,
663 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
664 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800665 audio_sink_->OnData(data);
666 }
667 }
668
669 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800670 {
671 rtc::CritScope cs(&volume_settings_critsect_);
672 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800673 }
674
675 // Output volume scaling
676 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800677 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700678 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800679 }
680
kwiberg55b97fe2016-01-28 05:22:45 -0800681 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700682 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700683 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700684 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700685 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800686
solenberg2397b9a2017-09-22 06:48:10 -0700687 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800688 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700689 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800690 }
691
692 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700693 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800694
695 // Compute elapsed time.
696 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700697 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
698 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800699 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700700 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800701
niklase@google.com470e71d2011-07-07 08:21:25 +0000702 {
kwiberg55b97fe2016-01-28 05:22:45 -0800703 rtc::CritScope lock(&ts_stats_lock_);
704 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700705 audio_frame->ntp_time_ms_ =
706 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800707 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700708 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800709 // Compute |capture_start_ntp_time_ms_| so that
710 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
711 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700712 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000713 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000714 }
kwiberg55b97fe2016-01-28 05:22:45 -0800715 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000716
solenberg2397b9a2017-09-22 06:48:10 -0700717 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
718 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000719}
720
solenberg2397b9a2017-09-22 06:48:10 -0700721int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800722 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700723 return std::max(audio_coding_->ReceiveFrequency(),
724 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
henrikaec6fbd22017-03-31 05:43:36 -0700727int32_t Channel::CreateChannel(Channel*& channel,
728 int32_t channelId,
729 uint32_t instanceId,
730 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800731 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
732 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
733 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000734
solenberg88499ec2016-09-07 07:34:41 -0700735 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800736 if (channel == NULL) {
737 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
738 "Channel::CreateChannel() unable to allocate memory for"
739 " channel");
740 return -1;
741 }
742 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000743}
744
pbos@webrtc.org92135212013-05-14 08:31:39 +0000745Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000746 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700747 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800748 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100749 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700750 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800751 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100752 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800753 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100754 rtp_receive_statistics_(
755 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
756 rtp_receiver_(
757 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100758 this,
759 this,
760 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700761 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100762 _outputAudioLevel(),
763 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100764 _timeStamp(0), // This is just an offset, RTP module will add it's own
765 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100766 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100767 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100768 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100769 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100770 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
771 capture_start_rtp_time_stamp_(-1),
772 capture_start_ntp_time_ms_(-1),
773 _engineStatisticsPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100774 _moduleProcessThreadPtr(NULL),
775 _audioDeviceModulePtr(NULL),
776 _voiceEngineObserverPtr(NULL),
777 _callbackCritSectPtr(NULL),
778 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700779 input_mute_(false),
780 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100781 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100782 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800783 transport_overhead_per_packet_(0),
784 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100785 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100786 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100787 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700788 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800789 feedback_observer_proxy_(new TransportFeedbackProxy()),
790 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700791 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200792 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
793 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700794 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700795 use_twcc_plr_for_ana_(
796 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800797 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
798 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700799 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800800 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700801 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800802 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200803
kwiberg55b97fe2016-01-28 05:22:45 -0800804 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000805
kwiberg55b97fe2016-01-28 05:22:45 -0800806 RtpRtcp::Configuration configuration;
807 configuration.audio = true;
808 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800809 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800810 configuration.receive_statistics = rtp_receive_statistics_.get();
811 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800812 if (pacing_enabled_) {
813 configuration.paced_sender = rtp_packet_sender_proxy_.get();
814 configuration.transport_sequence_number_allocator =
815 seq_num_allocator_proxy_.get();
816 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
817 }
ivoc14d5dbe2016-07-04 07:06:55 -0700818 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800819 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200820 configuration.retransmission_rate_limiter =
821 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000822
kwiberg55b97fe2016-01-28 05:22:45 -0800823 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100824 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000825}
826
kwiberg55b97fe2016-01-28 05:22:45 -0800827Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700828 RTC_DCHECK(!channel_state_.Get().sending);
829 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000830}
831
kwiberg55b97fe2016-01-28 05:22:45 -0800832int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700833 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800834 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
835 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000836
kwiberg55b97fe2016-01-28 05:22:45 -0800837 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000838
kwiberg55b97fe2016-01-28 05:22:45 -0800839 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000840
kwiberg55b97fe2016-01-28 05:22:45 -0800841 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
842 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
843 "Channel::Init() must call SetEngineInformation() first");
844 return -1;
845 }
846
847 // --- Add modules to process thread (for periodic schedulation)
848
tommidea489f2017-03-03 03:20:24 -0800849 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800850
851 // --- ACM initialization
852
853 if (audio_coding_->InitializeReceiver() == -1) {
854 _engineStatisticsPtr->SetLastError(
855 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
856 "Channel::Init() unable to initialize the ACM - 1");
857 return -1;
858 }
859
860 // --- RTP/RTCP module initialization
861
862 // Ensure that RTCP is enabled by default for the created channel.
863 // Note that, the module will keep generating RTCP until it is explicitly
864 // disabled by the user.
865 // After StopListen (when no sockets exists), RTCP packets will no longer
866 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700867 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800868 // RTCP is enabled by default.
869 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
870 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800871 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800872 _engineStatisticsPtr->SetLastError(
873 VE_CANNOT_INIT_CHANNEL, kTraceError,
874 "Channel::Init() callbacks not registered");
875 return -1;
876 }
877
solenberg6dc20382017-09-18 05:22:39 -0700878 // TODO(solenberg): Remove?
kwiberg1c07c702017-03-27 07:15:49 -0700879 // Register a default set of send codecs.
880 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -0800881 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -0700882 CodecInst codec;
883 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
884
885 // Ensure that PCMU is used as default send codec.
886 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
887 SetSendCodec(codec);
888 }
889
890 // Register default PT for 'telephone-event'
891 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
892 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
893 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
894 "Channel::Init() failed to register outband "
895 "'telephone-event' (%d/%d) correctly",
896 codec.pltype, codec.plfreq);
897 }
898 }
899
900 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
901 if (!codec_manager_.RegisterEncoder(codec) ||
902 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
903 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
904 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
905 "Channel::Init() failed to register CN (%d/%d) "
906 "correctly - 1",
907 codec.pltype, codec.plfreq);
908 }
909 }
910 }
911
912 return 0;
913}
914
tommi0a2391f2017-03-21 02:31:51 -0700915void Channel::Terminate() {
916 RTC_DCHECK(construction_thread_.CalledOnValidThread());
917 // Must be called on the same thread as Init().
918 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
919 "Channel::Terminate");
920
921 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
922
923 StopSend();
924 StopPlayout();
925
tommi0a2391f2017-03-21 02:31:51 -0700926 // The order to safely shutdown modules in a channel is:
927 // 1. De-register callbacks in modules
928 // 2. De-register modules in process thread
929 // 3. Destroy modules
930 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
931 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
932 "Terminate() failed to de-register transport callback"
933 " (Audio coding module)");
934 }
935
936 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
937 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
938 "Terminate() failed to de-register VAD callback"
939 " (Audio coding module)");
940 }
941
942 // De-register modules in process thread
943 if (_moduleProcessThreadPtr)
944 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
945
946 // End of modules shutdown
947}
948
kwiberg55b97fe2016-01-28 05:22:45 -0800949int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
kwiberg55b97fe2016-01-28 05:22:45 -0800950 ProcessThread& moduleProcessThread,
951 AudioDeviceModule& audioDeviceModule,
952 VoiceEngineObserver* voiceEngineObserver,
henrikaec6fbd22017-03-31 05:43:36 -0700953 rtc::CriticalSection* callbackCritSect,
954 rtc::TaskQueue* encoder_queue) {
955 RTC_DCHECK(encoder_queue);
956 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800957 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
958 "Channel::SetEngineInformation()");
959 _engineStatisticsPtr = &engineStatistics;
kwiberg55b97fe2016-01-28 05:22:45 -0800960 _moduleProcessThreadPtr = &moduleProcessThread;
961 _audioDeviceModulePtr = &audioDeviceModule;
962 _voiceEngineObserverPtr = voiceEngineObserver;
963 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -0700964 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800965 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000966}
967
kwibergb7f89d62016-02-17 10:04:18 -0800968void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800969 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800970 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100971}
972
ossu29b1a8d2016-06-13 07:34:51 -0700973const rtc::scoped_refptr<AudioDecoderFactory>&
974Channel::GetAudioDecoderFactory() const {
975 return decoder_factory_;
976}
977
kwiberg55b97fe2016-01-28 05:22:45 -0800978int32_t Channel::StartPlayout() {
979 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
980 "Channel::StartPlayout()");
981 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000982 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800983 }
984
kwiberg55b97fe2016-01-28 05:22:45 -0800985 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800986
987 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000988}
989
kwiberg55b97fe2016-01-28 05:22:45 -0800990int32_t Channel::StopPlayout() {
991 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
992 "Channel::StopPlayout()");
993 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000994 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800995 }
996
kwiberg55b97fe2016-01-28 05:22:45 -0800997 channel_state_.SetPlaying(false);
998 _outputAudioLevel.Clear();
999
1000 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001001}
1002
kwiberg55b97fe2016-01-28 05:22:45 -08001003int32_t Channel::StartSend() {
1004 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1005 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001006 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001007 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001008 }
1009 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -07001010 {
1011 // It is now OK to start posting tasks to the encoder task queue.
1012 rtc::CritScope cs(&encoder_queue_lock_);
1013 encoder_queue_is_active_ = true;
1014 }
solenberg08b19df2017-02-15 00:42:31 -08001015 // Resume the previous sequence number which was reset by StopSend(). This
1016 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1017 if (send_sequence_number_) {
1018 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1019 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001020 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001021 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1022 _engineStatisticsPtr->SetLastError(
1023 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1024 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001025 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001026 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001027 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001028 return -1;
1029 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001030
kwiberg55b97fe2016-01-28 05:22:45 -08001031 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001032}
1033
henrikaec6fbd22017-03-31 05:43:36 -07001034void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -08001035 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1036 "Channel::StopSend()");
1037 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -07001038 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001039 }
1040 channel_state_.SetSending(false);
1041
henrikaec6fbd22017-03-31 05:43:36 -07001042 // Post a task to the encoder thread which sets an event when the task is
1043 // executed. We know that no more encoding tasks will be added to the task
1044 // queue for this channel since sending is now deactivated. It means that,
1045 // if we wait for the event to bet set, we know that no more pending tasks
1046 // exists and it is therfore guaranteed that the task queue will never try
1047 // to acccess and invalid channel object.
1048 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001049
henrikaec6fbd22017-03-31 05:43:36 -07001050 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001051 {
1052 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1053 // than this final "flush task" to be posted on the queue.
1054 rtc::CritScope cs(&encoder_queue_lock_);
1055 encoder_queue_is_active_ = false;
1056 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1057 }
henrikaec6fbd22017-03-31 05:43:36 -07001058 flush.Wait(rtc::Event::kForever);
1059
kwiberg55b97fe2016-01-28 05:22:45 -08001060 // Store the sequence number to be able to pick up the same sequence for
1061 // the next StartSend(). This is needed for restarting device, otherwise
1062 // it might cause libSRTP to complain about packets being replayed.
1063 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1064 // CL is landed. See issue
1065 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1066 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1067
1068 // Reset sending SSRC and sequence number and triggers direct transmission
1069 // of RTCP BYE
1070 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1071 _engineStatisticsPtr->SetLastError(
1072 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1073 "StartSend() RTP/RTCP failed to stop sending");
1074 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001075 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001076}
1077
ossu1ffbd6c2017-04-06 12:05:04 -07001078bool Channel::SetEncoder(int payload_type,
1079 std::unique_ptr<AudioEncoder> encoder) {
1080 RTC_DCHECK_GE(payload_type, 0);
1081 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001082 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1083 // one for for us to keep track of sample rate and number of channels, etc.
1084
1085 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1086 // as well as some other things, so we collect this info and send it along.
1087 CodecInst rtp_codec;
1088 rtp_codec.pltype = payload_type;
1089 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1090 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001091 // Seems unclear if it should be clock rate or sample rate. CodecInst
1092 // supposedly carries the sample rate, but only clock rate seems sensible to
1093 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001094 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1095 rtp_codec.pacsize = rtc::CheckedDivExact(
1096 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1097 100);
1098 rtp_codec.channels = encoder->NumChannels();
1099 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001100
ossu76d29f92017-06-09 07:30:13 -07001101 // For audio encoding we need, instead, the actual sample rate of the codec.
1102 // The rest of the information should be the same.
1103 CodecInst send_codec = rtp_codec;
1104 send_codec.plfreq = encoder->SampleRateHz();
1105 cached_send_codec_.emplace(send_codec);
1106
1107 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001108 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001109 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001110 WEBRTC_TRACE(
1111 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1112 "SetEncoder() failed to register codec to RTP/RTCP module");
1113 return false;
1114 }
1115 }
1116
1117 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001118 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001119 return true;
1120}
1121
ossu20a4b3f2017-04-27 02:08:52 -07001122void Channel::ModifyEncoder(
1123 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1124 audio_coding_->ModifyEncoder(modifier);
1125}
1126
kwiberg55b97fe2016-01-28 05:22:45 -08001127int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1128 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1129 "Channel::RegisterVoiceEngineObserver()");
1130 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001131
kwiberg55b97fe2016-01-28 05:22:45 -08001132 if (_voiceEngineObserverPtr) {
1133 _engineStatisticsPtr->SetLastError(
1134 VE_INVALID_OPERATION, kTraceError,
1135 "RegisterVoiceEngineObserver() observer already enabled");
1136 return -1;
1137 }
1138 _voiceEngineObserverPtr = &observer;
1139 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001140}
1141
kwiberg55b97fe2016-01-28 05:22:45 -08001142int32_t Channel::DeRegisterVoiceEngineObserver() {
1143 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1144 "Channel::DeRegisterVoiceEngineObserver()");
1145 rtc::CritScope cs(&_callbackCritSect);
1146
1147 if (!_voiceEngineObserverPtr) {
1148 _engineStatisticsPtr->SetLastError(
1149 VE_INVALID_OPERATION, kTraceWarning,
1150 "DeRegisterVoiceEngineObserver() observer already disabled");
1151 return 0;
1152 }
1153 _voiceEngineObserverPtr = NULL;
1154 return 0;
1155}
1156
1157int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001158 if (cached_send_codec_) {
1159 codec = *cached_send_codec_;
1160 return 0;
1161 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001162 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1163 if (send_codec) {
1164 codec = *send_codec;
1165 return 0;
1166 }
1167 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001168 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001169}
1170
kwiberg55b97fe2016-01-28 05:22:45 -08001171int32_t Channel::GetRecCodec(CodecInst& codec) {
1172 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001173}
1174
kwiberg55b97fe2016-01-28 05:22:45 -08001175int32_t Channel::SetSendCodec(const CodecInst& codec) {
1176 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1177 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001178
kwibergc8d071e2016-04-06 12:22:38 -07001179 if (!codec_manager_.RegisterEncoder(codec) ||
1180 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001181 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1182 "SetSendCodec() failed to register codec to ACM");
1183 return -1;
1184 }
1185
1186 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1187 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1188 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1189 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1190 "SetSendCodec() failed to register codec to"
1191 " RTP/RTCP module");
1192 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001193 }
kwiberg55b97fe2016-01-28 05:22:45 -08001194 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001195
ossu76d29f92017-06-09 07:30:13 -07001196 cached_send_codec_.reset();
1197
kwiberg55b97fe2016-01-28 05:22:45 -08001198 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001199}
1200
minyue78b4d562016-11-30 04:47:39 -08001201void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001202 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1203 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001204 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001205 if (*encoder) {
1206 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001207 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001208 }
1209 });
michaelt566d8202017-01-12 10:17:38 -08001210 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001211}
1212
elad.alond12a8e12017-03-23 11:04:48 -07001213void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1214 if (!use_twcc_plr_for_ana_)
1215 return;
minyue7e304322016-10-12 05:00:55 -07001216 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001217 if (*encoder) {
1218 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1219 }
1220 });
1221}
1222
elad.alondadb4dc2017-03-23 15:29:50 -07001223void Channel::OnRecoverableUplinkPacketLossRate(
1224 float recoverable_packet_loss_rate) {
1225 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1226 if (*encoder) {
1227 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1228 recoverable_packet_loss_rate);
1229 }
1230 });
1231}
1232
elad.alond12a8e12017-03-23 11:04:48 -07001233void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1234 if (use_twcc_plr_for_ana_)
1235 return;
1236 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1237 if (*encoder) {
1238 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1239 }
minyue7e304322016-10-12 05:00:55 -07001240 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001241}
1242
kwiberg1c07c702017-03-27 07:15:49 -07001243void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1244 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1245 audio_coding_->SetReceiveCodecs(codecs);
1246}
1247
minyue7e304322016-10-12 05:00:55 -07001248bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1249 bool success = false;
1250 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1251 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001252 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1253 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001254 }
1255 });
1256 return success;
1257}
1258
1259void Channel::DisableAudioNetworkAdaptor() {
1260 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1261 if (*encoder)
1262 (*encoder)->DisableAudioNetworkAdaptor();
1263 });
1264}
1265
1266void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1267 int max_frame_length_ms) {
1268 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1269 if (*encoder) {
1270 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1271 max_frame_length_ms);
1272 }
1273 });
1274}
1275
mflodman3d7db262016-04-29 00:57:13 -07001276int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001277 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001278 "Channel::RegisterExternalTransport()");
1279
kwiberg55b97fe2016-01-28 05:22:45 -08001280 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001281 if (_externalTransport) {
1282 _engineStatisticsPtr->SetLastError(
1283 VE_INVALID_OPERATION, kTraceError,
1284 "RegisterExternalTransport() external transport already enabled");
1285 return -1;
1286 }
1287 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001288 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001289 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001290}
1291
kwiberg55b97fe2016-01-28 05:22:45 -08001292int32_t Channel::DeRegisterExternalTransport() {
1293 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1294 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001295
kwiberg55b97fe2016-01-28 05:22:45 -08001296 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001297 if (_transportPtr) {
1298 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1299 "DeRegisterExternalTransport() all transport is disabled");
1300 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001301 _engineStatisticsPtr->SetLastError(
1302 VE_INVALID_OPERATION, kTraceWarning,
1303 "DeRegisterExternalTransport() external transport already "
1304 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001305 }
1306 _externalTransport = false;
1307 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001308 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001309}
1310
nisse657bab22017-02-21 06:28:10 -08001311void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1312 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg946d8862017-09-21 04:02:53 -07001313 "Channel::OnRtpPacket()");
nisse657bab22017-02-21 06:28:10 -08001314
1315 RTPHeader header;
1316 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -07001317
1318 // Store playout timestamp for the received RTP packet
1319 UpdatePlayoutTimestamp(false);
1320
1321 header.payload_type_frequency =
1322 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1323 if (header.payload_type_frequency >= 0) {
1324 bool in_order = IsPacketInOrder(header);
1325 rtp_receive_statistics_->IncomingPacket(
1326 header, packet.size(), IsPacketRetransmitted(header, in_order));
1327 rtp_payload_registry_->SetIncomingPayloadType(header);
1328
1329 ReceivePacket(packet.data(), packet.size(), header, in_order);
1330 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001331}
1332
1333bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001334 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001335 const RTPHeader& header,
1336 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001337 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001338 assert(packet_length >= header.headerLength);
1339 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001340 const auto pl =
1341 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1342 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001343 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001344 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001345 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Karl Wiberg73b60b82017-09-21 15:00:58 +02001346 pl->typeSpecific, in_order);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001347}
1348
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001349bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1350 StreamStatistician* statistician =
1351 rtp_receive_statistics_->GetStatistician(header.ssrc);
1352 if (!statistician)
1353 return false;
1354 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001355}
1356
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001357bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1358 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001359 StreamStatistician* statistician =
1360 rtp_receive_statistics_->GetStatistician(header.ssrc);
1361 if (!statistician)
1362 return false;
1363 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001364 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001365 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001366 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001367}
1368
mflodman3d7db262016-04-29 00:57:13 -07001369int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001370 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001371 "Channel::ReceivedRTCPPacket()");
1372 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001373 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001374
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001375 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001376 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001377
Minyue2013aec2015-05-13 14:14:42 +02001378 int64_t rtt = GetRTT(true);
1379 if (rtt == 0) {
1380 // Waiting for valid RTT.
1381 return 0;
1382 }
Erik Språng737336d2016-07-29 12:59:36 +02001383
1384 int64_t nack_window_ms = rtt;
1385 if (nack_window_ms < kMinRetransmissionWindowMs) {
1386 nack_window_ms = kMinRetransmissionWindowMs;
1387 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1388 nack_window_ms = kMaxRetransmissionWindowMs;
1389 }
1390 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1391
minyue7e304322016-10-12 05:00:55 -07001392 // Invoke audio encoders OnReceivedRtt().
1393 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1394 if (*encoder)
1395 (*encoder)->OnReceivedRtt(rtt);
1396 });
1397
Minyue2013aec2015-05-13 14:14:42 +02001398 uint32_t ntp_secs = 0;
1399 uint32_t ntp_frac = 0;
1400 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001401 if (0 !=
1402 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1403 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001404 // Waiting for RTCP.
1405 return 0;
1406 }
1407
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001408 {
tommi31fc21f2016-01-21 10:37:37 -08001409 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001410 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001411 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001412 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001413}
1414
solenberg8d73f8c2017-03-08 01:52:20 -08001415int Channel::GetSpeechOutputLevel() const {
1416 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001417}
1418
solenberg8d73f8c2017-03-08 01:52:20 -08001419int Channel::GetSpeechOutputLevelFullRange() const {
1420 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001421}
1422
zsteine76bd3a2017-07-14 12:17:49 -07001423double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001424 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001425}
1426
1427double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001428 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001429}
1430
solenberg8d73f8c2017-03-08 01:52:20 -08001431void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001432 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001433 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001434}
1435
solenberg1c2af8e2016-03-24 10:36:00 -07001436bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001437 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001438 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001439}
1440
solenberg8d73f8c2017-03-08 01:52:20 -08001441void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001442 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001443 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001444}
1445
solenberg8842c3e2016-03-11 03:06:41 -08001446int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001447 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001448 "Channel::SendTelephoneEventOutband(...)");
1449 RTC_DCHECK_LE(0, event);
1450 RTC_DCHECK_GE(255, event);
1451 RTC_DCHECK_LE(0, duration_ms);
1452 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001453 if (!Sending()) {
1454 return -1;
1455 }
solenberg8842c3e2016-03-11 03:06:41 -08001456 if (_rtpRtcpModule->SendTelephoneEventOutband(
1457 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001458 _engineStatisticsPtr->SetLastError(
1459 VE_SEND_DTMF_FAILED, kTraceWarning,
1460 "SendTelephoneEventOutband() failed to send event");
1461 return -1;
1462 }
1463 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001464}
1465
solenbergffbbcac2016-11-17 05:25:37 -08001466int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1467 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001468 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001469 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001470 RTC_DCHECK_LE(0, payload_type);
1471 RTC_DCHECK_GE(127, payload_type);
1472 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001473 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001474 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001475 memcpy(codec.plname, "telephone-event", 16);
1476 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1477 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1478 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1479 _engineStatisticsPtr->SetLastError(
1480 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1481 "SetSendTelephoneEventPayloadType() failed to register send"
1482 "payload type");
1483 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001484 }
kwiberg55b97fe2016-01-28 05:22:45 -08001485 }
kwiberg55b97fe2016-01-28 05:22:45 -08001486 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001487}
1488
kwiberg55b97fe2016-01-28 05:22:45 -08001489int Channel::SetLocalSSRC(unsigned int ssrc) {
1490 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1491 "Channel::SetLocalSSRC()");
1492 if (channel_state_.Get().sending) {
1493 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
1494 "SetLocalSSRC() already sending");
1495 return -1;
1496 }
1497 _rtpRtcpModule->SetSSRC(ssrc);
1498 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001499}
1500
kwiberg55b97fe2016-01-28 05:22:45 -08001501int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1502 ssrc = rtp_receiver_->SSRC();
1503 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001504}
1505
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001506int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001507 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001508 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001509}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001510
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001511int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1512 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001513 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1514 if (enable &&
1515 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1516 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001517 return -1;
1518 }
1519 return 0;
1520}
1521
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001522void Channel::EnableSendTransportSequenceNumber(int id) {
1523 int ret =
1524 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1525 RTC_DCHECK_EQ(0, ret);
1526}
1527
stefan3313ec92016-01-21 06:32:43 -08001528void Channel::EnableReceiveTransportSequenceNumber(int id) {
1529 rtp_header_parser_->DeregisterRtpHeaderExtension(
1530 kRtpExtensionTransportSequenceNumber);
1531 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1532 kRtpExtensionTransportSequenceNumber, id);
1533 RTC_DCHECK(ret);
1534}
1535
stefanbba9dec2016-02-01 04:39:55 -08001536void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001537 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001538 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001539 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1540 TransportFeedbackObserver* transport_feedback_observer =
1541 transport->transport_feedback_observer();
1542 PacketRouter* packet_router = transport->packet_router();
1543
stefanbba9dec2016-02-01 04:39:55 -08001544 RTC_DCHECK(rtp_packet_sender);
1545 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001546 RTC_DCHECK(packet_router);
1547 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001548 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001549 feedback_observer_proxy_->SetTransportFeedbackObserver(
1550 transport_feedback_observer);
1551 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1552 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1553 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001554 constexpr bool remb_candidate = false;
1555 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001556 packet_router_ = packet_router;
1557}
1558
stefanbba9dec2016-02-01 04:39:55 -08001559void Channel::RegisterReceiverCongestionControlObjects(
1560 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001561 RTC_DCHECK(packet_router);
1562 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001563 constexpr bool remb_candidate = false;
1564 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001565 packet_router_ = packet_router;
1566}
1567
nissefdbfdc92017-03-31 05:44:52 -07001568void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001569 RTC_DCHECK(packet_router_);
1570 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001571 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001572 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1573 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001574 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001575 packet_router_ = nullptr;
1576 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1577}
1578
nissefdbfdc92017-03-31 05:44:52 -07001579void Channel::ResetReceiverCongestionControlObjects() {
1580 RTC_DCHECK(packet_router_);
1581 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1582 packet_router_ = nullptr;
1583}
1584
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001585void Channel::SetRTCPStatus(bool enable) {
1586 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1587 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001588 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001589}
1590
kwiberg55b97fe2016-01-28 05:22:45 -08001591int Channel::SetRTCP_CNAME(const char cName[256]) {
1592 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1593 "Channel::SetRTCP_CNAME()");
1594 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
1595 _engineStatisticsPtr->SetLastError(
1596 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1597 "SetRTCP_CNAME() failed to set RTCP CNAME");
1598 return -1;
1599 }
1600 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001601}
1602
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001603int Channel::GetRemoteRTCPReportBlocks(
1604 std::vector<ReportBlock>* report_blocks) {
1605 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08001606 _engineStatisticsPtr->SetLastError(
1607 VE_INVALID_ARGUMENT, kTraceError,
1608 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001609 return -1;
1610 }
1611
1612 // Get the report blocks from the latest received RTCP Sender or Receiver
1613 // Report. Each element in the vector contains the sender's SSRC and a
1614 // report block according to RFC 3550.
1615 std::vector<RTCPReportBlock> rtcp_report_blocks;
1616 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001617 return -1;
1618 }
1619
1620 if (rtcp_report_blocks.empty())
1621 return 0;
1622
1623 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1624 for (; it != rtcp_report_blocks.end(); ++it) {
1625 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001626 report_block.sender_SSRC = it->sender_ssrc;
1627 report_block.source_SSRC = it->source_ssrc;
1628 report_block.fraction_lost = it->fraction_lost;
1629 report_block.cumulative_num_packets_lost = it->packets_lost;
1630 report_block.extended_highest_sequence_number =
1631 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001632 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001633 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1634 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001635 report_blocks->push_back(report_block);
1636 }
1637 return 0;
1638}
1639
kwiberg55b97fe2016-01-28 05:22:45 -08001640int Channel::GetRTPStatistics(CallStatistics& stats) {
1641 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001642
kwiberg55b97fe2016-01-28 05:22:45 -08001643 // The jitter statistics is updated for each received RTP packet and is
1644 // based on received packets.
1645 RtcpStatistics statistics;
1646 StreamStatistician* statistician =
1647 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001648 if (statistician) {
1649 statistician->GetStatistics(&statistics,
1650 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001651 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001652
kwiberg55b97fe2016-01-28 05:22:45 -08001653 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001654 stats.cumulativeLost = statistics.packets_lost;
1655 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001656 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001657
kwiberg55b97fe2016-01-28 05:22:45 -08001658 // --- RTT
1659 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001660
kwiberg55b97fe2016-01-28 05:22:45 -08001661 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001662
kwiberg55b97fe2016-01-28 05:22:45 -08001663 size_t bytesSent(0);
1664 uint32_t packetsSent(0);
1665 size_t bytesReceived(0);
1666 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001667
kwiberg55b97fe2016-01-28 05:22:45 -08001668 if (statistician) {
1669 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1670 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001671
kwiberg55b97fe2016-01-28 05:22:45 -08001672 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
1673 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1674 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
1675 " output will not be complete");
1676 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001677
kwiberg55b97fe2016-01-28 05:22:45 -08001678 stats.bytesSent = bytesSent;
1679 stats.packetsSent = packetsSent;
1680 stats.bytesReceived = bytesReceived;
1681 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001682
kwiberg55b97fe2016-01-28 05:22:45 -08001683 // --- Timestamps
1684 {
1685 rtc::CritScope lock(&ts_stats_lock_);
1686 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1687 }
1688 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001689}
1690
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001691void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1692 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001693 // If pacing is enabled we always store packets.
1694 if (!pacing_enabled_)
1695 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001696 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001697 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001698 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001699 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001700 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001701}
1702
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001703// Called when we are missing one or more packets.
1704int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001705 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1706}
1707
henrikaec6fbd22017-03-31 05:43:36 -07001708void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001709 // Avoid posting any new tasks if sending was already stopped in StopSend().
1710 rtc::CritScope cs(&encoder_queue_lock_);
1711 if (!encoder_queue_is_active_) {
1712 return;
1713 }
henrikaec6fbd22017-03-31 05:43:36 -07001714 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1715 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1716 // either into pool of frames or into the task itself.
1717 audio_frame->CopyFrom(audio_input);
1718 audio_frame->id_ = ChannelId();
1719 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1720 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001721}
1722
henrikaec6fbd22017-03-31 05:43:36 -07001723void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1724 int sample_rate,
1725 size_t number_of_frames,
1726 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001727 // Avoid posting as new task if sending was already stopped in StopSend().
1728 rtc::CritScope cs(&encoder_queue_lock_);
1729 if (!encoder_queue_is_active_) {
1730 return;
1731 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001732 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001733 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001734 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1735 audio_frame->id_ = ChannelId();
ossu950c1c92017-07-11 08:19:31 -07001736 // TODO(ossu): Investigate how this could happen. b/62909493
1737 if (result == 0) {
1738 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1739 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1740 } else {
1741 audio_frame->sample_rate_hz_ = sample_rate;
1742 audio_frame->num_channels_ = number_of_channels;
1743 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1744 RTC_NOTREACHED();
1745 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001746 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001747 sample_rate, &input_resampler_, audio_frame.get());
1748 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1749 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001750}
1751
henrikaec6fbd22017-03-31 05:43:36 -07001752void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1753 RTC_DCHECK_RUN_ON(encoder_queue_);
1754 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1755 RTC_DCHECK_LE(audio_input->num_channels_, 2);
1756 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08001757
henrikaec6fbd22017-03-31 05:43:36 -07001758 bool is_muted = InputMute();
1759 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001760
kwiberg55b97fe2016-01-28 05:22:45 -08001761 if (_includeAudioLevelIndication) {
1762 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001763 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001764 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001765 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001766 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001767 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001768 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001769 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001770 }
kwiberg55b97fe2016-01-28 05:22:45 -08001771 }
solenberg1c2af8e2016-03-24 10:36:00 -07001772 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001773
henrikaec6fbd22017-03-31 05:43:36 -07001774 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001775
kwiberg55b97fe2016-01-28 05:22:45 -08001776 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001777 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001778 // This call will trigger AudioPacketizationCallback::SendData if encoding
1779 // is done and payload is ready for packetization and transmission.
1780 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001781 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1782 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1783 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001784 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001785
henrikaec6fbd22017-03-31 05:43:36 -07001786 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001787}
1788
solenberg7602aab2016-11-14 11:30:07 -08001789void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1790 RTC_DCHECK(!channel.channel() ||
1791 channel.channel()->ChannelId() != _channelId);
1792 rtc::CritScope lock(&assoc_send_channel_lock_);
1793 associate_send_channel_ = channel;
1794}
1795
Minyue2013aec2015-05-13 14:14:42 +02001796void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001797 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001798 Channel* channel = associate_send_channel_.channel();
1799 if (channel && channel->ChannelId() == channel_id) {
1800 // If this channel is associated with a send channel of the specified
1801 // Channel ID, disassociate with it.
1802 ChannelOwner ref(NULL);
1803 associate_send_channel_ = ref;
1804 }
1805}
1806
ivoc14d5dbe2016-07-04 07:06:55 -07001807void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1808 event_log_proxy_->SetEventLog(event_log);
1809}
1810
michaelt9332b7d2016-11-30 07:51:13 -08001811void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1812 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1813}
1814
nisse284542b2017-01-10 08:58:32 -08001815void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001816 size_t overhead_per_packet =
1817 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001818 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1819 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001820 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001821 }
1822 });
1823}
1824
1825void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001826 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001827 transport_overhead_per_packet_ = transport_overhead_per_packet;
1828 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001829}
1830
hbos3fd31fe2017-02-28 05:43:16 -08001831// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001832void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001833 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001834 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1835 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001836}
1837
kwiberg55b97fe2016-01-28 05:22:45 -08001838int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1839 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001840}
1841
wu@webrtc.org24301a62013-12-13 19:17:43 +00001842void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1843 audio_coding_->GetDecodingCallStatistics(stats);
1844}
1845
ivoce1198e02017-09-08 08:13:19 -07001846ANAStats Channel::GetANAStatistics() const {
1847 return audio_coding_->GetANAStats();
1848}
1849
solenberg358057b2015-11-27 10:46:42 -08001850uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001851 rtc::CritScope lock(&video_sync_lock_);
1852 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001853}
1854
kwiberg55b97fe2016-01-28 05:22:45 -08001855int Channel::SetMinimumPlayoutDelay(int delayMs) {
1856 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1857 "Channel::SetMinimumPlayoutDelay()");
1858 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1859 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
1860 _engineStatisticsPtr->SetLastError(
1861 VE_INVALID_ARGUMENT, kTraceError,
1862 "SetMinimumPlayoutDelay() invalid min delay");
1863 return -1;
1864 }
1865 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
1866 _engineStatisticsPtr->SetLastError(
1867 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1868 "SetMinimumPlayoutDelay() failed to set min playout delay");
1869 return -1;
1870 }
1871 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001872}
1873
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001874int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001875 uint32_t playout_timestamp_rtp = 0;
1876 {
tommi31fc21f2016-01-21 10:37:37 -08001877 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001878 playout_timestamp_rtp = playout_timestamp_rtp_;
1879 }
kwiberg55b97fe2016-01-28 05:22:45 -08001880 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001881 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07001882 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001883 "GetPlayoutTimestamp() failed to retrieve timestamp");
1884 return -1;
1885 }
deadbeef74375882015-08-13 12:09:10 -07001886 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001887 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001888}
1889
kwiberg55b97fe2016-01-28 05:22:45 -08001890int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1891 RtpReceiver** rtp_receiver) const {
1892 *rtpRtcpModule = _rtpRtcpModule.get();
1893 *rtp_receiver = rtp_receiver_.get();
1894 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001895}
1896
deadbeef74375882015-08-13 12:09:10 -07001897void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001898 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001899
henrik.lundin96bd5022016-04-06 04:13:56 -07001900 if (!jitter_buffer_playout_timestamp_) {
1901 // This can happen if this channel has not received any RTP packets. In
1902 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001903 return;
1904 }
1905
1906 uint16_t delay_ms = 0;
1907 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001908 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001909 "Channel::UpdatePlayoutTimestamp() failed to read playout"
1910 " delay from the ADM");
1911 _engineStatisticsPtr->SetLastError(
1912 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
1913 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
1914 return;
1915 }
1916
henrik.lundin96bd5022016-04-06 04:13:56 -07001917 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1918 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001919
1920 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001921 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001922
kwiberg55b97fe2016-01-28 05:22:45 -08001923 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001924 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07001925 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07001926
1927 {
tommi31fc21f2016-01-21 10:37:37 -08001928 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001929 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001930 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001931 }
1932 playout_delay_ms_ = delay_ms;
1933 }
1934}
1935
kwiberg55b97fe2016-01-28 05:22:45 -08001936void Channel::RegisterReceiveCodecsToRTPModule() {
1937 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1938 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001939
kwiberg55b97fe2016-01-28 05:22:45 -08001940 CodecInst codec;
1941 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00001942
kwiberg55b97fe2016-01-28 05:22:45 -08001943 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1944 // Open up the RTP/RTCP receiver for all supported codecs
1945 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001946 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001947 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1948 "Channel::RegisterReceiveCodecsToRTPModule() unable"
1949 " to register %s (%d/%d/%" PRIuS
1950 "/%d) to RTP/RTCP "
1951 "receiver",
1952 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1953 codec.rate);
1954 } else {
1955 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1956 "Channel::RegisterReceiveCodecsToRTPModule() %s "
1957 "(%d/%d/%" PRIuS
1958 "/%d) has been added to the RTP/RTCP "
1959 "receiver",
1960 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1961 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001962 }
kwiberg55b97fe2016-01-28 05:22:45 -08001963 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001964}
1965
kwiberg55b97fe2016-01-28 05:22:45 -08001966int Channel::SetSendRtpHeaderExtension(bool enable,
1967 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001968 unsigned char id) {
1969 int error = 0;
1970 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1971 if (enable) {
1972 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1973 }
1974 return error;
1975}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001976
ossue280cde2016-10-12 11:04:10 -07001977int Channel::GetRtpTimestampRateHz() const {
1978 const auto format = audio_coding_->ReceiveFormat();
1979 // Default to the playout frequency if we've not gotten any packets yet.
1980 // TODO(ossu): Zero clockrate can only happen if we've added an external
1981 // decoder for a format we don't support internally. Remove once that way of
1982 // adding decoders is gone!
1983 return (format && format->clockrate_hz != 0)
1984 ? format->clockrate_hz
1985 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001986}
1987
Minyue2013aec2015-05-13 14:14:42 +02001988int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001989 RtcpMode method = _rtpRtcpModule->RTCP();
1990 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001991 return 0;
1992 }
1993 std::vector<RTCPReportBlock> report_blocks;
1994 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001995
1996 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001997 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001998 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001999 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002000 Channel* channel = associate_send_channel_.channel();
2001 // Tries to get RTT from an associated channel. This is important for
2002 // receive-only channels.
2003 if (channel) {
2004 // To prevent infinite recursion and deadlock, calling GetRTT of
2005 // associate channel should always use "false" for argument:
2006 // |allow_associate_channel|.
2007 rtt = channel->GetRTT(false);
2008 }
2009 }
2010 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002011 }
2012
2013 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2014 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
2015 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07002016 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002017 break;
2018 }
2019 if (it == report_blocks.end()) {
2020 // We have not received packets with SSRC matching the report blocks.
2021 // To calculate RTT we try with the SSRC of the first report block.
2022 // This is very important for send-only channels where we don't know
2023 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07002024 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002025 }
Minyue2013aec2015-05-13 14:14:42 +02002026
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002027 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002028 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002029 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002030 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
2031 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002032 return 0;
2033 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002034 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002035}
2036
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00002037} // namespace voe
2038} // namespace webrtc