blob: 43088b696af4e454bf691f30e1f460603f9f4990 [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
kwiberg55b97fe2016-01-28 05:22:45 -0800650 // Store speech type for dead-or-alive detection
solenberg2397b9a2017-09-22 06:48:10 -0700651 _outputSpeechType = audio_frame->speech_type_;
kwiberg55b97fe2016-01-28 05:22:45 -0800652
kwiberg55b97fe2016-01-28 05:22:45 -0800653 {
654 // Pass the audio buffers to an optional sink callback, before applying
655 // scaling/panning, as that applies to the mix operation.
656 // External recipients of the audio (e.g. via AudioTrack), will do their
657 // own mixing/dynamic processing.
658 rtc::CritScope cs(&_callbackCritSect);
659 if (audio_sink_) {
660 AudioSinkInterface::Data data(
solenberg2397b9a2017-09-22 06:48:10 -0700661 audio_frame->data(), audio_frame->samples_per_channel_,
662 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
663 audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800664 audio_sink_->OnData(data);
665 }
666 }
667
668 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800669 {
670 rtc::CritScope cs(&volume_settings_critsect_);
671 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800672 }
673
674 // Output volume scaling
675 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800676 // TODO(solenberg): Combine with mute state - this can cause clicks!
solenberg2397b9a2017-09-22 06:48:10 -0700677 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
kwiberg55b97fe2016-01-28 05:22:45 -0800678 }
679
kwiberg55b97fe2016-01-28 05:22:45 -0800680 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700681 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700682 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700683 // https://crbug.com/webrtc/7517).
solenberg2397b9a2017-09-22 06:48:10 -0700684 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800685
solenberg2397b9a2017-09-22 06:48:10 -0700686 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800687 // The first frame with a valid rtp timestamp.
solenberg2397b9a2017-09-22 06:48:10 -0700688 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
kwiberg55b97fe2016-01-28 05:22:45 -0800689 }
690
691 if (capture_start_rtp_time_stamp_ >= 0) {
solenberg2397b9a2017-09-22 06:48:10 -0700692 // audio_frame.timestamp_ should be valid from now on.
kwiberg55b97fe2016-01-28 05:22:45 -0800693
694 // Compute elapsed time.
695 int64_t unwrap_timestamp =
solenberg2397b9a2017-09-22 06:48:10 -0700696 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
697 audio_frame->elapsed_time_ms_ =
kwiberg55b97fe2016-01-28 05:22:45 -0800698 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700699 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800700
niklase@google.com470e71d2011-07-07 08:21:25 +0000701 {
kwiberg55b97fe2016-01-28 05:22:45 -0800702 rtc::CritScope lock(&ts_stats_lock_);
703 // Compute ntp time.
solenberg2397b9a2017-09-22 06:48:10 -0700704 audio_frame->ntp_time_ms_ =
705 ntp_estimator_.Estimate(audio_frame->timestamp_);
kwiberg55b97fe2016-01-28 05:22:45 -0800706 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
solenberg2397b9a2017-09-22 06:48:10 -0700707 if (audio_frame->ntp_time_ms_ > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800708 // Compute |capture_start_ntp_time_ms_| so that
709 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
710 capture_start_ntp_time_ms_ =
solenberg2397b9a2017-09-22 06:48:10 -0700711 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000712 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000713 }
kwiberg55b97fe2016-01-28 05:22:45 -0800714 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000715
solenberg2397b9a2017-09-22 06:48:10 -0700716 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
717 : AudioMixer::Source::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000718}
719
solenberg2397b9a2017-09-22 06:48:10 -0700720int Channel::PreferredSampleRate() const {
kwiberg55b97fe2016-01-28 05:22:45 -0800721 // Return the bigger of playout and receive frequency in the ACM.
solenberg2397b9a2017-09-22 06:48:10 -0700722 return std::max(audio_coding_->ReceiveFrequency(),
723 audio_coding_->PlayoutFrequency());
niklase@google.com470e71d2011-07-07 08:21:25 +0000724}
725
henrikaec6fbd22017-03-31 05:43:36 -0700726int32_t Channel::CreateChannel(Channel*& channel,
727 int32_t channelId,
728 uint32_t instanceId,
729 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800730 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
731 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
732 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000733
solenberg88499ec2016-09-07 07:34:41 -0700734 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800735 if (channel == NULL) {
736 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
737 "Channel::CreateChannel() unable to allocate memory for"
738 " channel");
739 return -1;
740 }
741 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000742}
743
pbos@webrtc.org92135212013-05-14 08:31:39 +0000744Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000745 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700746 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800747 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100748 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700749 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800750 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100751 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800752 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100753 rtp_receive_statistics_(
754 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
755 rtp_receiver_(
756 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100757 this,
758 this,
759 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700760 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100761 _outputAudioLevel(),
762 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100763 _timeStamp(0), // This is just an offset, RTP module will add it's own
764 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100765 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100766 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100767 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100768 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100769 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
770 capture_start_rtp_time_stamp_(-1),
771 capture_start_ntp_time_ms_(-1),
772 _engineStatisticsPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100773 _moduleProcessThreadPtr(NULL),
774 _audioDeviceModulePtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100775 _callbackCritSectPtr(NULL),
776 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700777 input_mute_(false),
778 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100779 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100780 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800781 transport_overhead_per_packet_(0),
782 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100783 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100784 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100785 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700786 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800787 feedback_observer_proxy_(new TransportFeedbackProxy()),
788 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700789 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200790 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
791 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700792 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700793 use_twcc_plr_for_ana_(
794 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800795 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
796 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700797 AudioCodingModule::Config acm_config(config.acm_config);
henrik.lundina89ab962016-05-18 08:52:45 -0700798 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800799 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200800
kwiberg55b97fe2016-01-28 05:22:45 -0800801 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000802
kwiberg55b97fe2016-01-28 05:22:45 -0800803 RtpRtcp::Configuration configuration;
804 configuration.audio = true;
805 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800806 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800807 configuration.receive_statistics = rtp_receive_statistics_.get();
808 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800809 if (pacing_enabled_) {
810 configuration.paced_sender = rtp_packet_sender_proxy_.get();
811 configuration.transport_sequence_number_allocator =
812 seq_num_allocator_proxy_.get();
813 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
814 }
ivoc14d5dbe2016-07-04 07:06:55 -0700815 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800816 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200817 configuration.retransmission_rate_limiter =
818 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000819
kwiberg55b97fe2016-01-28 05:22:45 -0800820 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100821 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000822}
823
kwiberg55b97fe2016-01-28 05:22:45 -0800824Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700825 RTC_DCHECK(!channel_state_.Get().sending);
826 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000827}
828
kwiberg55b97fe2016-01-28 05:22:45 -0800829int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700830 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800831 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
832 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000833
kwiberg55b97fe2016-01-28 05:22:45 -0800834 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000835
kwiberg55b97fe2016-01-28 05:22:45 -0800836 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000837
kwiberg55b97fe2016-01-28 05:22:45 -0800838 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
839 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
840 "Channel::Init() must call SetEngineInformation() first");
841 return -1;
842 }
843
844 // --- Add modules to process thread (for periodic schedulation)
845
tommidea489f2017-03-03 03:20:24 -0800846 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800847
848 // --- ACM initialization
849
850 if (audio_coding_->InitializeReceiver() == -1) {
851 _engineStatisticsPtr->SetLastError(
852 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
853 "Channel::Init() unable to initialize the ACM - 1");
854 return -1;
855 }
856
857 // --- RTP/RTCP module initialization
858
859 // Ensure that RTCP is enabled by default for the created channel.
860 // Note that, the module will keep generating RTCP until it is explicitly
861 // disabled by the user.
862 // After StopListen (when no sockets exists), RTCP packets will no longer
863 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700864 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800865 // RTCP is enabled by default.
866 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
867 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800868 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800869 _engineStatisticsPtr->SetLastError(
870 VE_CANNOT_INIT_CHANNEL, kTraceError,
871 "Channel::Init() callbacks not registered");
872 return -1;
873 }
874
kwiberg1c07c702017-03-27 07:15:49 -0700875 return 0;
876}
877
tommi0a2391f2017-03-21 02:31:51 -0700878void Channel::Terminate() {
879 RTC_DCHECK(construction_thread_.CalledOnValidThread());
880 // Must be called on the same thread as Init().
881 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
882 "Channel::Terminate");
883
884 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
885
886 StopSend();
887 StopPlayout();
888
tommi0a2391f2017-03-21 02:31:51 -0700889 // The order to safely shutdown modules in a channel is:
890 // 1. De-register callbacks in modules
891 // 2. De-register modules in process thread
892 // 3. Destroy modules
893 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
894 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
895 "Terminate() failed to de-register transport callback"
896 " (Audio coding module)");
897 }
898
tommi0a2391f2017-03-21 02:31:51 -0700899 // De-register modules in process thread
900 if (_moduleProcessThreadPtr)
901 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
902
903 // End of modules shutdown
904}
905
kwiberg55b97fe2016-01-28 05:22:45 -0800906int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
kwiberg55b97fe2016-01-28 05:22:45 -0800907 ProcessThread& moduleProcessThread,
908 AudioDeviceModule& audioDeviceModule,
henrikaec6fbd22017-03-31 05:43:36 -0700909 rtc::CriticalSection* callbackCritSect,
910 rtc::TaskQueue* encoder_queue) {
911 RTC_DCHECK(encoder_queue);
912 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800913 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
914 "Channel::SetEngineInformation()");
915 _engineStatisticsPtr = &engineStatistics;
kwiberg55b97fe2016-01-28 05:22:45 -0800916 _moduleProcessThreadPtr = &moduleProcessThread;
917 _audioDeviceModulePtr = &audioDeviceModule;
kwiberg55b97fe2016-01-28 05:22:45 -0800918 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -0700919 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -0800920 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000921}
922
kwibergb7f89d62016-02-17 10:04:18 -0800923void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -0800924 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -0800925 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +0100926}
927
ossu29b1a8d2016-06-13 07:34:51 -0700928const rtc::scoped_refptr<AudioDecoderFactory>&
929Channel::GetAudioDecoderFactory() const {
930 return decoder_factory_;
931}
932
kwiberg55b97fe2016-01-28 05:22:45 -0800933int32_t Channel::StartPlayout() {
934 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
935 "Channel::StartPlayout()");
936 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000937 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800938 }
939
kwiberg55b97fe2016-01-28 05:22:45 -0800940 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800941
942 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000943}
944
kwiberg55b97fe2016-01-28 05:22:45 -0800945int32_t Channel::StopPlayout() {
946 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
947 "Channel::StopPlayout()");
948 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000949 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800950 }
951
kwiberg55b97fe2016-01-28 05:22:45 -0800952 channel_state_.SetPlaying(false);
953 _outputAudioLevel.Clear();
954
955 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000956}
957
kwiberg55b97fe2016-01-28 05:22:45 -0800958int32_t Channel::StartSend() {
959 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
960 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -0800961 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000962 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800963 }
964 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -0700965 {
966 // It is now OK to start posting tasks to the encoder task queue.
967 rtc::CritScope cs(&encoder_queue_lock_);
968 encoder_queue_is_active_ = true;
969 }
solenberg08b19df2017-02-15 00:42:31 -0800970 // Resume the previous sequence number which was reset by StopSend(). This
971 // needs to be done before |sending| is set to true on the RTP/RTCP module.
972 if (send_sequence_number_) {
973 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
974 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100975 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800976 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
977 _engineStatisticsPtr->SetLastError(
978 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
979 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100980 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800981 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000982 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -0800983 return -1;
984 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +0000985
kwiberg55b97fe2016-01-28 05:22:45 -0800986 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000987}
988
henrikaec6fbd22017-03-31 05:43:36 -0700989void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -0800990 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
991 "Channel::StopSend()");
992 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -0700993 return;
kwiberg55b97fe2016-01-28 05:22:45 -0800994 }
995 channel_state_.SetSending(false);
996
henrikaec6fbd22017-03-31 05:43:36 -0700997 // Post a task to the encoder thread which sets an event when the task is
998 // executed. We know that no more encoding tasks will be added to the task
999 // queue for this channel since sending is now deactivated. It means that,
1000 // if we wait for the event to bet set, we know that no more pending tasks
1001 // exists and it is therfore guaranteed that the task queue will never try
1002 // to acccess and invalid channel object.
1003 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001004
henrikaec6fbd22017-03-31 05:43:36 -07001005 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001006 {
1007 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1008 // than this final "flush task" to be posted on the queue.
1009 rtc::CritScope cs(&encoder_queue_lock_);
1010 encoder_queue_is_active_ = false;
1011 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1012 }
henrikaec6fbd22017-03-31 05:43:36 -07001013 flush.Wait(rtc::Event::kForever);
1014
kwiberg55b97fe2016-01-28 05:22:45 -08001015 // Store the sequence number to be able to pick up the same sequence for
1016 // the next StartSend(). This is needed for restarting device, otherwise
1017 // it might cause libSRTP to complain about packets being replayed.
1018 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1019 // CL is landed. See issue
1020 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1021 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1022
1023 // Reset sending SSRC and sequence number and triggers direct transmission
1024 // of RTCP BYE
1025 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1026 _engineStatisticsPtr->SetLastError(
1027 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1028 "StartSend() RTP/RTCP failed to stop sending");
1029 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001030 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001031}
1032
ossu1ffbd6c2017-04-06 12:05:04 -07001033bool Channel::SetEncoder(int payload_type,
1034 std::unique_ptr<AudioEncoder> encoder) {
1035 RTC_DCHECK_GE(payload_type, 0);
1036 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001037 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1038 // one for for us to keep track of sample rate and number of channels, etc.
1039
1040 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1041 // as well as some other things, so we collect this info and send it along.
1042 CodecInst rtp_codec;
1043 rtp_codec.pltype = payload_type;
1044 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1045 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001046 // Seems unclear if it should be clock rate or sample rate. CodecInst
1047 // supposedly carries the sample rate, but only clock rate seems sensible to
1048 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001049 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1050 rtp_codec.pacsize = rtc::CheckedDivExact(
1051 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1052 100);
1053 rtp_codec.channels = encoder->NumChannels();
1054 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001055
ossu76d29f92017-06-09 07:30:13 -07001056 // For audio encoding we need, instead, the actual sample rate of the codec.
1057 // The rest of the information should be the same.
1058 CodecInst send_codec = rtp_codec;
1059 send_codec.plfreq = encoder->SampleRateHz();
1060 cached_send_codec_.emplace(send_codec);
1061
1062 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001063 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001064 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001065 WEBRTC_TRACE(
1066 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1067 "SetEncoder() failed to register codec to RTP/RTCP module");
1068 return false;
1069 }
1070 }
1071
1072 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001073 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001074 return true;
1075}
1076
ossu20a4b3f2017-04-27 02:08:52 -07001077void Channel::ModifyEncoder(
1078 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1079 audio_coding_->ModifyEncoder(modifier);
1080}
1081
kwiberg55b97fe2016-01-28 05:22:45 -08001082int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001083 if (cached_send_codec_) {
1084 codec = *cached_send_codec_;
1085 return 0;
1086 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001087 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1088 if (send_codec) {
1089 codec = *send_codec;
1090 return 0;
1091 }
1092 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001093 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001094}
1095
kwiberg55b97fe2016-01-28 05:22:45 -08001096int32_t Channel::GetRecCodec(CodecInst& codec) {
1097 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001098}
1099
kwiberg55b97fe2016-01-28 05:22:45 -08001100int32_t Channel::SetSendCodec(const CodecInst& codec) {
1101 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1102 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001103
kwibergc8d071e2016-04-06 12:22:38 -07001104 if (!codec_manager_.RegisterEncoder(codec) ||
1105 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001106 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1107 "SetSendCodec() failed to register codec to ACM");
1108 return -1;
1109 }
1110
1111 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1112 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1113 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1114 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1115 "SetSendCodec() failed to register codec to"
1116 " RTP/RTCP module");
1117 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001118 }
kwiberg55b97fe2016-01-28 05:22:45 -08001119 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001120
ossu76d29f92017-06-09 07:30:13 -07001121 cached_send_codec_.reset();
1122
kwiberg55b97fe2016-01-28 05:22:45 -08001123 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001124}
1125
minyue78b4d562016-11-30 04:47:39 -08001126void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001127 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1128 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001129 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001130 if (*encoder) {
1131 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001132 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001133 }
1134 });
michaelt566d8202017-01-12 10:17:38 -08001135 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001136}
1137
elad.alond12a8e12017-03-23 11:04:48 -07001138void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1139 if (!use_twcc_plr_for_ana_)
1140 return;
minyue7e304322016-10-12 05:00:55 -07001141 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001142 if (*encoder) {
1143 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1144 }
1145 });
1146}
1147
elad.alondadb4dc2017-03-23 15:29:50 -07001148void Channel::OnRecoverableUplinkPacketLossRate(
1149 float recoverable_packet_loss_rate) {
1150 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1151 if (*encoder) {
1152 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1153 recoverable_packet_loss_rate);
1154 }
1155 });
1156}
1157
elad.alond12a8e12017-03-23 11:04:48 -07001158void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1159 if (use_twcc_plr_for_ana_)
1160 return;
1161 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1162 if (*encoder) {
1163 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1164 }
minyue7e304322016-10-12 05:00:55 -07001165 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001166}
1167
kwiberg1c07c702017-03-27 07:15:49 -07001168void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1169 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1170 audio_coding_->SetReceiveCodecs(codecs);
1171}
1172
minyue7e304322016-10-12 05:00:55 -07001173bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1174 bool success = false;
1175 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1176 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001177 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1178 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001179 }
1180 });
1181 return success;
1182}
1183
1184void Channel::DisableAudioNetworkAdaptor() {
1185 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1186 if (*encoder)
1187 (*encoder)->DisableAudioNetworkAdaptor();
1188 });
1189}
1190
1191void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1192 int max_frame_length_ms) {
1193 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1194 if (*encoder) {
1195 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1196 max_frame_length_ms);
1197 }
1198 });
1199}
1200
mflodman3d7db262016-04-29 00:57:13 -07001201int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001202 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001203 "Channel::RegisterExternalTransport()");
1204
kwiberg55b97fe2016-01-28 05:22:45 -08001205 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001206 if (_externalTransport) {
1207 _engineStatisticsPtr->SetLastError(
1208 VE_INVALID_OPERATION, kTraceError,
1209 "RegisterExternalTransport() external transport already enabled");
1210 return -1;
1211 }
1212 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001213 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001214 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001215}
1216
kwiberg55b97fe2016-01-28 05:22:45 -08001217int32_t Channel::DeRegisterExternalTransport() {
1218 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1219 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001220
kwiberg55b97fe2016-01-28 05:22:45 -08001221 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001222 if (_transportPtr) {
1223 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1224 "DeRegisterExternalTransport() all transport is disabled");
1225 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001226 _engineStatisticsPtr->SetLastError(
1227 VE_INVALID_OPERATION, kTraceWarning,
1228 "DeRegisterExternalTransport() external transport already "
1229 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001230 }
1231 _externalTransport = false;
1232 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001233 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001234}
1235
nisse657bab22017-02-21 06:28:10 -08001236void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1237 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg946d8862017-09-21 04:02:53 -07001238 "Channel::OnRtpPacket()");
nisse657bab22017-02-21 06:28:10 -08001239
1240 RTPHeader header;
1241 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -07001242
1243 // Store playout timestamp for the received RTP packet
1244 UpdatePlayoutTimestamp(false);
1245
1246 header.payload_type_frequency =
1247 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1248 if (header.payload_type_frequency >= 0) {
1249 bool in_order = IsPacketInOrder(header);
1250 rtp_receive_statistics_->IncomingPacket(
1251 header, packet.size(), IsPacketRetransmitted(header, in_order));
1252 rtp_payload_registry_->SetIncomingPayloadType(header);
1253
1254 ReceivePacket(packet.data(), packet.size(), header, in_order);
1255 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001256}
1257
1258bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001259 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001260 const RTPHeader& header,
1261 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001262 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001263 assert(packet_length >= header.headerLength);
1264 size_t payload_length = packet_length - header.headerLength;
Karl Wiberg73b60b82017-09-21 15:00:58 +02001265 const auto pl =
1266 rtp_payload_registry_->PayloadTypeToPayload(header.payloadType);
1267 if (!pl) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001268 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001269 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001270 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
Karl Wiberg73b60b82017-09-21 15:00:58 +02001271 pl->typeSpecific, in_order);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001272}
1273
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001274bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1275 StreamStatistician* statistician =
1276 rtp_receive_statistics_->GetStatistician(header.ssrc);
1277 if (!statistician)
1278 return false;
1279 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001280}
1281
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001282bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1283 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001284 StreamStatistician* statistician =
1285 rtp_receive_statistics_->GetStatistician(header.ssrc);
1286 if (!statistician)
1287 return false;
1288 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001289 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001290 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001291 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001292}
1293
mflodman3d7db262016-04-29 00:57:13 -07001294int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001295 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001296 "Channel::ReceivedRTCPPacket()");
1297 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001298 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001299
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001300 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001301 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001302
Minyue2013aec2015-05-13 14:14:42 +02001303 int64_t rtt = GetRTT(true);
1304 if (rtt == 0) {
1305 // Waiting for valid RTT.
1306 return 0;
1307 }
Erik Språng737336d2016-07-29 12:59:36 +02001308
1309 int64_t nack_window_ms = rtt;
1310 if (nack_window_ms < kMinRetransmissionWindowMs) {
1311 nack_window_ms = kMinRetransmissionWindowMs;
1312 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1313 nack_window_ms = kMaxRetransmissionWindowMs;
1314 }
1315 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1316
minyue7e304322016-10-12 05:00:55 -07001317 // Invoke audio encoders OnReceivedRtt().
1318 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1319 if (*encoder)
1320 (*encoder)->OnReceivedRtt(rtt);
1321 });
1322
Minyue2013aec2015-05-13 14:14:42 +02001323 uint32_t ntp_secs = 0;
1324 uint32_t ntp_frac = 0;
1325 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001326 if (0 !=
1327 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1328 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001329 // Waiting for RTCP.
1330 return 0;
1331 }
1332
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001333 {
tommi31fc21f2016-01-21 10:37:37 -08001334 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001335 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001336 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001337 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001338}
1339
solenberg8d73f8c2017-03-08 01:52:20 -08001340int Channel::GetSpeechOutputLevel() const {
1341 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001342}
1343
solenberg8d73f8c2017-03-08 01:52:20 -08001344int Channel::GetSpeechOutputLevelFullRange() const {
1345 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001346}
1347
zsteine76bd3a2017-07-14 12:17:49 -07001348double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001349 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001350}
1351
1352double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001353 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001354}
1355
solenberg8d73f8c2017-03-08 01:52:20 -08001356void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001357 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001358 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001359}
1360
solenberg1c2af8e2016-03-24 10:36:00 -07001361bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001362 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001363 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001364}
1365
solenberg8d73f8c2017-03-08 01:52:20 -08001366void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001367 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001368 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001369}
1370
solenberg8842c3e2016-03-11 03:06:41 -08001371int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001372 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001373 "Channel::SendTelephoneEventOutband(...)");
1374 RTC_DCHECK_LE(0, event);
1375 RTC_DCHECK_GE(255, event);
1376 RTC_DCHECK_LE(0, duration_ms);
1377 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001378 if (!Sending()) {
1379 return -1;
1380 }
solenberg8842c3e2016-03-11 03:06:41 -08001381 if (_rtpRtcpModule->SendTelephoneEventOutband(
1382 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001383 _engineStatisticsPtr->SetLastError(
1384 VE_SEND_DTMF_FAILED, kTraceWarning,
1385 "SendTelephoneEventOutband() failed to send event");
1386 return -1;
1387 }
1388 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001389}
1390
solenbergffbbcac2016-11-17 05:25:37 -08001391int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1392 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001393 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001394 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001395 RTC_DCHECK_LE(0, payload_type);
1396 RTC_DCHECK_GE(127, payload_type);
1397 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001398 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001399 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001400 memcpy(codec.plname, "telephone-event", 16);
1401 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1402 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1403 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1404 _engineStatisticsPtr->SetLastError(
1405 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1406 "SetSendTelephoneEventPayloadType() failed to register send"
1407 "payload type");
1408 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001409 }
kwiberg55b97fe2016-01-28 05:22:45 -08001410 }
kwiberg55b97fe2016-01-28 05:22:45 -08001411 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001412}
1413
kwiberg55b97fe2016-01-28 05:22:45 -08001414int Channel::SetLocalSSRC(unsigned int ssrc) {
1415 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1416 "Channel::SetLocalSSRC()");
1417 if (channel_state_.Get().sending) {
1418 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
1419 "SetLocalSSRC() already sending");
1420 return -1;
1421 }
1422 _rtpRtcpModule->SetSSRC(ssrc);
1423 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001424}
1425
kwiberg55b97fe2016-01-28 05:22:45 -08001426int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1427 ssrc = rtp_receiver_->SSRC();
1428 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001429}
1430
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001431int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001432 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001433 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001434}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001435
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001436int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1437 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001438 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1439 if (enable &&
1440 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1441 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001442 return -1;
1443 }
1444 return 0;
1445}
1446
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001447void Channel::EnableSendTransportSequenceNumber(int id) {
1448 int ret =
1449 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1450 RTC_DCHECK_EQ(0, ret);
1451}
1452
stefan3313ec92016-01-21 06:32:43 -08001453void Channel::EnableReceiveTransportSequenceNumber(int id) {
1454 rtp_header_parser_->DeregisterRtpHeaderExtension(
1455 kRtpExtensionTransportSequenceNumber);
1456 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1457 kRtpExtensionTransportSequenceNumber, id);
1458 RTC_DCHECK(ret);
1459}
1460
stefanbba9dec2016-02-01 04:39:55 -08001461void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001462 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001463 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001464 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1465 TransportFeedbackObserver* transport_feedback_observer =
1466 transport->transport_feedback_observer();
1467 PacketRouter* packet_router = transport->packet_router();
1468
stefanbba9dec2016-02-01 04:39:55 -08001469 RTC_DCHECK(rtp_packet_sender);
1470 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001471 RTC_DCHECK(packet_router);
1472 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001473 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001474 feedback_observer_proxy_->SetTransportFeedbackObserver(
1475 transport_feedback_observer);
1476 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1477 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1478 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001479 constexpr bool remb_candidate = false;
1480 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001481 packet_router_ = packet_router;
1482}
1483
stefanbba9dec2016-02-01 04:39:55 -08001484void Channel::RegisterReceiverCongestionControlObjects(
1485 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001486 RTC_DCHECK(packet_router);
1487 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001488 constexpr bool remb_candidate = false;
1489 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001490 packet_router_ = packet_router;
1491}
1492
nissefdbfdc92017-03-31 05:44:52 -07001493void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001494 RTC_DCHECK(packet_router_);
1495 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001496 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001497 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1498 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001499 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001500 packet_router_ = nullptr;
1501 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1502}
1503
nissefdbfdc92017-03-31 05:44:52 -07001504void Channel::ResetReceiverCongestionControlObjects() {
1505 RTC_DCHECK(packet_router_);
1506 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1507 packet_router_ = nullptr;
1508}
1509
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001510void Channel::SetRTCPStatus(bool enable) {
1511 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1512 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001513 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001514}
1515
kwiberg55b97fe2016-01-28 05:22:45 -08001516int Channel::SetRTCP_CNAME(const char cName[256]) {
1517 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1518 "Channel::SetRTCP_CNAME()");
1519 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
1520 _engineStatisticsPtr->SetLastError(
1521 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1522 "SetRTCP_CNAME() failed to set RTCP CNAME");
1523 return -1;
1524 }
1525 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001526}
1527
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001528int Channel::GetRemoteRTCPReportBlocks(
1529 std::vector<ReportBlock>* report_blocks) {
1530 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08001531 _engineStatisticsPtr->SetLastError(
1532 VE_INVALID_ARGUMENT, kTraceError,
1533 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001534 return -1;
1535 }
1536
1537 // Get the report blocks from the latest received RTCP Sender or Receiver
1538 // Report. Each element in the vector contains the sender's SSRC and a
1539 // report block according to RFC 3550.
1540 std::vector<RTCPReportBlock> rtcp_report_blocks;
1541 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001542 return -1;
1543 }
1544
1545 if (rtcp_report_blocks.empty())
1546 return 0;
1547
1548 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1549 for (; it != rtcp_report_blocks.end(); ++it) {
1550 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001551 report_block.sender_SSRC = it->sender_ssrc;
1552 report_block.source_SSRC = it->source_ssrc;
1553 report_block.fraction_lost = it->fraction_lost;
1554 report_block.cumulative_num_packets_lost = it->packets_lost;
1555 report_block.extended_highest_sequence_number =
1556 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001557 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001558 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1559 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001560 report_blocks->push_back(report_block);
1561 }
1562 return 0;
1563}
1564
kwiberg55b97fe2016-01-28 05:22:45 -08001565int Channel::GetRTPStatistics(CallStatistics& stats) {
1566 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001567
kwiberg55b97fe2016-01-28 05:22:45 -08001568 // The jitter statistics is updated for each received RTP packet and is
1569 // based on received packets.
1570 RtcpStatistics statistics;
1571 StreamStatistician* statistician =
1572 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001573 if (statistician) {
1574 statistician->GetStatistics(&statistics,
1575 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001576 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001577
kwiberg55b97fe2016-01-28 05:22:45 -08001578 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001579 stats.cumulativeLost = statistics.packets_lost;
1580 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001581 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001582
kwiberg55b97fe2016-01-28 05:22:45 -08001583 // --- RTT
1584 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001585
kwiberg55b97fe2016-01-28 05:22:45 -08001586 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001587
kwiberg55b97fe2016-01-28 05:22:45 -08001588 size_t bytesSent(0);
1589 uint32_t packetsSent(0);
1590 size_t bytesReceived(0);
1591 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001592
kwiberg55b97fe2016-01-28 05:22:45 -08001593 if (statistician) {
1594 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1595 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001596
kwiberg55b97fe2016-01-28 05:22:45 -08001597 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
1598 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1599 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
1600 " output will not be complete");
1601 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001602
kwiberg55b97fe2016-01-28 05:22:45 -08001603 stats.bytesSent = bytesSent;
1604 stats.packetsSent = packetsSent;
1605 stats.bytesReceived = bytesReceived;
1606 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001607
kwiberg55b97fe2016-01-28 05:22:45 -08001608 // --- Timestamps
1609 {
1610 rtc::CritScope lock(&ts_stats_lock_);
1611 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1612 }
1613 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001614}
1615
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001616void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1617 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001618 // If pacing is enabled we always store packets.
1619 if (!pacing_enabled_)
1620 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001621 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001622 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001623 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001624 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001625 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001626}
1627
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001628// Called when we are missing one or more packets.
1629int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001630 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1631}
1632
henrikaec6fbd22017-03-31 05:43:36 -07001633void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001634 // Avoid posting any new tasks if sending was already stopped in StopSend().
1635 rtc::CritScope cs(&encoder_queue_lock_);
1636 if (!encoder_queue_is_active_) {
1637 return;
1638 }
henrikaec6fbd22017-03-31 05:43:36 -07001639 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1640 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1641 // either into pool of frames or into the task itself.
1642 audio_frame->CopyFrom(audio_input);
henrika45802172017-09-28 09:39:34 +02001643 // Profile time between when the audio frame is added to the task queue and
1644 // when the task is actually executed.
1645 audio_frame->UpdateProfileTimeStamp();
henrikaec6fbd22017-03-31 05:43:36 -07001646 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1647 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001648}
1649
henrikaec6fbd22017-03-31 05:43:36 -07001650void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1651 int sample_rate,
1652 size_t number_of_frames,
1653 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001654 // Avoid posting as new task if sending was already stopped in StopSend().
1655 rtc::CritScope cs(&encoder_queue_lock_);
1656 if (!encoder_queue_is_active_) {
1657 return;
1658 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001659 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001660 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001661 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
ossu950c1c92017-07-11 08:19:31 -07001662 // TODO(ossu): Investigate how this could happen. b/62909493
1663 if (result == 0) {
1664 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1665 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1666 } else {
1667 audio_frame->sample_rate_hz_ = sample_rate;
1668 audio_frame->num_channels_ = number_of_channels;
1669 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1670 RTC_NOTREACHED();
1671 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001672 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001673 sample_rate, &input_resampler_, audio_frame.get());
1674 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1675 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001676}
1677
henrikaec6fbd22017-03-31 05:43:36 -07001678void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1679 RTC_DCHECK_RUN_ON(encoder_queue_);
1680 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1681 RTC_DCHECK_LE(audio_input->num_channels_, 2);
kwiberg55b97fe2016-01-28 05:22:45 -08001682
henrika45802172017-09-28 09:39:34 +02001683 // Measure time between when the audio frame is added to the task queue and
1684 // when the task is actually executed. Goal is to keep track of unwanted
1685 // extra latency added by the task queue.
1686 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
1687 audio_input->ElapsedProfileTimeMs());
1688
henrikaec6fbd22017-03-31 05:43:36 -07001689 bool is_muted = InputMute();
1690 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001691
kwiberg55b97fe2016-01-28 05:22:45 -08001692 if (_includeAudioLevelIndication) {
1693 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001694 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001695 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001696 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001697 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001698 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001699 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001700 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001701 }
kwiberg55b97fe2016-01-28 05:22:45 -08001702 }
solenberg1c2af8e2016-03-24 10:36:00 -07001703 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001704
henrikaec6fbd22017-03-31 05:43:36 -07001705 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001706
kwiberg55b97fe2016-01-28 05:22:45 -08001707 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001708 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001709 // This call will trigger AudioPacketizationCallback::SendData if encoding
1710 // is done and payload is ready for packetization and transmission.
1711 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001712 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1713 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1714 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001715 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001716
henrikaec6fbd22017-03-31 05:43:36 -07001717 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001718}
1719
solenberg7602aab2016-11-14 11:30:07 -08001720void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1721 RTC_DCHECK(!channel.channel() ||
1722 channel.channel()->ChannelId() != _channelId);
1723 rtc::CritScope lock(&assoc_send_channel_lock_);
1724 associate_send_channel_ = channel;
1725}
1726
Minyue2013aec2015-05-13 14:14:42 +02001727void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001728 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001729 Channel* channel = associate_send_channel_.channel();
1730 if (channel && channel->ChannelId() == channel_id) {
1731 // If this channel is associated with a send channel of the specified
1732 // Channel ID, disassociate with it.
1733 ChannelOwner ref(NULL);
1734 associate_send_channel_ = ref;
1735 }
1736}
1737
ivoc14d5dbe2016-07-04 07:06:55 -07001738void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1739 event_log_proxy_->SetEventLog(event_log);
1740}
1741
michaelt9332b7d2016-11-30 07:51:13 -08001742void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1743 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1744}
1745
nisse284542b2017-01-10 08:58:32 -08001746void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001747 size_t overhead_per_packet =
1748 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001749 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1750 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001751 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001752 }
1753 });
1754}
1755
1756void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001757 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001758 transport_overhead_per_packet_ = transport_overhead_per_packet;
1759 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001760}
1761
hbos3fd31fe2017-02-28 05:43:16 -08001762// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001763void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001764 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001765 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1766 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001767}
1768
kwiberg55b97fe2016-01-28 05:22:45 -08001769int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1770 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001771}
1772
wu@webrtc.org24301a62013-12-13 19:17:43 +00001773void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1774 audio_coding_->GetDecodingCallStatistics(stats);
1775}
1776
ivoce1198e02017-09-08 08:13:19 -07001777ANAStats Channel::GetANAStatistics() const {
1778 return audio_coding_->GetANAStats();
1779}
1780
solenberg358057b2015-11-27 10:46:42 -08001781uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001782 rtc::CritScope lock(&video_sync_lock_);
1783 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001784}
1785
kwiberg55b97fe2016-01-28 05:22:45 -08001786int Channel::SetMinimumPlayoutDelay(int delayMs) {
1787 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1788 "Channel::SetMinimumPlayoutDelay()");
1789 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1790 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
1791 _engineStatisticsPtr->SetLastError(
1792 VE_INVALID_ARGUMENT, kTraceError,
1793 "SetMinimumPlayoutDelay() invalid min delay");
1794 return -1;
1795 }
1796 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
1797 _engineStatisticsPtr->SetLastError(
1798 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1799 "SetMinimumPlayoutDelay() failed to set min playout delay");
1800 return -1;
1801 }
1802 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001803}
1804
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001805int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001806 uint32_t playout_timestamp_rtp = 0;
1807 {
tommi31fc21f2016-01-21 10:37:37 -08001808 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001809 playout_timestamp_rtp = playout_timestamp_rtp_;
1810 }
kwiberg55b97fe2016-01-28 05:22:45 -08001811 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001812 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07001813 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001814 "GetPlayoutTimestamp() failed to retrieve timestamp");
1815 return -1;
1816 }
deadbeef74375882015-08-13 12:09:10 -07001817 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001818 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001819}
1820
kwiberg55b97fe2016-01-28 05:22:45 -08001821int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1822 RtpReceiver** rtp_receiver) const {
1823 *rtpRtcpModule = _rtpRtcpModule.get();
1824 *rtp_receiver = rtp_receiver_.get();
1825 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001826}
1827
deadbeef74375882015-08-13 12:09:10 -07001828void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001829 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001830
henrik.lundin96bd5022016-04-06 04:13:56 -07001831 if (!jitter_buffer_playout_timestamp_) {
1832 // This can happen if this channel has not received any RTP packets. In
1833 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001834 return;
1835 }
1836
1837 uint16_t delay_ms = 0;
1838 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001839 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001840 "Channel::UpdatePlayoutTimestamp() failed to read playout"
1841 " delay from the ADM");
1842 _engineStatisticsPtr->SetLastError(
1843 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
1844 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
1845 return;
1846 }
1847
henrik.lundin96bd5022016-04-06 04:13:56 -07001848 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1849 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001850
1851 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001852 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001853
kwiberg55b97fe2016-01-28 05:22:45 -08001854 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001855 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07001856 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07001857
1858 {
tommi31fc21f2016-01-21 10:37:37 -08001859 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001860 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001861 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001862 }
1863 playout_delay_ms_ = delay_ms;
1864 }
1865}
1866
kwiberg55b97fe2016-01-28 05:22:45 -08001867void Channel::RegisterReceiveCodecsToRTPModule() {
1868 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1869 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001870
kwiberg55b97fe2016-01-28 05:22:45 -08001871 CodecInst codec;
1872 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00001873
kwiberg55b97fe2016-01-28 05:22:45 -08001874 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1875 // Open up the RTP/RTCP receiver for all supported codecs
1876 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001877 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001878 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1879 "Channel::RegisterReceiveCodecsToRTPModule() unable"
1880 " to register %s (%d/%d/%" PRIuS
1881 "/%d) to RTP/RTCP "
1882 "receiver",
1883 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1884 codec.rate);
1885 } else {
1886 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1887 "Channel::RegisterReceiveCodecsToRTPModule() %s "
1888 "(%d/%d/%" PRIuS
1889 "/%d) has been added to the RTP/RTCP "
1890 "receiver",
1891 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1892 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001893 }
kwiberg55b97fe2016-01-28 05:22:45 -08001894 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001895}
1896
kwiberg55b97fe2016-01-28 05:22:45 -08001897int Channel::SetSendRtpHeaderExtension(bool enable,
1898 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001899 unsigned char id) {
1900 int error = 0;
1901 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
1902 if (enable) {
1903 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
1904 }
1905 return error;
1906}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001907
ossue280cde2016-10-12 11:04:10 -07001908int Channel::GetRtpTimestampRateHz() const {
1909 const auto format = audio_coding_->ReceiveFormat();
1910 // Default to the playout frequency if we've not gotten any packets yet.
1911 // TODO(ossu): Zero clockrate can only happen if we've added an external
1912 // decoder for a format we don't support internally. Remove once that way of
1913 // adding decoders is gone!
1914 return (format && format->clockrate_hz != 0)
1915 ? format->clockrate_hz
1916 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00001917}
1918
Minyue2013aec2015-05-13 14:14:42 +02001919int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07001920 RtcpMode method = _rtpRtcpModule->RTCP();
1921 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001922 return 0;
1923 }
1924 std::vector<RTCPReportBlock> report_blocks;
1925 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02001926
1927 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001928 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02001929 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08001930 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001931 Channel* channel = associate_send_channel_.channel();
1932 // Tries to get RTT from an associated channel. This is important for
1933 // receive-only channels.
1934 if (channel) {
1935 // To prevent infinite recursion and deadlock, calling GetRTT of
1936 // associate channel should always use "false" for argument:
1937 // |allow_associate_channel|.
1938 rtt = channel->GetRTT(false);
1939 }
1940 }
1941 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001942 }
1943
1944 uint32_t remoteSSRC = rtp_receiver_->SSRC();
1945 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
1946 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07001947 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001948 break;
1949 }
1950 if (it == report_blocks.end()) {
1951 // We have not received packets with SSRC matching the report blocks.
1952 // To calculate RTT we try with the SSRC of the first report block.
1953 // This is very important for send-only channels where we don't know
1954 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07001955 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001956 }
Minyue2013aec2015-05-13 14:14:42 +02001957
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001958 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001959 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001960 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001961 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
1962 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001963 return 0;
1964 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001965 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00001966}
1967
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00001968} // namespace voe
1969} // namespace webrtc