blob: e3ba1eeb55624d92e3c3c9b6069b93ba9b7b621c [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
henrika@webrtc.org2919e952012-01-31 08:45:03 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "voice_engine/channel.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Henrik Lundin64dad832015-05-11 12:44:23 +020013#include <algorithm>
Tommif888bb52015-12-12 01:37:01 +010014#include <utility>
Henrik Lundin64dad832015-05-11 12:44:23 +020015
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "api/array_view.h"
17#include "audio/utility/audio_frame_operations.h"
18#include "call/rtp_transport_controller_send_interface.h"
19#include "logging/rtc_event_log/rtc_event_log.h"
20#include "modules/audio_coding/codecs/audio_format_conversion.h"
21#include "modules/audio_device/include/audio_device.h"
22#include "modules/audio_processing/include/audio_processing.h"
23#include "modules/include/module_common_types.h"
24#include "modules/pacing/packet_router.h"
25#include "modules/rtp_rtcp/include/receive_statistics.h"
26#include "modules/rtp_rtcp/include/rtp_payload_registry.h"
27#include "modules/rtp_rtcp/include/rtp_receiver.h"
28#include "modules/rtp_rtcp/source/rtp_packet_received.h"
29#include "modules/rtp_rtcp/source/rtp_receiver_strategy.h"
30#include "modules/utility/include/process_thread.h"
31#include "rtc_base/checks.h"
32#include "rtc_base/criticalsection.h"
33#include "rtc_base/format_macros.h"
34#include "rtc_base/location.h"
35#include "rtc_base/logging.h"
36#include "rtc_base/rate_limiter.h"
37#include "rtc_base/task_queue.h"
38#include "rtc_base/thread_checker.h"
39#include "rtc_base/timeutils.h"
40#include "system_wrappers/include/field_trial.h"
henrika45802172017-09-28 09:39:34 +020041#include "system_wrappers/include/metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "system_wrappers/include/trace.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "voice_engine/statistics.h"
44#include "voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000045
andrew@webrtc.org50419b02012-11-14 19:07:54 +000046namespace webrtc {
47namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000048
kwibergc8d071e2016-04-06 12:22:38 -070049namespace {
50
zsteine76bd3a2017-07-14 12:17:49 -070051constexpr double kAudioSampleDurationSeconds = 0.01;
Erik Språng737336d2016-07-29 12:59:36 +020052constexpr int64_t kMaxRetransmissionWindowMs = 1000;
53constexpr int64_t kMinRetransmissionWindowMs = 30;
54
kwibergc8d071e2016-04-06 12:22:38 -070055} // namespace
56
solenberg8842c3e2016-03-11 03:06:41 -080057const int kTelephoneEventAttenuationdB = 10;
58
ivoc14d5dbe2016-07-04 07:06:55 -070059class RtcEventLogProxy final : public webrtc::RtcEventLog {
60 public:
61 RtcEventLogProxy() : event_log_(nullptr) {}
62
63 bool StartLogging(const std::string& file_name,
64 int64_t max_size_bytes) override {
65 RTC_NOTREACHED();
66 return false;
67 }
68
69 bool StartLogging(rtc::PlatformFile log_file,
70 int64_t max_size_bytes) override {
71 RTC_NOTREACHED();
72 return false;
73 }
74
75 void StopLogging() override { RTC_NOTREACHED(); }
76
77 void LogVideoReceiveStreamConfig(
perkj09e71da2017-05-22 03:26:49 -070078 const webrtc::rtclog::StreamConfig&) override {
79 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070080 }
81
perkjc0876aa2017-05-22 04:08:28 -070082 void LogVideoSendStreamConfig(const webrtc::rtclog::StreamConfig&) override {
83 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070084 }
85
ivoce0928d82016-10-10 05:12:51 -070086 void LogAudioReceiveStreamConfig(
perkjac8f52d2017-05-22 09:36:28 -070087 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070088 rtc::CritScope lock(&crit_);
89 if (event_log_) {
90 event_log_->LogAudioReceiveStreamConfig(config);
91 }
92 }
93
94 void LogAudioSendStreamConfig(
perkjf4726992017-05-22 10:12:26 -070095 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070096 rtc::CritScope lock(&crit_);
97 if (event_log_) {
98 event_log_->LogAudioSendStreamConfig(config);
99 }
100 }
101
ivoc14d5dbe2016-07-04 07:06:55 -0700102 void LogRtpHeader(webrtc::PacketDirection direction,
ivoc14d5dbe2016-07-04 07:06:55 -0700103 const uint8_t* header,
104 size_t packet_length) override {
perkj77cd58e2017-05-30 03:52:10 -0700105 LogRtpHeader(direction, header, packet_length, PacedPacketInfo::kNotAProbe);
philipel32d00102017-02-27 02:18:46 -0800106 }
107
108 void LogRtpHeader(webrtc::PacketDirection direction,
philipel32d00102017-02-27 02:18:46 -0800109 const uint8_t* header,
110 size_t packet_length,
111 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700112 rtc::CritScope lock(&crit_);
113 if (event_log_) {
perkj77cd58e2017-05-30 03:52:10 -0700114 event_log_->LogRtpHeader(direction, header, packet_length,
philipel32d00102017-02-27 02:18:46 -0800115 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700116 }
117 }
118
119 void LogRtcpPacket(webrtc::PacketDirection direction,
ivoc14d5dbe2016-07-04 07:06:55 -0700120 const uint8_t* packet,
121 size_t length) override {
122 rtc::CritScope lock(&crit_);
123 if (event_log_) {
perkj77cd58e2017-05-30 03:52:10 -0700124 event_log_->LogRtcpPacket(direction, packet, length);
ivoc14d5dbe2016-07-04 07:06:55 -0700125 }
126 }
127
128 void LogAudioPlayout(uint32_t ssrc) override {
129 rtc::CritScope lock(&crit_);
130 if (event_log_) {
131 event_log_->LogAudioPlayout(ssrc);
132 }
133 }
134
terelius424e6cf2017-02-20 05:14:41 -0800135 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700136 uint8_t fraction_loss,
137 int32_t total_packets) override {
138 rtc::CritScope lock(&crit_);
139 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800140 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
141 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700142 }
143 }
144
terelius424e6cf2017-02-20 05:14:41 -0800145 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800146 BandwidthUsage detector_state) override {
147 rtc::CritScope lock(&crit_);
148 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800149 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800150 }
151 }
152
minyue4b7c9522017-01-24 04:54:59 -0800153 void LogAudioNetworkAdaptation(
michaeltcde46b72017-04-06 05:59:10 -0700154 const AudioEncoderRuntimeConfig& config) override {
minyue4b7c9522017-01-24 04:54:59 -0800155 rtc::CritScope lock(&crit_);
156 if (event_log_) {
157 event_log_->LogAudioNetworkAdaptation(config);
158 }
159 }
160
philipel32d00102017-02-27 02:18:46 -0800161 void LogProbeClusterCreated(int id,
162 int bitrate_bps,
163 int min_probes,
164 int min_bytes) override {
165 rtc::CritScope lock(&crit_);
166 if (event_log_) {
167 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
168 min_bytes);
169 }
170 };
171
172 void LogProbeResultSuccess(int id, int bitrate_bps) override {
173 rtc::CritScope lock(&crit_);
174 if (event_log_) {
175 event_log_->LogProbeResultSuccess(id, bitrate_bps);
176 }
177 };
178
179 void LogProbeResultFailure(int id,
180 ProbeFailureReason failure_reason) override {
181 rtc::CritScope lock(&crit_);
182 if (event_log_) {
183 event_log_->LogProbeResultFailure(id, failure_reason);
184 }
185 };
186
ivoc14d5dbe2016-07-04 07:06:55 -0700187 void SetEventLog(RtcEventLog* event_log) {
188 rtc::CritScope lock(&crit_);
189 event_log_ = event_log;
190 }
191
192 private:
193 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700194 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -0700195 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
196};
197
michaelt9332b7d2016-11-30 07:51:13 -0800198class RtcpRttStatsProxy final : public RtcpRttStats {
199 public:
200 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
201
202 void OnRttUpdate(int64_t rtt) override {
203 rtc::CritScope lock(&crit_);
204 if (rtcp_rtt_stats_)
205 rtcp_rtt_stats_->OnRttUpdate(rtt);
206 }
207
208 int64_t LastProcessedRtt() const override {
209 rtc::CritScope lock(&crit_);
210 if (!rtcp_rtt_stats_)
211 return 0;
212 return rtcp_rtt_stats_->LastProcessedRtt();
213 }
214
215 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
216 rtc::CritScope lock(&crit_);
217 rtcp_rtt_stats_ = rtcp_rtt_stats;
218 }
219
220 private:
221 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700222 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800223 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
224};
225
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100226class TransportFeedbackProxy : public TransportFeedbackObserver {
227 public:
228 TransportFeedbackProxy() : feedback_observer_(nullptr) {
229 pacer_thread_.DetachFromThread();
230 network_thread_.DetachFromThread();
231 }
232
233 void SetTransportFeedbackObserver(
234 TransportFeedbackObserver* feedback_observer) {
235 RTC_DCHECK(thread_checker_.CalledOnValidThread());
236 rtc::CritScope lock(&crit_);
237 feedback_observer_ = feedback_observer;
238 }
239
240 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700241 void AddPacket(uint32_t ssrc,
242 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100243 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800244 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100245 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
246 rtc::CritScope lock(&crit_);
247 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700248 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100249 }
philipel8aadd502017-02-23 02:56:13 -0800250
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100251 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
252 RTC_DCHECK(network_thread_.CalledOnValidThread());
253 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700254 if (feedback_observer_)
255 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200256 }
elad.alonf9490002017-03-06 05:32:21 -0800257 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200258 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800259 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100260 }
261
262 private:
263 rtc::CriticalSection crit_;
264 rtc::ThreadChecker thread_checker_;
265 rtc::ThreadChecker pacer_thread_;
266 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700267 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100268};
269
270class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
271 public:
272 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
273 pacer_thread_.DetachFromThread();
274 }
275
276 void SetSequenceNumberAllocator(
277 TransportSequenceNumberAllocator* seq_num_allocator) {
278 RTC_DCHECK(thread_checker_.CalledOnValidThread());
279 rtc::CritScope lock(&crit_);
280 seq_num_allocator_ = seq_num_allocator;
281 }
282
283 // Implements TransportSequenceNumberAllocator.
284 uint16_t AllocateSequenceNumber() override {
285 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
286 rtc::CritScope lock(&crit_);
287 if (!seq_num_allocator_)
288 return 0;
289 return seq_num_allocator_->AllocateSequenceNumber();
290 }
291
292 private:
293 rtc::CriticalSection crit_;
294 rtc::ThreadChecker thread_checker_;
295 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700296 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100297};
298
299class RtpPacketSenderProxy : public RtpPacketSender {
300 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800301 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100302
303 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
304 RTC_DCHECK(thread_checker_.CalledOnValidThread());
305 rtc::CritScope lock(&crit_);
306 rtp_packet_sender_ = rtp_packet_sender;
307 }
308
309 // Implements RtpPacketSender.
310 void InsertPacket(Priority priority,
311 uint32_t ssrc,
312 uint16_t sequence_number,
313 int64_t capture_time_ms,
314 size_t bytes,
315 bool retransmission) override {
316 rtc::CritScope lock(&crit_);
317 if (rtp_packet_sender_) {
318 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
319 capture_time_ms, bytes, retransmission);
320 }
321 }
322
323 private:
324 rtc::ThreadChecker thread_checker_;
325 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700326 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100327};
328
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000329class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000330 public:
stefan7de8d642017-02-07 07:14:08 -0800331 explicit VoERtcpObserver(Channel* owner)
332 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000333 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000334
stefan7de8d642017-02-07 07:14:08 -0800335 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
336 rtc::CritScope lock(&crit_);
337 bandwidth_observer_ = bandwidth_observer;
338 }
339
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000340 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800341 rtc::CritScope lock(&crit_);
342 if (bandwidth_observer_) {
343 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
344 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000345 }
346
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000347 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
348 int64_t rtt,
349 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800350 {
351 rtc::CritScope lock(&crit_);
352 if (bandwidth_observer_) {
353 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
354 now_ms);
355 }
356 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000357 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
358 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
359 // report for VoiceEngine?
360 if (report_blocks.empty())
361 return;
362
363 int fraction_lost_aggregate = 0;
364 int total_number_of_packets = 0;
365
366 // If receiving multiple report blocks, calculate the weighted average based
367 // on the number of packets a report refers to.
368 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
369 block_it != report_blocks.end(); ++block_it) {
370 // Find the previous extended high sequence number for this remote SSRC,
371 // to calculate the number of RTP packets this report refers to. Ignore if
372 // we haven't seen this SSRC before.
373 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700374 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000375 int number_of_packets = 0;
376 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700377 number_of_packets =
378 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000379 }
srte3e69e5c2017-08-09 06:13:45 -0700380 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000381 total_number_of_packets += number_of_packets;
382
srte3e69e5c2017-08-09 06:13:45 -0700383 extended_max_sequence_number_[block_it->source_ssrc] =
384 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000385 }
386 int weighted_fraction_lost = 0;
387 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800388 weighted_fraction_lost =
389 (fraction_lost_aggregate + total_number_of_packets / 2) /
390 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000391 }
elad.alond12a8e12017-03-23 11:04:48 -0700392 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000393 }
394
395 private:
396 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000397 // Maps remote side ssrc to extended highest sequence number received.
398 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800399 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700400 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000401};
402
henrikaec6fbd22017-03-31 05:43:36 -0700403class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
404 public:
405 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
406 Channel* channel)
407 : audio_frame_(std::move(audio_frame)), channel_(channel) {
408 RTC_DCHECK(channel_);
409 }
410
411 private:
412 bool Run() override {
413 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
414 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
415 return true;
416 }
417
418 std::unique_ptr<AudioFrame> audio_frame_;
419 Channel* const channel_;
420};
421
kwiberg55b97fe2016-01-28 05:22:45 -0800422int32_t Channel::SendData(FrameType frameType,
423 uint8_t payloadType,
424 uint32_t timeStamp,
425 const uint8_t* payloadData,
426 size_t payloadSize,
427 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700428 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800429 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
430 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
431 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
432 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000433
kwiberg55b97fe2016-01-28 05:22:45 -0800434 if (_includeAudioLevelIndication) {
435 // Store current audio level in the RTP/RTCP module.
436 // The level will be used in combination with voice-activity state
437 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800438 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800439 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000440
kwiberg55b97fe2016-01-28 05:22:45 -0800441 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
442 // packetization.
443 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700444 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800445 (FrameType&)frameType, payloadType, timeStamp,
446 // Leaving the time when this frame was
447 // received from the capture device as
448 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700449 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800450 _engineStatisticsPtr->SetLastError(
451 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
452 "Channel::SendData() failed to send data to RTP/RTCP module");
453 return -1;
454 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000455
kwiberg55b97fe2016-01-28 05:22:45 -0800456 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000457}
458
stefan1d8a5062015-10-02 03:39:33 -0700459bool Channel::SendRtp(const uint8_t* data,
460 size_t len,
461 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800462 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
463 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000464
kwiberg55b97fe2016-01-28 05:22:45 -0800465 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000466
kwiberg55b97fe2016-01-28 05:22:45 -0800467 if (_transportPtr == NULL) {
468 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
469 "Channel::SendPacket() failed to send RTP packet due to"
470 " invalid transport object");
471 return false;
472 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000473
kwiberg55b97fe2016-01-28 05:22:45 -0800474 uint8_t* bufferToSendPtr = (uint8_t*)data;
475 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000476
kwiberg55b97fe2016-01-28 05:22:45 -0800477 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
478 std::string transport_name =
479 _externalTransport ? "external transport" : "WebRtc sockets";
480 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
481 "Channel::SendPacket() RTP transmission using %s failed",
482 transport_name.c_str());
483 return false;
484 }
485 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000486}
487
kwiberg55b97fe2016-01-28 05:22:45 -0800488bool Channel::SendRtcp(const uint8_t* data, size_t len) {
489 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
490 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000491
kwiberg55b97fe2016-01-28 05:22:45 -0800492 rtc::CritScope cs(&_callbackCritSect);
493 if (_transportPtr == NULL) {
494 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
495 "Channel::SendRtcp() failed to send RTCP packet"
496 " due to invalid transport object");
497 return false;
498 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000499
kwiberg55b97fe2016-01-28 05:22:45 -0800500 uint8_t* bufferToSendPtr = (uint8_t*)data;
501 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000502
kwiberg55b97fe2016-01-28 05:22:45 -0800503 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
504 if (n < 0) {
505 std::string transport_name =
506 _externalTransport ? "external transport" : "WebRtc sockets";
507 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
508 "Channel::SendRtcp() transmission using %s failed",
509 transport_name.c_str());
510 return false;
511 }
512 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000513}
514
kwiberg55b97fe2016-01-28 05:22:45 -0800515void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
516 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
517 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000518
kwiberg55b97fe2016-01-28 05:22:45 -0800519 // Update ssrc so that NTP for AV sync can be updated.
520 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000521}
522
Peter Boströmac547a62015-09-17 23:03:57 +0200523void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
524 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
525 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
526 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000527}
528
Peter Boströmac547a62015-09-17 23:03:57 +0200529int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000530 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000531 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000532 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800533 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200534 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800535 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
536 "Channel::OnInitializeDecoder(payloadType=%d, "
537 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
538 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000539
kwiberg55b97fe2016-01-28 05:22:45 -0800540 CodecInst receiveCodec = {0};
541 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000542
kwiberg55b97fe2016-01-28 05:22:45 -0800543 receiveCodec.pltype = payloadType;
544 receiveCodec.plfreq = frequency;
545 receiveCodec.channels = channels;
546 receiveCodec.rate = rate;
547 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000548
kwiberg55b97fe2016-01-28 05:22:45 -0800549 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
550 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000551
kwiberg55b97fe2016-01-28 05:22:45 -0800552 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700553 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
554 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800555 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
556 "Channel::OnInitializeDecoder() invalid codec ("
557 "pt=%d, name=%s) received - 1",
558 payloadType, payloadName);
559 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
560 return -1;
561 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000562
kwiberg55b97fe2016-01-28 05:22:45 -0800563 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000564}
565
kwiberg55b97fe2016-01-28 05:22:45 -0800566int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
567 size_t payloadSize,
568 const WebRtcRTPHeader* rtpHeader) {
569 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
570 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
571 ","
572 " payloadType=%u, audioChannel=%" PRIuS ")",
573 payloadSize, rtpHeader->header.payloadType,
574 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000575
kwiberg55b97fe2016-01-28 05:22:45 -0800576 if (!channel_state_.Get().playing) {
577 // Avoid inserting into NetEQ when we are not playing. Count the
578 // packet as discarded.
579 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
580 "received packet is discarded since playing is not"
581 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000582 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800583 }
584
585 // Push the incoming payload (parsed and ready for decoding) into the ACM
586 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
587 0) {
588 _engineStatisticsPtr->SetLastError(
589 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
590 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
591 return -1;
592 }
593
kwiberg55b97fe2016-01-28 05:22:45 -0800594 int64_t round_trip_time = 0;
595 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
596 NULL);
597
598 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
599 if (!nack_list.empty()) {
600 // Can't use nack_list.data() since it's not supported by all
601 // compilers.
602 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
603 }
604 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000605}
606
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000607bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000608 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000609 RTPHeader header;
610 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
611 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
612 "IncomingPacket invalid RTP header");
613 return false;
614 }
615 header.payload_type_frequency =
616 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
617 if (header.payload_type_frequency < 0)
618 return false;
619 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
620}
621
solenberg2397b9a2017-09-22 06:48:10 -0700622AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
623 int sample_rate_hz,
624 AudioFrame* audio_frame) {
625 audio_frame->sample_rate_hz_ = sample_rate_hz;
626
ivoc14d5dbe2016-07-04 07:06:55 -0700627 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800628 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700629 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800630 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700631 bool muted;
solenberg2397b9a2017-09-22 06:48:10 -0700632 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
henrik.lundind4ccb002016-05-17 12:21:55 -0700633 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800634 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
635 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
636 // In all likelihood, the audio in this frame is garbage. We return an
637 // error so that the audio mixer module doesn't add it to the mix. As
638 // a result, it won't be played out and the actions skipped here are
639 // irrelevant.
solenberg2397b9a2017-09-22 06:48:10 -0700640 return AudioMixer::Source::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800641 }
henrik.lundina89ab962016-05-18 08:52:45 -0700642
643 if (muted) {
644 // TODO(henrik.lundin): We should be able to do better than this. But we
645 // will have to go through all the cases below where the audio samples may
646 // be used, and handle the muted case in some way.
solenberg2397b9a2017-09-22 06:48:10 -0700647 AudioFrameOperations::Mute(audio_frame);
henrik.lundina89ab962016-05-18 08:52:45 -0700648 }
kwiberg55b97fe2016-01-28 05:22:45 -0800649
solenberge423a9de2017-09-27 11:28:14 -0700650 // Convert module ID to internal VoE channel ID
651 audio_frame->id_ = VoEChannelId(audio_frame->id_);
kwiberg55b97fe2016-01-28 05:22:45 -0800652 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700653 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800654
kwiberg55b97fe2016-01-28 05:22:45 -0800655 {
656 // Pass the audio buffers to an optional sink callback, before applying
657 // scaling/panning, as that applies to the mix operation.
658 // External recipients of the audio (e.g. via AudioTrack), will do their
659 // own mixing/dynamic processing.
660 rtc::CritScope cs(&_callbackCritSect);
661 if (audio_sink_) {
662 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700663 audio_frame->data(), audio_frame->samples_per_channel_,
664 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
665 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800666 audio_sink_->OnData(data);
667 }
668 }
669
670 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800671 {
672 rtc::CritScope cs(&volume_settings_critsect_);
673 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800674 }
675
676 // Output volume scaling
677 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800678 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700679 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800680 }
681
kwiberg55b97fe2016-01-28 05:22:45 -0800682 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700683 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700684 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700685 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700686 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800687
solenberg2397b9a2017-09-22 06:48:10 -0700688 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800689 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700690 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800691 }
692
693 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700694 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800695
696 // Compute elapsed time.
697 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700698 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
699 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800700 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700701 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800702
niklase@google.com470e71d2011-07-07 08:21:25 +0000703 {
kwiberg55b97fe2016-01-28 05:22:45 -0800704 rtc::CritScope lock(&ts_stats_lock_);
705 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700706 audio_frame->ntp_time_ms_ =
707 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800708 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700709 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800710 // Compute |capture_start_ntp_time_ms_| so that
711 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
712 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700713 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000714 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000715 }
kwiberg55b97fe2016-01-28 05:22:45 -0800716 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000717
solenberg2397b9a2017-09-22 06:48:10 -0700718 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
719 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000720}
721
solenberg2397b9a2017-09-22 06:48:10 -0700722int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800723 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700724 return std::max(audio_coding_->ReceiveFrequency(),
725 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000726}
727
henrikaec6fbd22017-03-31 05:43:36 -0700728int32_t Channel::CreateChannel(Channel*& channel,
729 int32_t channelId,
730 uint32_t instanceId,
731 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800732 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
733 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
734 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000735
solenberg88499ec2016-09-07 07:34:41 -0700736 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800737 if (channel == NULL) {
738 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
739 "Channel::CreateChannel() unable to allocate memory for"
740 " channel");
741 return -1;
742 }
743 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
pbos@webrtc.org92135212013-05-14 08:31:39 +0000746Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000747 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700748 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800749 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100750 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700751 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800752 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100753 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800754 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100755 rtp_receive_statistics_(
756 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
757 rtp_receiver_(
758 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100759 this,
760 this,
761 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700762 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100763 _outputAudioLevel(),
764 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100765 _timeStamp(0), // This is just an offset, RTP module will add it's own
766 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100767 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100768 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100769 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100770 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100771 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
772 capture_start_rtp_time_stamp_(-1),
773 capture_start_ntp_time_ms_(-1),
774 _engineStatisticsPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100775 _moduleProcessThreadPtr(NULL),
776 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100777 _callbackCritSectPtr(NULL),
778 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700779 input_mute_(false),
780 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100781 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100782 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800783 transport_overhead_per_packet_(0),
784 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100785 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100786 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100787 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700788 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800789 feedback_observer_proxy_(new TransportFeedbackProxy()),
790 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700791 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200792 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
793 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700794 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700795 use_twcc_plr_for_ana_(
796 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800797 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
798 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700799 AudioCodingModule::Config acm_config(config.acm_config);
solenberge423a9de2017-09-27 11:28:14 -0700800 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700801 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800802 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200803
kwiberg55b97fe2016-01-28 05:22:45 -0800804 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000805
kwiberg55b97fe2016-01-28 05:22:45 -0800806 RtpRtcp::Configuration configuration;
807 configuration.audio = true;
808 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800809 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800810 configuration.receive_statistics = rtp_receive_statistics_.get();
811 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800812 if (pacing_enabled_) {
813 configuration.paced_sender = rtp_packet_sender_proxy_.get();
814 configuration.transport_sequence_number_allocator =
815 seq_num_allocator_proxy_.get();
816 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
817 }
ivoc14d5dbe2016-07-04 07:06:55 -0700818 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800819 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200820 configuration.retransmission_rate_limiter =
821 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000822
kwiberg55b97fe2016-01-28 05:22:45 -0800823 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100824 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000825}
826
kwiberg55b97fe2016-01-28 05:22:45 -0800827Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700828 RTC_DCHECK(!channel_state_.Get().sending);
829 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000830}
831
kwiberg55b97fe2016-01-28 05:22:45 -0800832int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700833 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800834 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
835 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000836
kwiberg55b97fe2016-01-28 05:22:45 -0800837 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000838
kwiberg55b97fe2016-01-28 05:22:45 -0800839 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000840
kwiberg55b97fe2016-01-28 05:22:45 -0800841 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
842 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
843 "Channel::Init() must call SetEngineInformation() first");
844 return -1;
845 }
846
847 // --- Add modules to process thread (for periodic schedulation)
848
tommidea489f2017-03-03 03:20:24 -0800849 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800850
851 // --- ACM initialization
852
853 if (audio_coding_->InitializeReceiver() == -1) {
854 _engineStatisticsPtr->SetLastError(
855 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
856 "Channel::Init() unable to initialize the ACM - 1");
857 return -1;
858 }
859
860 // --- RTP/RTCP module initialization
861
862 // Ensure that RTCP is enabled by default for the created channel.
863 // Note that, the module will keep generating RTCP until it is explicitly
864 // disabled by the user.
865 // After StopListen (when no sockets exists), RTCP packets will no longer
866 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700867 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800868 // RTCP is enabled by default.
869 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
870 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800871 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800872 _engineStatisticsPtr->SetLastError(
873 VE_CANNOT_INIT_CHANNEL, kTraceError,
874 "Channel::Init() callbacks not registered");
875 return -1;
876 }
877
kwiberg1c07c702017-03-27 07:15:49 -0700878 return 0;
879}
880
tommi0a2391f2017-03-21 02:31:51 -0700881void Channel::Terminate() {
882 RTC_DCHECK(construction_thread_.CalledOnValidThread());
883 // Must be called on the same thread as Init().
884 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
885 "Channel::Terminate");
886
887 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
888
889 StopSend();
890 StopPlayout();
891
tommi0a2391f2017-03-21 02:31:51 -0700892 // The order to safely shutdown modules in a channel is:
893 // 1. De-register callbacks in modules
894 // 2. De-register modules in process thread
895 // 3. Destroy modules
896 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
897 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
898 "Terminate() failed to de-register transport callback"
899 " (Audio coding module)");
900 }
901
tommi0a2391f2017-03-21 02:31:51 -0700902 // De-register modules in process thread
903 if (_moduleProcessThreadPtr)
904 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
905
906 // End of modules shutdown
907}
908
kwiberg55b97fe2016-01-28 05:22:45 -0800909int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
kwiberg55b97fe2016-01-28 05:22:45 -0800910 ProcessThread& moduleProcessThread,
911 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700912 rtc::CriticalSection* callbackCritSect,
913 rtc::TaskQueue* encoder_queue) {
914 RTC_DCHECK(encoder_queue);
915 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800916 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
917 "Channel::SetEngineInformation()");
918 _engineStatisticsPtr = &engineStatistics;
kwiberg55b97fe2016-01-28 05:22:45 -0800919 _moduleProcessThreadPtr = &moduleProcessThread;
920 _audioDeviceModulePtr = &audioDeviceModule;
kwiberg55b97fe2016-01-28 05:22:45 -0800921 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -0700922 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800923 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000924}
925
kwibergb7f89d62016-02-17 10:04:18 -0800926void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800927 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800928 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100929}
930
ossu29b1a8d2016-06-13 07:34:51 -0700931const rtc::scoped_refptr<AudioDecoderFactory>&
932Channel::GetAudioDecoderFactory() const {
933 return decoder_factory_;
934}
935
kwiberg55b97fe2016-01-28 05:22:45 -0800936int32_t Channel::StartPlayout() {
937 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
938 "Channel::StartPlayout()");
939 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000940 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800941 }
942
kwiberg55b97fe2016-01-28 05:22:45 -0800943 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800944
945 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000946}
947
kwiberg55b97fe2016-01-28 05:22:45 -0800948int32_t Channel::StopPlayout() {
949 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
950 "Channel::StopPlayout()");
951 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000952 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800953 }
954
kwiberg55b97fe2016-01-28 05:22:45 -0800955 channel_state_.SetPlaying(false);
956 _outputAudioLevel.Clear();
957
958 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000959}
960
kwiberg55b97fe2016-01-28 05:22:45 -0800961int32_t Channel::StartSend() {
962 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
963 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -0800964 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000965 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800966 }
967 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700968 {
969 // It is now OK to start posting tasks to the encoder task queue.
970 rtc::CritScope cs(&encoder_queue_lock_);
971 encoder_queue_is_active_ = true;
972 }
solenberg08b19df2017-02-15 00:42:31 -0800973 // Resume the previous sequence number which was reset by StopSend(). This
974 // needs to be done before |sending| is set to true on the RTP/RTCP module.
975 if (send_sequence_number_) {
976 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
977 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100978 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800979 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
980 _engineStatisticsPtr->SetLastError(
981 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
982 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100983 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800984 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000985 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800986 return -1;
987 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000988
kwiberg55b97fe2016-01-28 05:22:45 -0800989 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000990}
991
henrikaec6fbd22017-03-31 05:43:36 -0700992void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800993 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
994 "Channel::StopSend()");
995 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700996 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800997 }
998 channel_state_.SetSending(false);
999
henrikaec6fbd22017-03-31 05:43:36 -07001000 // Post a task to the encoder thread which sets an event when the task is
1001 // executed. We know that no more encoding tasks will be added to the task
1002 // queue for this channel since sending is now deactivated. It means that,
1003 // if we wait for the event to bet set, we know that no more pending tasks
1004 // exists and it is therfore guaranteed that the task queue will never try
1005 // to acccess and invalid channel object.
1006 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001007
henrikaec6fbd22017-03-31 05:43:36 -07001008 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001009 {
1010 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1011 // than this final "flush task" to be posted on the queue.
1012 rtc::CritScope cs(&encoder_queue_lock_);
1013 encoder_queue_is_active_ = false;
1014 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1015 }
henrikaec6fbd22017-03-31 05:43:36 -07001016 flush.Wait(rtc::Event::kForever);
1017
kwiberg55b97fe2016-01-28 05:22:45 -08001018 // Store the sequence number to be able to pick up the same sequence for
1019 // the next StartSend(). This is needed for restarting device, otherwise
1020 // it might cause libSRTP to complain about packets being replayed.
1021 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1022 // CL is landed. See issue
1023 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1024 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1025
1026 // Reset sending SSRC and sequence number and triggers direct transmission
1027 // of RTCP BYE
1028 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1029 _engineStatisticsPtr->SetLastError(
1030 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1031 "StartSend() RTP/RTCP failed to stop sending");
1032 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001033 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001034}
1035
ossu1ffbd6c2017-04-06 12:05:04 -07001036bool Channel::SetEncoder(int payload_type,
1037 std::unique_ptr<AudioEncoder> encoder) {
1038 RTC_DCHECK_GE(payload_type, 0);
1039 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001040 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1041 // one for for us to keep track of sample rate and number of channels, etc.
1042
1043 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1044 // as well as some other things, so we collect this info and send it along.
1045 CodecInst rtp_codec;
1046 rtp_codec.pltype = payload_type;
1047 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1048 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001049 // Seems unclear if it should be clock rate or sample rate. CodecInst
1050 // supposedly carries the sample rate, but only clock rate seems sensible to
1051 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001052 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1053 rtp_codec.pacsize = rtc::CheckedDivExact(
1054 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1055 100);
1056 rtp_codec.channels = encoder->NumChannels();
1057 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001058
ossu76d29f92017-06-09 07:30:13 -07001059 // For audio encoding we need, instead, the actual sample rate of the codec.
1060 // The rest of the information should be the same.
1061 CodecInst send_codec = rtp_codec;
1062 send_codec.plfreq = encoder->SampleRateHz();
1063 cached_send_codec_.emplace(send_codec);
1064
1065 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001066 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001067 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001068 WEBRTC_TRACE(
1069 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1070 "SetEncoder() failed to register codec to RTP/RTCP module");
1071 return false;
1072 }
1073 }
1074
1075 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001076 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001077 return true;
1078}
1079
ossu20a4b3f2017-04-27 02:08:52 -07001080void Channel::ModifyEncoder(
1081 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1082 audio_coding_->ModifyEncoder(modifier);
1083}
1084
kwiberg55b97fe2016-01-28 05:22:45 -08001085int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001086 if (cached_send_codec_) {
1087 codec = *cached_send_codec_;
1088 return 0;
1089 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001090 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1091 if (send_codec) {
1092 codec = *send_codec;
1093 return 0;
1094 }
1095 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001096 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001097}
1098
kwiberg55b97fe2016-01-28 05:22:45 -08001099int32_t Channel::GetRecCodec(CodecInst& codec) {
1100 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001101}
1102
kwiberg55b97fe2016-01-28 05:22:45 -08001103int32_t Channel::SetSendCodec(const CodecInst& codec) {
1104 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1105 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001106
kwibergc8d071e2016-04-06 12:22:38 -07001107 if (!codec_manager_.RegisterEncoder(codec) ||
1108 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001109 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1110 "SetSendCodec() failed to register codec to ACM");
1111 return -1;
1112 }
1113
1114 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1115 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1116 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1117 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1118 "SetSendCodec() failed to register codec to"
1119 " RTP/RTCP module");
1120 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001121 }
kwiberg55b97fe2016-01-28 05:22:45 -08001122 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001123
ossu76d29f92017-06-09 07:30:13 -07001124 cached_send_codec_.reset();
1125
kwiberg55b97fe2016-01-28 05:22:45 -08001126 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001127}
1128
minyue78b4d562016-11-30 04:47:39 -08001129void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001130 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1131 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001132 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001133 if (*encoder) {
1134 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001135 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001136 }
1137 });
michaelt566d8202017-01-12 10:17:38 -08001138 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001139}
1140
elad.alond12a8e12017-03-23 11:04:48 -07001141void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1142 if (!use_twcc_plr_for_ana_)
1143 return;
minyue7e304322016-10-12 05:00:55 -07001144 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001145 if (*encoder) {
1146 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1147 }
1148 });
1149}
1150
elad.alondadb4dc2017-03-23 15:29:50 -07001151void Channel::OnRecoverableUplinkPacketLossRate(
1152 float recoverable_packet_loss_rate) {
1153 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1154 if (*encoder) {
1155 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1156 recoverable_packet_loss_rate);
1157 }
1158 });
1159}
1160
elad.alond12a8e12017-03-23 11:04:48 -07001161void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1162 if (use_twcc_plr_for_ana_)
1163 return;
1164 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1165 if (*encoder) {
1166 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1167 }
minyue7e304322016-10-12 05:00:55 -07001168 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001169}
1170
kwiberg1c07c702017-03-27 07:15:49 -07001171void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1172 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1173 audio_coding_->SetReceiveCodecs(codecs);
1174}
1175
minyue7e304322016-10-12 05:00:55 -07001176bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1177 bool success = false;
1178 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1179 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001180 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1181 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001182 }
1183 });
1184 return success;
1185}
1186
1187void Channel::DisableAudioNetworkAdaptor() {
1188 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1189 if (*encoder)
1190 (*encoder)->DisableAudioNetworkAdaptor();
1191 });
1192}
1193
1194void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1195 int max_frame_length_ms) {
1196 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1197 if (*encoder) {
1198 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1199 max_frame_length_ms);
1200 }
1201 });
1202}
1203
mflodman3d7db262016-04-29 00:57:13 -07001204int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001205 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001206 "Channel::RegisterExternalTransport()");
1207
kwiberg55b97fe2016-01-28 05:22:45 -08001208 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001209 if (_externalTransport) {
1210 _engineStatisticsPtr->SetLastError(
1211 VE_INVALID_OPERATION, kTraceError,
1212 "RegisterExternalTransport() external transport already enabled");
1213 return -1;
1214 }
1215 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001216 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001217 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001218}
1219
kwiberg55b97fe2016-01-28 05:22:45 -08001220int32_t Channel::DeRegisterExternalTransport() {
1221 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1222 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001223
kwiberg55b97fe2016-01-28 05:22:45 -08001224 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001225 if (_transportPtr) {
1226 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1227 "DeRegisterExternalTransport() all transport is disabled");
1228 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001229 _engineStatisticsPtr->SetLastError(
1230 VE_INVALID_OPERATION, kTraceWarning,
1231 "DeRegisterExternalTransport() external transport already "
1232 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001233 }
1234 _externalTransport = false;
1235 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001236 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001237}
1238
nisse657bab22017-02-21 06:28:10 -08001239void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1240 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg946d8862017-09-21 04:02:53 -07001241 "Channel::OnRtpPacket()");
nisse657bab22017-02-21 06:28:10 -08001242
1243 RTPHeader header;
1244 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -07001245
1246 // Store playout timestamp for the received RTP packet
1247 UpdatePlayoutTimestamp(false);
1248
1249 header.payload_type_frequency =
1250 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1251 if (header.payload_type_frequency >= 0) {
1252 bool in_order = IsPacketInOrder(header);
1253 rtp_receive_statistics_->IncomingPacket(
1254 header, packet.size(), IsPacketRetransmitted(header, in_order));
1255 rtp_payload_registry_->SetIncomingPayloadType(header);
1256
1257 ReceivePacket(packet.data(), packet.size(), header, in_order);
1258 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001259}
1260
1261bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001262 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001263 const RTPHeader& header,
1264 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001265 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001266 assert(packet_length >= header.headerLength);
1267 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001268 const auto pl =
1269 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1270 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001271 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001272 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001273 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Karl Wiberg73b60b82017-09-21 15:00:58 +02001274 pl->typeSpecific, in_order);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001275}
1276
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001277bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1278 StreamStatistician* statistician =
1279 rtp_receive_statistics_->GetStatistician(header.ssrc);
1280 if (!statistician)
1281 return false;
1282 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001283}
1284
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001285bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1286 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001287 StreamStatistician* statistician =
1288 rtp_receive_statistics_->GetStatistician(header.ssrc);
1289 if (!statistician)
1290 return false;
1291 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001292 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001293 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001294 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001295}
1296
mflodman3d7db262016-04-29 00:57:13 -07001297int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001298 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001299 "Channel::ReceivedRTCPPacket()");
1300 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001301 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001302
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001303 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001304 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001305
Minyue2013aec2015-05-13 14:14:42 +02001306 int64_t rtt = GetRTT(true);
1307 if (rtt == 0) {
1308 // Waiting for valid RTT.
1309 return 0;
1310 }
Erik Språng737336d2016-07-29 12:59:36 +02001311
1312 int64_t nack_window_ms = rtt;
1313 if (nack_window_ms < kMinRetransmissionWindowMs) {
1314 nack_window_ms = kMinRetransmissionWindowMs;
1315 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1316 nack_window_ms = kMaxRetransmissionWindowMs;
1317 }
1318 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1319
minyue7e304322016-10-12 05:00:55 -07001320 // Invoke audio encoders OnReceivedRtt().
1321 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1322 if (*encoder)
1323 (*encoder)->OnReceivedRtt(rtt);
1324 });
1325
Minyue2013aec2015-05-13 14:14:42 +02001326 uint32_t ntp_secs = 0;
1327 uint32_t ntp_frac = 0;
1328 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001329 if (0 !=
1330 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1331 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001332 // Waiting for RTCP.
1333 return 0;
1334 }
1335
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001336 {
tommi31fc21f2016-01-21 10:37:37 -08001337 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001338 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001339 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001340 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001341}
1342
solenberg8d73f8c2017-03-08 01:52:20 -08001343int Channel::GetSpeechOutputLevel() const {
1344 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001345}
1346
solenberg8d73f8c2017-03-08 01:52:20 -08001347int Channel::GetSpeechOutputLevelFullRange() const {
1348 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001349}
1350
zsteine76bd3a2017-07-14 12:17:49 -07001351double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001352 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001353}
1354
1355double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001356 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001357}
1358
solenberg8d73f8c2017-03-08 01:52:20 -08001359void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001360 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001361 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001362}
1363
solenberg1c2af8e2016-03-24 10:36:00 -07001364bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001365 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001366 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001367}
1368
solenberg8d73f8c2017-03-08 01:52:20 -08001369void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001370 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001371 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001372}
1373
solenberg8842c3e2016-03-11 03:06:41 -08001374int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001375 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001376 "Channel::SendTelephoneEventOutband(...)");
1377 RTC_DCHECK_LE(0, event);
1378 RTC_DCHECK_GE(255, event);
1379 RTC_DCHECK_LE(0, duration_ms);
1380 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001381 if (!Sending()) {
1382 return -1;
1383 }
solenberg8842c3e2016-03-11 03:06:41 -08001384 if (_rtpRtcpModule->SendTelephoneEventOutband(
1385 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001386 _engineStatisticsPtr->SetLastError(
1387 VE_SEND_DTMF_FAILED, kTraceWarning,
1388 "SendTelephoneEventOutband() failed to send event");
1389 return -1;
1390 }
1391 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001392}
1393
solenbergffbbcac2016-11-17 05:25:37 -08001394int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1395 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001396 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001397 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001398 RTC_DCHECK_LE(0, payload_type);
1399 RTC_DCHECK_GE(127, payload_type);
1400 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001401 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001402 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001403 memcpy(codec.plname, "telephone-event", 16);
1404 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1405 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1406 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1407 _engineStatisticsPtr->SetLastError(
1408 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1409 "SetSendTelephoneEventPayloadType() failed to register send"
1410 "payload type");
1411 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001412 }
kwiberg55b97fe2016-01-28 05:22:45 -08001413 }
kwiberg55b97fe2016-01-28 05:22:45 -08001414 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001415}
1416
kwiberg55b97fe2016-01-28 05:22:45 -08001417int Channel::SetLocalSSRC(unsigned int ssrc) {
1418 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1419 "Channel::SetLocalSSRC()");
1420 if (channel_state_.Get().sending) {
1421 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
1422 "SetLocalSSRC() already sending");
1423 return -1;
1424 }
1425 _rtpRtcpModule->SetSSRC(ssrc);
1426 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001427}
1428
kwiberg55b97fe2016-01-28 05:22:45 -08001429int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1430 ssrc = rtp_receiver_->SSRC();
1431 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001432}
1433
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001434int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001435 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001436 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001437}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001438
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001439int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1440 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001441 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1442 if (enable &&
1443 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1444 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001445 return -1;
1446 }
1447 return 0;
1448}
1449
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001450void Channel::EnableSendTransportSequenceNumber(int id) {
1451 int ret =
1452 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1453 RTC_DCHECK_EQ(0, ret);
1454}
1455
stefan3313ec92016-01-21 06:32:43 -08001456void Channel::EnableReceiveTransportSequenceNumber(int id) {
1457 rtp_header_parser_->DeregisterRtpHeaderExtension(
1458 kRtpExtensionTransportSequenceNumber);
1459 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1460 kRtpExtensionTransportSequenceNumber, id);
1461 RTC_DCHECK(ret);
1462}
1463
stefanbba9dec2016-02-01 04:39:55 -08001464void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001465 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001466 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001467 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1468 TransportFeedbackObserver* transport_feedback_observer =
1469 transport->transport_feedback_observer();
1470 PacketRouter* packet_router = transport->packet_router();
1471
stefanbba9dec2016-02-01 04:39:55 -08001472 RTC_DCHECK(rtp_packet_sender);
1473 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001474 RTC_DCHECK(packet_router);
1475 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001476 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001477 feedback_observer_proxy_->SetTransportFeedbackObserver(
1478 transport_feedback_observer);
1479 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1480 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1481 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001482 constexpr bool remb_candidate = false;
1483 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001484 packet_router_ = packet_router;
1485}
1486
stefanbba9dec2016-02-01 04:39:55 -08001487void Channel::RegisterReceiverCongestionControlObjects(
1488 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001489 RTC_DCHECK(packet_router);
1490 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001491 constexpr bool remb_candidate = false;
1492 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001493 packet_router_ = packet_router;
1494}
1495
nissefdbfdc92017-03-31 05:44:52 -07001496void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001497 RTC_DCHECK(packet_router_);
1498 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001499 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001500 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1501 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001502 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001503 packet_router_ = nullptr;
1504 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1505}
1506
nissefdbfdc92017-03-31 05:44:52 -07001507void Channel::ResetReceiverCongestionControlObjects() {
1508 RTC_DCHECK(packet_router_);
1509 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1510 packet_router_ = nullptr;
1511}
1512
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001513void Channel::SetRTCPStatus(bool enable) {
1514 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1515 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001516 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001517}
1518
kwiberg55b97fe2016-01-28 05:22:45 -08001519int Channel::SetRTCP_CNAME(const char cName[256]) {
1520 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1521 "Channel::SetRTCP_CNAME()");
1522 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
1523 _engineStatisticsPtr->SetLastError(
1524 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1525 "SetRTCP_CNAME() failed to set RTCP CNAME");
1526 return -1;
1527 }
1528 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001529}
1530
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001531int Channel::GetRemoteRTCPReportBlocks(
1532 std::vector<ReportBlock>* report_blocks) {
1533 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08001534 _engineStatisticsPtr->SetLastError(
1535 VE_INVALID_ARGUMENT, kTraceError,
1536 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001537 return -1;
1538 }
1539
1540 // Get the report blocks from the latest received RTCP Sender or Receiver
1541 // Report. Each element in the vector contains the sender's SSRC and a
1542 // report block according to RFC 3550.
1543 std::vector<RTCPReportBlock> rtcp_report_blocks;
1544 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001545 return -1;
1546 }
1547
1548 if (rtcp_report_blocks.empty())
1549 return 0;
1550
1551 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1552 for (; it != rtcp_report_blocks.end(); ++it) {
1553 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001554 report_block.sender_SSRC = it->sender_ssrc;
1555 report_block.source_SSRC = it->source_ssrc;
1556 report_block.fraction_lost = it->fraction_lost;
1557 report_block.cumulative_num_packets_lost = it->packets_lost;
1558 report_block.extended_highest_sequence_number =
1559 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001560 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001561 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1562 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001563 report_blocks->push_back(report_block);
1564 }
1565 return 0;
1566}
1567
kwiberg55b97fe2016-01-28 05:22:45 -08001568int Channel::GetRTPStatistics(CallStatistics& stats) {
1569 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001570
kwiberg55b97fe2016-01-28 05:22:45 -08001571 // The jitter statistics is updated for each received RTP packet and is
1572 // based on received packets.
1573 RtcpStatistics statistics;
1574 StreamStatistician* statistician =
1575 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001576 if (statistician) {
1577 statistician->GetStatistics(&statistics,
1578 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001579 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001580
kwiberg55b97fe2016-01-28 05:22:45 -08001581 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001582 stats.cumulativeLost = statistics.packets_lost;
1583 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001584 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001585
kwiberg55b97fe2016-01-28 05:22:45 -08001586 // --- RTT
1587 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001588
kwiberg55b97fe2016-01-28 05:22:45 -08001589 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001590
kwiberg55b97fe2016-01-28 05:22:45 -08001591 size_t bytesSent(0);
1592 uint32_t packetsSent(0);
1593 size_t bytesReceived(0);
1594 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001595
kwiberg55b97fe2016-01-28 05:22:45 -08001596 if (statistician) {
1597 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1598 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001599
kwiberg55b97fe2016-01-28 05:22:45 -08001600 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
1601 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1602 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
1603 " output will not be complete");
1604 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001605
kwiberg55b97fe2016-01-28 05:22:45 -08001606 stats.bytesSent = bytesSent;
1607 stats.packetsSent = packetsSent;
1608 stats.bytesReceived = bytesReceived;
1609 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001610
kwiberg55b97fe2016-01-28 05:22:45 -08001611 // --- Timestamps
1612 {
1613 rtc::CritScope lock(&ts_stats_lock_);
1614 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1615 }
1616 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001617}
1618
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001619void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1620 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001621 // If pacing is enabled we always store packets.
1622 if (!pacing_enabled_)
1623 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001624 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001625 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001626 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001627 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001628 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001629}
1630
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001631// Called when we are missing one or more packets.
1632int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001633 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1634}
1635
henrikaec6fbd22017-03-31 05:43:36 -07001636void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001637 // Avoid posting any new tasks if sending was already stopped in StopSend().
1638 rtc::CritScope cs(&encoder_queue_lock_);
1639 if (!encoder_queue_is_active_) {
1640 return;
1641 }
henrikaec6fbd22017-03-31 05:43:36 -07001642 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1643 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1644 // either into pool of frames or into the task itself.
1645 audio_frame->CopyFrom(audio_input);
solenberge423a9de2017-09-27 11:28:14 -07001646 audio_frame->id_ = ChannelId();
henrika45802172017-09-28 09:39:34 +02001647 // Profile time between when the audio frame is added to the task queue and
1648 // when the task is actually executed.
1649 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001650 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1651 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001652}
1653
henrikaec6fbd22017-03-31 05:43:36 -07001654void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1655 int sample_rate,
1656 size_t number_of_frames,
1657 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001658 // Avoid posting as new task if sending was already stopped in StopSend().
1659 rtc::CritScope cs(&encoder_queue_lock_);
1660 if (!encoder_queue_is_active_) {
1661 return;
1662 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001663 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001664 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001665 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
solenberge423a9de2017-09-27 11:28:14 -07001666 audio_frame->id_ = ChannelId();
ossu950c1c92017-07-11 08:19:31 -07001667 // TODO(ossu): Investigate how this could happen. b/62909493
1668 if (result == 0) {
1669 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1670 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1671 } else {
1672 audio_frame->sample_rate_hz_ = sample_rate;
1673 audio_frame->num_channels_ = number_of_channels;
1674 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1675 RTC_NOTREACHED();
1676 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001677 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001678 sample_rate, &input_resampler_, audio_frame.get());
1679 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1680 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001681}
1682
henrikaec6fbd22017-03-31 05:43:36 -07001683void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1684 RTC_DCHECK_RUN_ON(encoder_queue_);
1685 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1686 RTC_DCHECK_LE(audio_input->num_channels_, 2);
solenberge423a9de2017-09-27 11:28:14 -07001687 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08001688
henrika45802172017-09-28 09:39:34 +02001689 // Measure time between when the audio frame is added to the task queue and
1690 // when the task is actually executed. Goal is to keep track of unwanted
1691 // extra latency added by the task queue.
1692 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1693 audio_input->ElapsedProfileTimeMs());
1694
henrikaec6fbd22017-03-31 05:43:36 -07001695 bool is_muted = InputMute();
1696 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001697
kwiberg55b97fe2016-01-28 05:22:45 -08001698 if (_includeAudioLevelIndication) {
1699 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001700 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001701 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001702 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001703 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001704 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001705 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001706 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001707 }
kwiberg55b97fe2016-01-28 05:22:45 -08001708 }
solenberg1c2af8e2016-03-24 10:36:00 -07001709 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001710
henrikaec6fbd22017-03-31 05:43:36 -07001711 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001712
kwiberg55b97fe2016-01-28 05:22:45 -08001713 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001714 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001715 // This call will trigger AudioPacketizationCallback::SendData if encoding
1716 // is done and payload is ready for packetization and transmission.
1717 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001718 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1719 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1720 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001721 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001722
henrikaec6fbd22017-03-31 05:43:36 -07001723 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001724}
1725
solenberg7602aab2016-11-14 11:30:07 -08001726void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1727 RTC_DCHECK(!channel.channel() ||
1728 channel.channel()->ChannelId() != _channelId);
1729 rtc::CritScope lock(&assoc_send_channel_lock_);
1730 associate_send_channel_ = channel;
1731}
1732
Minyue2013aec2015-05-13 14:14:42 +02001733void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001734 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001735 Channel* channel = associate_send_channel_.channel();
1736 if (channel && channel->ChannelId() == channel_id) {
1737 // If this channel is associated with a send channel of the specified
1738 // Channel ID, disassociate with it.
1739 ChannelOwner ref(NULL);
1740 associate_send_channel_ = ref;
1741 }
1742}
1743
ivoc14d5dbe2016-07-04 07:06:55 -07001744void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1745 event_log_proxy_->SetEventLog(event_log);
1746}
1747
michaelt9332b7d2016-11-30 07:51:13 -08001748void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1749 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1750}
1751
nisse284542b2017-01-10 08:58:32 -08001752void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001753 size_t overhead_per_packet =
1754 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001755 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1756 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001757 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001758 }
1759 });
1760}
1761
1762void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001763 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001764 transport_overhead_per_packet_ = transport_overhead_per_packet;
1765 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001766}
1767
hbos3fd31fe2017-02-28 05:43:16 -08001768// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001769void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001770 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001771 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1772 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001773}
1774
kwiberg55b97fe2016-01-28 05:22:45 -08001775int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1776 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001777}
1778
wu@webrtc.org24301a62013-12-13 19:17:43 +00001779void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1780 audio_coding_->GetDecodingCallStatistics(stats);
1781}
1782
ivoce1198e02017-09-08 08:13:19 -07001783ANAStats Channel::GetANAStatistics() const {
1784 return audio_coding_->GetANAStats();
1785}
1786
solenberg358057b2015-11-27 10:46:42 -08001787uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001788 rtc::CritScope lock(&video_sync_lock_);
1789 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001790}
1791
kwiberg55b97fe2016-01-28 05:22:45 -08001792int Channel::SetMinimumPlayoutDelay(int delayMs) {
1793 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1794 "Channel::SetMinimumPlayoutDelay()");
1795 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1796 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
1797 _engineStatisticsPtr->SetLastError(
1798 VE_INVALID_ARGUMENT, kTraceError,
1799 "SetMinimumPlayoutDelay() invalid min delay");
1800 return -1;
1801 }
1802 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
1803 _engineStatisticsPtr->SetLastError(
1804 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1805 "SetMinimumPlayoutDelay() failed to set min playout delay");
1806 return -1;
1807 }
1808 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001809}
1810
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001811int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001812 uint32_t playout_timestamp_rtp = 0;
1813 {
tommi31fc21f2016-01-21 10:37:37 -08001814 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001815 playout_timestamp_rtp = playout_timestamp_rtp_;
1816 }
kwiberg55b97fe2016-01-28 05:22:45 -08001817 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001818 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07001819 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001820 "GetPlayoutTimestamp() failed to retrieve timestamp");
1821 return -1;
1822 }
deadbeef74375882015-08-13 12:09:10 -07001823 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001824 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001825}
1826
kwiberg55b97fe2016-01-28 05:22:45 -08001827int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1828 RtpReceiver** rtp_receiver) const {
1829 *rtpRtcpModule = _rtpRtcpModule.get();
1830 *rtp_receiver = rtp_receiver_.get();
1831 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001832}
1833
deadbeef74375882015-08-13 12:09:10 -07001834void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001835 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001836
henrik.lundin96bd5022016-04-06 04:13:56 -07001837 if (!jitter_buffer_playout_timestamp_) {
1838 // This can happen if this channel has not received any RTP packets. In
1839 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001840 return;
1841 }
1842
1843 uint16_t delay_ms = 0;
1844 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001845 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001846 "Channel::UpdatePlayoutTimestamp() failed to read playout"
1847 " delay from the ADM");
1848 _engineStatisticsPtr->SetLastError(
1849 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
1850 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
1851 return;
1852 }
1853
henrik.lundin96bd5022016-04-06 04:13:56 -07001854 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1855 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001856
1857 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001858 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001859
kwiberg55b97fe2016-01-28 05:22:45 -08001860 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001861 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07001862 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07001863
1864 {
tommi31fc21f2016-01-21 10:37:37 -08001865 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001866 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001867 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001868 }
1869 playout_delay_ms_ = delay_ms;
1870 }
1871}
1872
kwiberg55b97fe2016-01-28 05:22:45 -08001873void Channel::RegisterReceiveCodecsToRTPModule() {
1874 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1875 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001876
kwiberg55b97fe2016-01-28 05:22:45 -08001877 CodecInst codec;
1878 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00001879
kwiberg55b97fe2016-01-28 05:22:45 -08001880 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1881 // Open up the RTP/RTCP receiver for all supported codecs
1882 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001883 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001884 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1885 "Channel::RegisterReceiveCodecsToRTPModule() unable"
1886 " to register %s (%d/%d/%" PRIuS
1887 "/%d) to RTP/RTCP "
1888 "receiver",
1889 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1890 codec.rate);
1891 } else {
1892 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1893 "Channel::RegisterReceiveCodecsToRTPModule() %s "
1894 "(%d/%d/%" PRIuS
1895 "/%d) has been added to the RTP/RTCP "
1896 "receiver",
1897 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1898 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001899 }
kwiberg55b97fe2016-01-28 05:22:45 -08001900 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001901}
1902
kwiberg55b97fe2016-01-28 05:22:45 -08001903int Channel::SetSendRtpHeaderExtension(bool enable,
1904 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001905 unsigned char id) {
1906 int error = 0;
1907 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1908 if (enable) {
1909 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1910 }
1911 return error;
1912}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001913
ossue280cde2016-10-12 11:04:10 -07001914int Channel::GetRtpTimestampRateHz() const {
1915 const auto format = audio_coding_->ReceiveFormat();
1916 // Default to the playout frequency if we've not gotten any packets yet.
1917 // TODO(ossu): Zero clockrate can only happen if we've added an external
1918 // decoder for a format we don't support internally. Remove once that way of
1919 // adding decoders is gone!
1920 return (format && format->clockrate_hz != 0)
1921 ? format->clockrate_hz
1922 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001923}
1924
Minyue2013aec2015-05-13 14:14:42 +02001925int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001926 RtcpMode method = _rtpRtcpModule->RTCP();
1927 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001928 return 0;
1929 }
1930 std::vector<RTCPReportBlock> report_blocks;
1931 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001932
1933 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001934 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001935 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001936 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001937 Channel* channel = associate_send_channel_.channel();
1938 // Tries to get RTT from an associated channel. This is important for
1939 // receive-only channels.
1940 if (channel) {
1941 // To prevent infinite recursion and deadlock, calling GetRTT of
1942 // associate channel should always use "false" for argument:
1943 // |allow_associate_channel|.
1944 rtt = channel->GetRTT(false);
1945 }
1946 }
1947 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001948 }
1949
1950 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1951 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1952 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001953 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001954 break;
1955 }
1956 if (it == report_blocks.end()) {
1957 // We have not received packets with SSRC matching the report blocks.
1958 // To calculate RTT we try with the SSRC of the first report block.
1959 // This is very important for send-only channels where we don't know
1960 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001961 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001962 }
Minyue2013aec2015-05-13 14:14:42 +02001963
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001964 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001965 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001966 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001967 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1968 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001969 return 0;
1970 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001971 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001972}
1973
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001974} // namespace voe
1975} // namespace webrtc