blob: 4dff3de585c38ef9aeeb2001fb0906cc6e621b7b [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
solenberge423a9de2017-09-27 11:28:14 -0700649 // Convert module ID to internal VoE channel ID
650 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),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100776 _callbackCritSectPtr(NULL),
777 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700778 input_mute_(false),
779 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100780 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100781 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800782 transport_overhead_per_packet_(0),
783 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100784 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100785 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100786 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700787 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800788 feedback_observer_proxy_(new TransportFeedbackProxy()),
789 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700790 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200791 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
792 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700793 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700794 use_twcc_plr_for_ana_(
795 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800796 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
797 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700798 AudioCodingModule::Config acm_config(config.acm_config);
solenberge423a9de2017-09-27 11:28:14 -0700799 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700800 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800801 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200802
kwiberg55b97fe2016-01-28 05:22:45 -0800803 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000804
kwiberg55b97fe2016-01-28 05:22:45 -0800805 RtpRtcp::Configuration configuration;
806 configuration.audio = true;
807 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800808 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800809 configuration.receive_statistics = rtp_receive_statistics_.get();
810 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800811 if (pacing_enabled_) {
812 configuration.paced_sender = rtp_packet_sender_proxy_.get();
813 configuration.transport_sequence_number_allocator =
814 seq_num_allocator_proxy_.get();
815 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
816 }
ivoc14d5dbe2016-07-04 07:06:55 -0700817 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800818 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200819 configuration.retransmission_rate_limiter =
820 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000821
kwiberg55b97fe2016-01-28 05:22:45 -0800822 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100823 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000824}
825
kwiberg55b97fe2016-01-28 05:22:45 -0800826Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700827 RTC_DCHECK(!channel_state_.Get().sending);
828 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000829}
830
kwiberg55b97fe2016-01-28 05:22:45 -0800831int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700832 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800833 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
834 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000835
kwiberg55b97fe2016-01-28 05:22:45 -0800836 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000837
kwiberg55b97fe2016-01-28 05:22:45 -0800838 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000839
kwiberg55b97fe2016-01-28 05:22:45 -0800840 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
841 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
842 "Channel::Init() must call SetEngineInformation() first");
843 return -1;
844 }
845
846 // --- Add modules to process thread (for periodic schedulation)
847
tommidea489f2017-03-03 03:20:24 -0800848 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800849
850 // --- ACM initialization
851
852 if (audio_coding_->InitializeReceiver() == -1) {
853 _engineStatisticsPtr->SetLastError(
854 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
855 "Channel::Init() unable to initialize the ACM - 1");
856 return -1;
857 }
858
859 // --- RTP/RTCP module initialization
860
861 // Ensure that RTCP is enabled by default for the created channel.
862 // Note that, the module will keep generating RTCP until it is explicitly
863 // disabled by the user.
864 // After StopListen (when no sockets exists), RTCP packets will no longer
865 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700866 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800867 // RTCP is enabled by default.
868 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
869 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800870 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800871 _engineStatisticsPtr->SetLastError(
872 VE_CANNOT_INIT_CHANNEL, kTraceError,
873 "Channel::Init() callbacks not registered");
874 return -1;
875 }
876
kwiberg1c07c702017-03-27 07:15:49 -0700877 return 0;
878}
879
tommi0a2391f2017-03-21 02:31:51 -0700880void Channel::Terminate() {
881 RTC_DCHECK(construction_thread_.CalledOnValidThread());
882 // Must be called on the same thread as Init().
883 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
884 "Channel::Terminate");
885
886 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
887
888 StopSend();
889 StopPlayout();
890
tommi0a2391f2017-03-21 02:31:51 -0700891 // The order to safely shutdown modules in a channel is:
892 // 1. De-register callbacks in modules
893 // 2. De-register modules in process thread
894 // 3. Destroy modules
895 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
896 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
897 "Terminate() failed to de-register transport callback"
898 " (Audio coding module)");
899 }
900
tommi0a2391f2017-03-21 02:31:51 -0700901 // De-register modules in process thread
902 if (_moduleProcessThreadPtr)
903 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
904
905 // End of modules shutdown
906}
907
kwiberg55b97fe2016-01-28 05:22:45 -0800908int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
kwiberg55b97fe2016-01-28 05:22:45 -0800909 ProcessThread& moduleProcessThread,
910 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700911 rtc::CriticalSection* callbackCritSect,
912 rtc::TaskQueue* encoder_queue) {
913 RTC_DCHECK(encoder_queue);
914 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800915 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
916 "Channel::SetEngineInformation()");
917 _engineStatisticsPtr = &engineStatistics;
kwiberg55b97fe2016-01-28 05:22:45 -0800918 _moduleProcessThreadPtr = &moduleProcessThread;
919 _audioDeviceModulePtr = &audioDeviceModule;
kwiberg55b97fe2016-01-28 05:22:45 -0800920 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -0700921 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800922 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000923}
924
kwibergb7f89d62016-02-17 10:04:18 -0800925void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800926 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800927 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100928}
929
ossu29b1a8d2016-06-13 07:34:51 -0700930const rtc::scoped_refptr<AudioDecoderFactory>&
931Channel::GetAudioDecoderFactory() const {
932 return decoder_factory_;
933}
934
kwiberg55b97fe2016-01-28 05:22:45 -0800935int32_t Channel::StartPlayout() {
936 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
937 "Channel::StartPlayout()");
938 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000939 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800940 }
941
kwiberg55b97fe2016-01-28 05:22:45 -0800942 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800943
944 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000945}
946
kwiberg55b97fe2016-01-28 05:22:45 -0800947int32_t Channel::StopPlayout() {
948 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
949 "Channel::StopPlayout()");
950 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000951 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800952 }
953
kwiberg55b97fe2016-01-28 05:22:45 -0800954 channel_state_.SetPlaying(false);
955 _outputAudioLevel.Clear();
956
957 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000958}
959
kwiberg55b97fe2016-01-28 05:22:45 -0800960int32_t Channel::StartSend() {
961 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
962 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -0800963 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000964 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800965 }
966 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700967 {
968 // It is now OK to start posting tasks to the encoder task queue.
969 rtc::CritScope cs(&encoder_queue_lock_);
970 encoder_queue_is_active_ = true;
971 }
solenberg08b19df2017-02-15 00:42:31 -0800972 // Resume the previous sequence number which was reset by StopSend(). This
973 // needs to be done before |sending| is set to true on the RTP/RTCP module.
974 if (send_sequence_number_) {
975 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
976 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100977 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800978 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
979 _engineStatisticsPtr->SetLastError(
980 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
981 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100982 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800983 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000984 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800985 return -1;
986 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000987
kwiberg55b97fe2016-01-28 05:22:45 -0800988 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000989}
990
henrikaec6fbd22017-03-31 05:43:36 -0700991void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800992 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
993 "Channel::StopSend()");
994 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700995 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800996 }
997 channel_state_.SetSending(false);
998
henrikaec6fbd22017-03-31 05:43:36 -0700999 // Post a task to the encoder thread which sets an event when the task is
1000 // executed. We know that no more encoding tasks will be added to the task
1001 // queue for this channel since sending is now deactivated. It means that,
1002 // if we wait for the event to bet set, we know that no more pending tasks
1003 // exists and it is therfore guaranteed that the task queue will never try
1004 // to acccess and invalid channel object.
1005 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001006
henrikaec6fbd22017-03-31 05:43:36 -07001007 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001008 {
1009 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1010 // than this final "flush task" to be posted on the queue.
1011 rtc::CritScope cs(&encoder_queue_lock_);
1012 encoder_queue_is_active_ = false;
1013 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1014 }
henrikaec6fbd22017-03-31 05:43:36 -07001015 flush.Wait(rtc::Event::kForever);
1016
kwiberg55b97fe2016-01-28 05:22:45 -08001017 // Store the sequence number to be able to pick up the same sequence for
1018 // the next StartSend(). This is needed for restarting device, otherwise
1019 // it might cause libSRTP to complain about packets being replayed.
1020 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1021 // CL is landed. See issue
1022 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1023 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1024
1025 // Reset sending SSRC and sequence number and triggers direct transmission
1026 // of RTCP BYE
1027 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1028 _engineStatisticsPtr->SetLastError(
1029 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1030 "StartSend() RTP/RTCP failed to stop sending");
1031 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001032 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001033}
1034
ossu1ffbd6c2017-04-06 12:05:04 -07001035bool Channel::SetEncoder(int payload_type,
1036 std::unique_ptr<AudioEncoder> encoder) {
1037 RTC_DCHECK_GE(payload_type, 0);
1038 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001039 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1040 // one for for us to keep track of sample rate and number of channels, etc.
1041
1042 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1043 // as well as some other things, so we collect this info and send it along.
1044 CodecInst rtp_codec;
1045 rtp_codec.pltype = payload_type;
1046 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1047 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001048 // Seems unclear if it should be clock rate or sample rate. CodecInst
1049 // supposedly carries the sample rate, but only clock rate seems sensible to
1050 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001051 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1052 rtp_codec.pacsize = rtc::CheckedDivExact(
1053 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1054 100);
1055 rtp_codec.channels = encoder->NumChannels();
1056 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001057
ossu76d29f92017-06-09 07:30:13 -07001058 // For audio encoding we need, instead, the actual sample rate of the codec.
1059 // The rest of the information should be the same.
1060 CodecInst send_codec = rtp_codec;
1061 send_codec.plfreq = encoder->SampleRateHz();
1062 cached_send_codec_.emplace(send_codec);
1063
1064 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001065 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001066 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001067 WEBRTC_TRACE(
1068 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1069 "SetEncoder() failed to register codec to RTP/RTCP module");
1070 return false;
1071 }
1072 }
1073
1074 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001075 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001076 return true;
1077}
1078
ossu20a4b3f2017-04-27 02:08:52 -07001079void Channel::ModifyEncoder(
1080 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1081 audio_coding_->ModifyEncoder(modifier);
1082}
1083
kwiberg55b97fe2016-01-28 05:22:45 -08001084int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001085 if (cached_send_codec_) {
1086 codec = *cached_send_codec_;
1087 return 0;
1088 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001089 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1090 if (send_codec) {
1091 codec = *send_codec;
1092 return 0;
1093 }
1094 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001095 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001096}
1097
kwiberg55b97fe2016-01-28 05:22:45 -08001098int32_t Channel::GetRecCodec(CodecInst& codec) {
1099 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001100}
1101
kwiberg55b97fe2016-01-28 05:22:45 -08001102int32_t Channel::SetSendCodec(const CodecInst& codec) {
1103 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1104 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001105
kwibergc8d071e2016-04-06 12:22:38 -07001106 if (!codec_manager_.RegisterEncoder(codec) ||
1107 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001108 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1109 "SetSendCodec() failed to register codec to ACM");
1110 return -1;
1111 }
1112
1113 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1114 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1115 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1116 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1117 "SetSendCodec() failed to register codec to"
1118 " RTP/RTCP module");
1119 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001120 }
kwiberg55b97fe2016-01-28 05:22:45 -08001121 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001122
ossu76d29f92017-06-09 07:30:13 -07001123 cached_send_codec_.reset();
1124
kwiberg55b97fe2016-01-28 05:22:45 -08001125 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001126}
1127
minyue78b4d562016-11-30 04:47:39 -08001128void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001129 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1130 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001131 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001132 if (*encoder) {
1133 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001134 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001135 }
1136 });
michaelt566d8202017-01-12 10:17:38 -08001137 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001138}
1139
elad.alond12a8e12017-03-23 11:04:48 -07001140void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1141 if (!use_twcc_plr_for_ana_)
1142 return;
minyue7e304322016-10-12 05:00:55 -07001143 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001144 if (*encoder) {
1145 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1146 }
1147 });
1148}
1149
elad.alondadb4dc2017-03-23 15:29:50 -07001150void Channel::OnRecoverableUplinkPacketLossRate(
1151 float recoverable_packet_loss_rate) {
1152 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1153 if (*encoder) {
1154 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1155 recoverable_packet_loss_rate);
1156 }
1157 });
1158}
1159
elad.alond12a8e12017-03-23 11:04:48 -07001160void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1161 if (use_twcc_plr_for_ana_)
1162 return;
1163 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1164 if (*encoder) {
1165 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1166 }
minyue7e304322016-10-12 05:00:55 -07001167 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001168}
1169
kwiberg1c07c702017-03-27 07:15:49 -07001170void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1171 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1172 audio_coding_->SetReceiveCodecs(codecs);
1173}
1174
minyue7e304322016-10-12 05:00:55 -07001175bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1176 bool success = false;
1177 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1178 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001179 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1180 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001181 }
1182 });
1183 return success;
1184}
1185
1186void Channel::DisableAudioNetworkAdaptor() {
1187 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1188 if (*encoder)
1189 (*encoder)->DisableAudioNetworkAdaptor();
1190 });
1191}
1192
1193void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1194 int max_frame_length_ms) {
1195 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1196 if (*encoder) {
1197 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1198 max_frame_length_ms);
1199 }
1200 });
1201}
1202
mflodman3d7db262016-04-29 00:57:13 -07001203int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001204 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001205 "Channel::RegisterExternalTransport()");
1206
kwiberg55b97fe2016-01-28 05:22:45 -08001207 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001208 if (_externalTransport) {
1209 _engineStatisticsPtr->SetLastError(
1210 VE_INVALID_OPERATION, kTraceError,
1211 "RegisterExternalTransport() external transport already enabled");
1212 return -1;
1213 }
1214 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001215 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001216 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001217}
1218
kwiberg55b97fe2016-01-28 05:22:45 -08001219int32_t Channel::DeRegisterExternalTransport() {
1220 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1221 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001222
kwiberg55b97fe2016-01-28 05:22:45 -08001223 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001224 if (_transportPtr) {
1225 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1226 "DeRegisterExternalTransport() all transport is disabled");
1227 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001228 _engineStatisticsPtr->SetLastError(
1229 VE_INVALID_OPERATION, kTraceWarning,
1230 "DeRegisterExternalTransport() external transport already "
1231 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001232 }
1233 _externalTransport = false;
1234 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001235 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001236}
1237
nisse657bab22017-02-21 06:28:10 -08001238void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1239 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg946d8862017-09-21 04:02:53 -07001240 "Channel::OnRtpPacket()");
nisse657bab22017-02-21 06:28:10 -08001241
1242 RTPHeader header;
1243 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -07001244
1245 // Store playout timestamp for the received RTP packet
1246 UpdatePlayoutTimestamp(false);
1247
1248 header.payload_type_frequency =
1249 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1250 if (header.payload_type_frequency >= 0) {
1251 bool in_order = IsPacketInOrder(header);
1252 rtp_receive_statistics_->IncomingPacket(
1253 header, packet.size(), IsPacketRetransmitted(header, in_order));
1254 rtp_payload_registry_->SetIncomingPayloadType(header);
1255
1256 ReceivePacket(packet.data(), packet.size(), header, in_order);
1257 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001258}
1259
1260bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001261 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001262 const RTPHeader& header,
1263 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001264 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001265 assert(packet_length >= header.headerLength);
1266 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001267 const auto pl =
1268 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1269 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001270 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001271 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001272 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Karl Wiberg73b60b82017-09-21 15:00:58 +02001273 pl->typeSpecific, in_order);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001274}
1275
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001276bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1277 StreamStatistician* statistician =
1278 rtp_receive_statistics_->GetStatistician(header.ssrc);
1279 if (!statistician)
1280 return false;
1281 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001282}
1283
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001284bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1285 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001286 StreamStatistician* statistician =
1287 rtp_receive_statistics_->GetStatistician(header.ssrc);
1288 if (!statistician)
1289 return false;
1290 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001291 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001292 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001293 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001294}
1295
mflodman3d7db262016-04-29 00:57:13 -07001296int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001297 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001298 "Channel::ReceivedRTCPPacket()");
1299 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001300 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001301
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001302 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001303 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001304
Minyue2013aec2015-05-13 14:14:42 +02001305 int64_t rtt = GetRTT(true);
1306 if (rtt == 0) {
1307 // Waiting for valid RTT.
1308 return 0;
1309 }
Erik Språng737336d2016-07-29 12:59:36 +02001310
1311 int64_t nack_window_ms = rtt;
1312 if (nack_window_ms < kMinRetransmissionWindowMs) {
1313 nack_window_ms = kMinRetransmissionWindowMs;
1314 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1315 nack_window_ms = kMaxRetransmissionWindowMs;
1316 }
1317 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1318
minyue7e304322016-10-12 05:00:55 -07001319 // Invoke audio encoders OnReceivedRtt().
1320 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1321 if (*encoder)
1322 (*encoder)->OnReceivedRtt(rtt);
1323 });
1324
Minyue2013aec2015-05-13 14:14:42 +02001325 uint32_t ntp_secs = 0;
1326 uint32_t ntp_frac = 0;
1327 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001328 if (0 !=
1329 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1330 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001331 // Waiting for RTCP.
1332 return 0;
1333 }
1334
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001335 {
tommi31fc21f2016-01-21 10:37:37 -08001336 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001337 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001338 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001339 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001340}
1341
solenberg8d73f8c2017-03-08 01:52:20 -08001342int Channel::GetSpeechOutputLevel() const {
1343 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001344}
1345
solenberg8d73f8c2017-03-08 01:52:20 -08001346int Channel::GetSpeechOutputLevelFullRange() const {
1347 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001348}
1349
zsteine76bd3a2017-07-14 12:17:49 -07001350double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001351 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001352}
1353
1354double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001355 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001356}
1357
solenberg8d73f8c2017-03-08 01:52:20 -08001358void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001359 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001360 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001361}
1362
solenberg1c2af8e2016-03-24 10:36:00 -07001363bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001364 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001365 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001366}
1367
solenberg8d73f8c2017-03-08 01:52:20 -08001368void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001369 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001370 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001371}
1372
solenberg8842c3e2016-03-11 03:06:41 -08001373int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001374 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001375 "Channel::SendTelephoneEventOutband(...)");
1376 RTC_DCHECK_LE(0, event);
1377 RTC_DCHECK_GE(255, event);
1378 RTC_DCHECK_LE(0, duration_ms);
1379 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001380 if (!Sending()) {
1381 return -1;
1382 }
solenberg8842c3e2016-03-11 03:06:41 -08001383 if (_rtpRtcpModule->SendTelephoneEventOutband(
1384 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001385 _engineStatisticsPtr->SetLastError(
1386 VE_SEND_DTMF_FAILED, kTraceWarning,
1387 "SendTelephoneEventOutband() failed to send event");
1388 return -1;
1389 }
1390 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001391}
1392
solenbergffbbcac2016-11-17 05:25:37 -08001393int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1394 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001395 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001396 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001397 RTC_DCHECK_LE(0, payload_type);
1398 RTC_DCHECK_GE(127, payload_type);
1399 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001400 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001401 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001402 memcpy(codec.plname, "telephone-event", 16);
1403 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1404 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1405 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1406 _engineStatisticsPtr->SetLastError(
1407 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1408 "SetSendTelephoneEventPayloadType() failed to register send"
1409 "payload type");
1410 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001411 }
kwiberg55b97fe2016-01-28 05:22:45 -08001412 }
kwiberg55b97fe2016-01-28 05:22:45 -08001413 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001414}
1415
kwiberg55b97fe2016-01-28 05:22:45 -08001416int Channel::SetLocalSSRC(unsigned int ssrc) {
1417 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1418 "Channel::SetLocalSSRC()");
1419 if (channel_state_.Get().sending) {
1420 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
1421 "SetLocalSSRC() already sending");
1422 return -1;
1423 }
1424 _rtpRtcpModule->SetSSRC(ssrc);
1425 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001426}
1427
kwiberg55b97fe2016-01-28 05:22:45 -08001428int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1429 ssrc = rtp_receiver_->SSRC();
1430 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001431}
1432
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001433int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001434 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001435 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001436}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001437
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001438int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1439 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001440 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1441 if (enable &&
1442 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1443 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001444 return -1;
1445 }
1446 return 0;
1447}
1448
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001449void Channel::EnableSendTransportSequenceNumber(int id) {
1450 int ret =
1451 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1452 RTC_DCHECK_EQ(0, ret);
1453}
1454
stefan3313ec92016-01-21 06:32:43 -08001455void Channel::EnableReceiveTransportSequenceNumber(int id) {
1456 rtp_header_parser_->DeregisterRtpHeaderExtension(
1457 kRtpExtensionTransportSequenceNumber);
1458 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1459 kRtpExtensionTransportSequenceNumber, id);
1460 RTC_DCHECK(ret);
1461}
1462
stefanbba9dec2016-02-01 04:39:55 -08001463void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001464 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001465 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001466 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1467 TransportFeedbackObserver* transport_feedback_observer =
1468 transport->transport_feedback_observer();
1469 PacketRouter* packet_router = transport->packet_router();
1470
stefanbba9dec2016-02-01 04:39:55 -08001471 RTC_DCHECK(rtp_packet_sender);
1472 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001473 RTC_DCHECK(packet_router);
1474 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001475 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001476 feedback_observer_proxy_->SetTransportFeedbackObserver(
1477 transport_feedback_observer);
1478 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1479 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1480 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001481 constexpr bool remb_candidate = false;
1482 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001483 packet_router_ = packet_router;
1484}
1485
stefanbba9dec2016-02-01 04:39:55 -08001486void Channel::RegisterReceiverCongestionControlObjects(
1487 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001488 RTC_DCHECK(packet_router);
1489 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001490 constexpr bool remb_candidate = false;
1491 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001492 packet_router_ = packet_router;
1493}
1494
nissefdbfdc92017-03-31 05:44:52 -07001495void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001496 RTC_DCHECK(packet_router_);
1497 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001498 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001499 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1500 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001501 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001502 packet_router_ = nullptr;
1503 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1504}
1505
nissefdbfdc92017-03-31 05:44:52 -07001506void Channel::ResetReceiverCongestionControlObjects() {
1507 RTC_DCHECK(packet_router_);
1508 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1509 packet_router_ = nullptr;
1510}
1511
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001512void Channel::SetRTCPStatus(bool enable) {
1513 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1514 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001515 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001516}
1517
kwiberg55b97fe2016-01-28 05:22:45 -08001518int Channel::SetRTCP_CNAME(const char cName[256]) {
1519 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1520 "Channel::SetRTCP_CNAME()");
1521 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
1522 _engineStatisticsPtr->SetLastError(
1523 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1524 "SetRTCP_CNAME() failed to set RTCP CNAME");
1525 return -1;
1526 }
1527 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001528}
1529
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001530int Channel::GetRemoteRTCPReportBlocks(
1531 std::vector<ReportBlock>* report_blocks) {
1532 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08001533 _engineStatisticsPtr->SetLastError(
1534 VE_INVALID_ARGUMENT, kTraceError,
1535 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001536 return -1;
1537 }
1538
1539 // Get the report blocks from the latest received RTCP Sender or Receiver
1540 // Report. Each element in the vector contains the sender's SSRC and a
1541 // report block according to RFC 3550.
1542 std::vector<RTCPReportBlock> rtcp_report_blocks;
1543 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001544 return -1;
1545 }
1546
1547 if (rtcp_report_blocks.empty())
1548 return 0;
1549
1550 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1551 for (; it != rtcp_report_blocks.end(); ++it) {
1552 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001553 report_block.sender_SSRC = it->sender_ssrc;
1554 report_block.source_SSRC = it->source_ssrc;
1555 report_block.fraction_lost = it->fraction_lost;
1556 report_block.cumulative_num_packets_lost = it->packets_lost;
1557 report_block.extended_highest_sequence_number =
1558 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001559 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001560 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1561 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001562 report_blocks->push_back(report_block);
1563 }
1564 return 0;
1565}
1566
kwiberg55b97fe2016-01-28 05:22:45 -08001567int Channel::GetRTPStatistics(CallStatistics& stats) {
1568 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001569
kwiberg55b97fe2016-01-28 05:22:45 -08001570 // The jitter statistics is updated for each received RTP packet and is
1571 // based on received packets.
1572 RtcpStatistics statistics;
1573 StreamStatistician* statistician =
1574 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001575 if (statistician) {
1576 statistician->GetStatistics(&statistics,
1577 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001578 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001579
kwiberg55b97fe2016-01-28 05:22:45 -08001580 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001581 stats.cumulativeLost = statistics.packets_lost;
1582 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001583 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001584
kwiberg55b97fe2016-01-28 05:22:45 -08001585 // --- RTT
1586 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001587
kwiberg55b97fe2016-01-28 05:22:45 -08001588 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001589
kwiberg55b97fe2016-01-28 05:22:45 -08001590 size_t bytesSent(0);
1591 uint32_t packetsSent(0);
1592 size_t bytesReceived(0);
1593 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001594
kwiberg55b97fe2016-01-28 05:22:45 -08001595 if (statistician) {
1596 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1597 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001598
kwiberg55b97fe2016-01-28 05:22:45 -08001599 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
1600 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1601 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
1602 " output will not be complete");
1603 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001604
kwiberg55b97fe2016-01-28 05:22:45 -08001605 stats.bytesSent = bytesSent;
1606 stats.packetsSent = packetsSent;
1607 stats.bytesReceived = bytesReceived;
1608 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001609
kwiberg55b97fe2016-01-28 05:22:45 -08001610 // --- Timestamps
1611 {
1612 rtc::CritScope lock(&ts_stats_lock_);
1613 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1614 }
1615 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001616}
1617
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001618void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1619 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001620 // If pacing is enabled we always store packets.
1621 if (!pacing_enabled_)
1622 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001623 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001624 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001625 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001626 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001627 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001628}
1629
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001630// Called when we are missing one or more packets.
1631int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001632 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1633}
1634
henrikaec6fbd22017-03-31 05:43:36 -07001635void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001636 // Avoid posting any new tasks if sending was already stopped in StopSend().
1637 rtc::CritScope cs(&encoder_queue_lock_);
1638 if (!encoder_queue_is_active_) {
1639 return;
1640 }
henrikaec6fbd22017-03-31 05:43:36 -07001641 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1642 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1643 // either into pool of frames or into the task itself.
1644 audio_frame->CopyFrom(audio_input);
solenberge423a9de2017-09-27 11:28:14 -07001645 audio_frame->id_ = ChannelId();
henrikaec6fbd22017-03-31 05:43:36 -07001646 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1647 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001648}
1649
henrikaec6fbd22017-03-31 05:43:36 -07001650void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1651 int sample_rate,
1652 size_t number_of_frames,
1653 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001654 // Avoid posting as new task if sending was already stopped in StopSend().
1655 rtc::CritScope cs(&encoder_queue_lock_);
1656 if (!encoder_queue_is_active_) {
1657 return;
1658 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001659 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001660 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001661 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
solenberge423a9de2017-09-27 11:28:14 -07001662 audio_frame->id_ = ChannelId();
ossu950c1c92017-07-11 08:19:31 -07001663 // TODO(ossu): Investigate how this could happen. b/62909493
1664 if (result == 0) {
1665 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1666 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1667 } else {
1668 audio_frame->sample_rate_hz_ = sample_rate;
1669 audio_frame->num_channels_ = number_of_channels;
1670 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1671 RTC_NOTREACHED();
1672 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001673 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001674 sample_rate, &input_resampler_, audio_frame.get());
1675 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1676 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001677}
1678
henrikaec6fbd22017-03-31 05:43:36 -07001679void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1680 RTC_DCHECK_RUN_ON(encoder_queue_);
1681 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1682 RTC_DCHECK_LE(audio_input->num_channels_, 2);
solenberge423a9de2017-09-27 11:28:14 -07001683 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08001684
henrikaec6fbd22017-03-31 05:43:36 -07001685 bool is_muted = InputMute();
1686 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001687
kwiberg55b97fe2016-01-28 05:22:45 -08001688 if (_includeAudioLevelIndication) {
1689 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001690 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001691 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001692 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001693 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001694 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001695 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001696 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001697 }
kwiberg55b97fe2016-01-28 05:22:45 -08001698 }
solenberg1c2af8e2016-03-24 10:36:00 -07001699 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001700
henrikaec6fbd22017-03-31 05:43:36 -07001701 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001702
kwiberg55b97fe2016-01-28 05:22:45 -08001703 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001704 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001705 // This call will trigger AudioPacketizationCallback::SendData if encoding
1706 // is done and payload is ready for packetization and transmission.
1707 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001708 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1709 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1710 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001711 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001712
henrikaec6fbd22017-03-31 05:43:36 -07001713 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001714}
1715
solenberg7602aab2016-11-14 11:30:07 -08001716void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1717 RTC_DCHECK(!channel.channel() ||
1718 channel.channel()->ChannelId() != _channelId);
1719 rtc::CritScope lock(&assoc_send_channel_lock_);
1720 associate_send_channel_ = channel;
1721}
1722
Minyue2013aec2015-05-13 14:14:42 +02001723void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001724 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001725 Channel* channel = associate_send_channel_.channel();
1726 if (channel && channel->ChannelId() == channel_id) {
1727 // If this channel is associated with a send channel of the specified
1728 // Channel ID, disassociate with it.
1729 ChannelOwner ref(NULL);
1730 associate_send_channel_ = ref;
1731 }
1732}
1733
ivoc14d5dbe2016-07-04 07:06:55 -07001734void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1735 event_log_proxy_->SetEventLog(event_log);
1736}
1737
michaelt9332b7d2016-11-30 07:51:13 -08001738void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1739 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1740}
1741
nisse284542b2017-01-10 08:58:32 -08001742void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001743 size_t overhead_per_packet =
1744 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001745 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1746 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001747 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001748 }
1749 });
1750}
1751
1752void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001753 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001754 transport_overhead_per_packet_ = transport_overhead_per_packet;
1755 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001756}
1757
hbos3fd31fe2017-02-28 05:43:16 -08001758// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001759void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001760 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001761 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1762 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001763}
1764
kwiberg55b97fe2016-01-28 05:22:45 -08001765int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1766 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001767}
1768
wu@webrtc.org24301a62013-12-13 19:17:43 +00001769void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1770 audio_coding_->GetDecodingCallStatistics(stats);
1771}
1772
ivoce1198e02017-09-08 08:13:19 -07001773ANAStats Channel::GetANAStatistics() const {
1774 return audio_coding_->GetANAStats();
1775}
1776
solenberg358057b2015-11-27 10:46:42 -08001777uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001778 rtc::CritScope lock(&video_sync_lock_);
1779 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001780}
1781
kwiberg55b97fe2016-01-28 05:22:45 -08001782int Channel::SetMinimumPlayoutDelay(int delayMs) {
1783 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1784 "Channel::SetMinimumPlayoutDelay()");
1785 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1786 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
1787 _engineStatisticsPtr->SetLastError(
1788 VE_INVALID_ARGUMENT, kTraceError,
1789 "SetMinimumPlayoutDelay() invalid min delay");
1790 return -1;
1791 }
1792 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
1793 _engineStatisticsPtr->SetLastError(
1794 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1795 "SetMinimumPlayoutDelay() failed to set min playout delay");
1796 return -1;
1797 }
1798 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001799}
1800
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001801int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001802 uint32_t playout_timestamp_rtp = 0;
1803 {
tommi31fc21f2016-01-21 10:37:37 -08001804 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001805 playout_timestamp_rtp = playout_timestamp_rtp_;
1806 }
kwiberg55b97fe2016-01-28 05:22:45 -08001807 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001808 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07001809 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001810 "GetPlayoutTimestamp() failed to retrieve timestamp");
1811 return -1;
1812 }
deadbeef74375882015-08-13 12:09:10 -07001813 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001814 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001815}
1816
kwiberg55b97fe2016-01-28 05:22:45 -08001817int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1818 RtpReceiver** rtp_receiver) const {
1819 *rtpRtcpModule = _rtpRtcpModule.get();
1820 *rtp_receiver = rtp_receiver_.get();
1821 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001822}
1823
deadbeef74375882015-08-13 12:09:10 -07001824void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001825 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001826
henrik.lundin96bd5022016-04-06 04:13:56 -07001827 if (!jitter_buffer_playout_timestamp_) {
1828 // This can happen if this channel has not received any RTP packets. In
1829 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001830 return;
1831 }
1832
1833 uint16_t delay_ms = 0;
1834 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001835 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001836 "Channel::UpdatePlayoutTimestamp() failed to read playout"
1837 " delay from the ADM");
1838 _engineStatisticsPtr->SetLastError(
1839 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
1840 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
1841 return;
1842 }
1843
henrik.lundin96bd5022016-04-06 04:13:56 -07001844 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1845 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001846
1847 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001848 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001849
kwiberg55b97fe2016-01-28 05:22:45 -08001850 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001851 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07001852 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07001853
1854 {
tommi31fc21f2016-01-21 10:37:37 -08001855 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001856 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001857 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001858 }
1859 playout_delay_ms_ = delay_ms;
1860 }
1861}
1862
kwiberg55b97fe2016-01-28 05:22:45 -08001863void Channel::RegisterReceiveCodecsToRTPModule() {
1864 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1865 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001866
kwiberg55b97fe2016-01-28 05:22:45 -08001867 CodecInst codec;
1868 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00001869
kwiberg55b97fe2016-01-28 05:22:45 -08001870 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1871 // Open up the RTP/RTCP receiver for all supported codecs
1872 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001873 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001874 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1875 "Channel::RegisterReceiveCodecsToRTPModule() unable"
1876 " to register %s (%d/%d/%" PRIuS
1877 "/%d) to RTP/RTCP "
1878 "receiver",
1879 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1880 codec.rate);
1881 } else {
1882 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1883 "Channel::RegisterReceiveCodecsToRTPModule() %s "
1884 "(%d/%d/%" PRIuS
1885 "/%d) has been added to the RTP/RTCP "
1886 "receiver",
1887 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1888 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001889 }
kwiberg55b97fe2016-01-28 05:22:45 -08001890 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001891}
1892
kwiberg55b97fe2016-01-28 05:22:45 -08001893int Channel::SetSendRtpHeaderExtension(bool enable,
1894 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001895 unsigned char id) {
1896 int error = 0;
1897 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1898 if (enable) {
1899 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1900 }
1901 return error;
1902}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001903
ossue280cde2016-10-12 11:04:10 -07001904int Channel::GetRtpTimestampRateHz() const {
1905 const auto format = audio_coding_->ReceiveFormat();
1906 // Default to the playout frequency if we've not gotten any packets yet.
1907 // TODO(ossu): Zero clockrate can only happen if we've added an external
1908 // decoder for a format we don't support internally. Remove once that way of
1909 // adding decoders is gone!
1910 return (format && format->clockrate_hz != 0)
1911 ? format->clockrate_hz
1912 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001913}
1914
Minyue2013aec2015-05-13 14:14:42 +02001915int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001916 RtcpMode method = _rtpRtcpModule->RTCP();
1917 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001918 return 0;
1919 }
1920 std::vector<RTCPReportBlock> report_blocks;
1921 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001922
1923 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001924 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001925 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001926 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001927 Channel* channel = associate_send_channel_.channel();
1928 // Tries to get RTT from an associated channel. This is important for
1929 // receive-only channels.
1930 if (channel) {
1931 // To prevent infinite recursion and deadlock, calling GetRTT of
1932 // associate channel should always use "false" for argument:
1933 // |allow_associate_channel|.
1934 rtt = channel->GetRTT(false);
1935 }
1936 }
1937 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001938 }
1939
1940 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1941 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1942 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001943 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001944 break;
1945 }
1946 if (it == report_blocks.end()) {
1947 // We have not received packets with SSRC matching the report blocks.
1948 // To calculate RTT we try with the SSRC of the first report block.
1949 // This is very important for send-only channels where we don't know
1950 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001951 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001952 }
Minyue2013aec2015-05-13 14:14:42 +02001953
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001954 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001955 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001956 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001957 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1958 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001959 return 0;
1960 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001961 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001962}
1963
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001964} // namespace voe
1965} // namespace webrtc