blob: e95a468d4dc785372faf8ca3f0e10f9dc094e994 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
henrika@webrtc.org2919e952012-01-31 08:45:03 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "voice_engine/channel.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Henrik Lundin64dad832015-05-11 12:44:23 +020013#include <algorithm>
Tommif888bb52015-12-12 01:37:01 +010014#include <utility>
Henrik Lundin64dad832015-05-11 12:44:23 +020015
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "api/array_view.h"
17#include "audio/utility/audio_frame_operations.h"
18#include "call/rtp_transport_controller_send_interface.h"
19#include "logging/rtc_event_log/rtc_event_log.h"
20#include "modules/audio_coding/codecs/audio_format_conversion.h"
21#include "modules/audio_device/include/audio_device.h"
22#include "modules/audio_processing/include/audio_processing.h"
23#include "modules/include/module_common_types.h"
24#include "modules/pacing/packet_router.h"
25#include "modules/rtp_rtcp/include/receive_statistics.h"
26#include "modules/rtp_rtcp/include/rtp_payload_registry.h"
27#include "modules/rtp_rtcp/include/rtp_receiver.h"
28#include "modules/rtp_rtcp/source/rtp_packet_received.h"
29#include "modules/rtp_rtcp/source/rtp_receiver_strategy.h"
30#include "modules/utility/include/process_thread.h"
31#include "rtc_base/checks.h"
32#include "rtc_base/criticalsection.h"
33#include "rtc_base/format_macros.h"
34#include "rtc_base/location.h"
35#include "rtc_base/logging.h"
36#include "rtc_base/rate_limiter.h"
37#include "rtc_base/task_queue.h"
38#include "rtc_base/thread_checker.h"
39#include "rtc_base/timeutils.h"
40#include "system_wrappers/include/field_trial.h"
41#include "system_wrappers/include/trace.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "voice_engine/output_mixer.h"
43#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
henrik.lundin42dda502016-05-18 05:36:01 -0700622MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
623 int32_t id,
624 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700625 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800626 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700627 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800628 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700629 bool muted;
630 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
631 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800632 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
633 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
634 // In all likelihood, the audio in this frame is garbage. We return an
635 // error so that the audio mixer module doesn't add it to the mix. As
636 // a result, it won't be played out and the actions skipped here are
637 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700638 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800639 }
henrik.lundina89ab962016-05-18 08:52:45 -0700640
641 if (muted) {
642 // TODO(henrik.lundin): We should be able to do better than this. But we
643 // will have to go through all the cases below where the audio samples may
644 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800645 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700646 }
kwiberg55b97fe2016-01-28 05:22:45 -0800647
kwiberg55b97fe2016-01-28 05:22:45 -0800648 // Convert module ID to internal VoE channel ID
649 audioFrame->id_ = VoEChannelId(audioFrame->id_);
650 // Store speech type for dead-or-alive detection
651 _outputSpeechType = audioFrame->speech_type_;
652
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(
yujo36b1a5f2017-06-12 12:45:32 -0700661 audioFrame->data(), audioFrame->samples_per_channel_,
kwiberg55b97fe2016-01-28 05:22:45 -0800662 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
663 audioFrame->timestamp_);
664 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!
oprypin67fdb802017-03-09 06:25:06 -0800677 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
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).
zstein3c451862017-07-20 09:57:42 -0700684 _outputAudioLevel.ComputeLevel(*audioFrame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800685
686 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
687 // The first frame with a valid rtp timestamp.
688 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
689 }
690
691 if (capture_start_rtp_time_stamp_ >= 0) {
692 // audioFrame.timestamp_ should be valid from now on.
693
694 // Compute elapsed time.
695 int64_t unwrap_timestamp =
696 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
697 audioFrame->elapsed_time_ms_ =
698 (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.
704 audioFrame->ntp_time_ms_ =
705 ntp_estimator_.Estimate(audioFrame->timestamp_);
706 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
707 if (audioFrame->ntp_time_ms_ > 0) {
708 // 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_ =
711 audioFrame->ntp_time_ms_ - audioFrame->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
henrik.lundin42dda502016-05-18 05:36:01 -0700716 return muted ? MixerParticipant::AudioFrameInfo::kMuted
717 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000718}
719
aleloi6c278492016-10-20 14:24:39 -0700720AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
721 int sample_rate_hz,
722 AudioFrame* audio_frame) {
723 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700724
aleloi6c278492016-10-20 14:24:39 -0700725 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700726
727 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
728 FrameInfo new_audio_frame_info = FrameInfo::kError;
729 switch (frame_info) {
730 case MixerParticipant::AudioFrameInfo::kNormal:
731 new_audio_frame_info = FrameInfo::kNormal;
732 break;
733 case MixerParticipant::AudioFrameInfo::kMuted:
734 new_audio_frame_info = FrameInfo::kMuted;
735 break;
736 case MixerParticipant::AudioFrameInfo::kError:
737 new_audio_frame_info = FrameInfo::kError;
738 break;
739 }
aleloi6c278492016-10-20 14:24:39 -0700740 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700741}
742
kwiberg55b97fe2016-01-28 05:22:45 -0800743int32_t Channel::NeededFrequency(int32_t id) const {
744 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
745 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000746
kwiberg55b97fe2016-01-28 05:22:45 -0800747 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000748
kwiberg55b97fe2016-01-28 05:22:45 -0800749 // Determine highest needed receive frequency
750 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000751
kwiberg55b97fe2016-01-28 05:22:45 -0800752 // Return the bigger of playout and receive frequency in the ACM.
753 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
754 highestNeeded = audio_coding_->PlayoutFrequency();
755 } else {
756 highestNeeded = receiveFrequency;
757 }
758
solenbergb63310a2017-09-18 03:04:12 -0700759 return highestNeeded;
niklase@google.com470e71d2011-07-07 08:21:25 +0000760}
761
henrikaec6fbd22017-03-31 05:43:36 -0700762int32_t Channel::CreateChannel(Channel*& channel,
763 int32_t channelId,
764 uint32_t instanceId,
765 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800766 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
767 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
768 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000769
solenberg88499ec2016-09-07 07:34:41 -0700770 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800771 if (channel == NULL) {
772 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
773 "Channel::CreateChannel() unable to allocate memory for"
774 " channel");
775 return -1;
776 }
777 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000778}
779
pbos@webrtc.org92135212013-05-14 08:31:39 +0000780Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000781 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700782 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800783 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100784 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700785 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800786 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100787 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800788 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100789 rtp_receive_statistics_(
790 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
791 rtp_receiver_(
792 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100793 this,
794 this,
795 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700796 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100797 _outputAudioLevel(),
798 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100799 _timeStamp(0), // This is just an offset, RTP module will add it's own
800 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100801 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100802 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100803 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100804 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100805 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
806 capture_start_rtp_time_stamp_(-1),
807 capture_start_ntp_time_ms_(-1),
808 _engineStatisticsPtr(NULL),
809 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100810 _moduleProcessThreadPtr(NULL),
811 _audioDeviceModulePtr(NULL),
812 _voiceEngineObserverPtr(NULL),
813 _callbackCritSectPtr(NULL),
814 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700815 input_mute_(false),
816 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100817 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100818 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800819 transport_overhead_per_packet_(0),
820 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100821 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100822 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100823 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700824 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800825 feedback_observer_proxy_(new TransportFeedbackProxy()),
826 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700827 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200828 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
829 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700830 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700831 use_twcc_plr_for_ana_(
832 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800833 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
834 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700835 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800836 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700837 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800838 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200839
kwiberg55b97fe2016-01-28 05:22:45 -0800840 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000841
kwiberg55b97fe2016-01-28 05:22:45 -0800842 RtpRtcp::Configuration configuration;
843 configuration.audio = true;
844 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800845 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800846 configuration.receive_statistics = rtp_receive_statistics_.get();
847 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800848 if (pacing_enabled_) {
849 configuration.paced_sender = rtp_packet_sender_proxy_.get();
850 configuration.transport_sequence_number_allocator =
851 seq_num_allocator_proxy_.get();
852 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
853 }
ivoc14d5dbe2016-07-04 07:06:55 -0700854 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800855 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200856 configuration.retransmission_rate_limiter =
857 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000858
kwiberg55b97fe2016-01-28 05:22:45 -0800859 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100860 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000861}
862
kwiberg55b97fe2016-01-28 05:22:45 -0800863Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700864 RTC_DCHECK(!channel_state_.Get().sending);
865 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000866}
867
kwiberg55b97fe2016-01-28 05:22:45 -0800868int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700869 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800870 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
871 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000872
kwiberg55b97fe2016-01-28 05:22:45 -0800873 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000874
kwiberg55b97fe2016-01-28 05:22:45 -0800875 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000876
kwiberg55b97fe2016-01-28 05:22:45 -0800877 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
878 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
879 "Channel::Init() must call SetEngineInformation() first");
880 return -1;
881 }
882
883 // --- Add modules to process thread (for periodic schedulation)
884
tommidea489f2017-03-03 03:20:24 -0800885 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800886
887 // --- ACM initialization
888
889 if (audio_coding_->InitializeReceiver() == -1) {
890 _engineStatisticsPtr->SetLastError(
891 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
892 "Channel::Init() unable to initialize the ACM - 1");
893 return -1;
894 }
895
896 // --- RTP/RTCP module initialization
897
898 // Ensure that RTCP is enabled by default for the created channel.
899 // Note that, the module will keep generating RTCP until it is explicitly
900 // disabled by the user.
901 // After StopListen (when no sockets exists), RTCP packets will no longer
902 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700903 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800904 // RTCP is enabled by default.
905 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
906 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800907 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800908 _engineStatisticsPtr->SetLastError(
909 VE_CANNOT_INIT_CHANNEL, kTraceError,
910 "Channel::Init() callbacks not registered");
911 return -1;
912 }
913
solenberg6dc20382017-09-18 05:22:39 -0700914 // TODO(solenberg): Remove?
kwiberg1c07c702017-03-27 07:15:49 -0700915 // Register a default set of send codecs.
916 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -0800917 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -0700918 CodecInst codec;
919 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
920
921 // Ensure that PCMU is used as default send codec.
922 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
923 SetSendCodec(codec);
924 }
925
926 // Register default PT for 'telephone-event'
927 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
928 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
929 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
930 "Channel::Init() failed to register outband "
931 "'telephone-event' (%d/%d) correctly",
932 codec.pltype, codec.plfreq);
933 }
934 }
935
936 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
937 if (!codec_manager_.RegisterEncoder(codec) ||
938 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
939 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
940 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
941 "Channel::Init() failed to register CN (%d/%d) "
942 "correctly - 1",
943 codec.pltype, codec.plfreq);
944 }
945 }
946 }
947
948 return 0;
949}
950
tommi0a2391f2017-03-21 02:31:51 -0700951void Channel::Terminate() {
952 RTC_DCHECK(construction_thread_.CalledOnValidThread());
953 // Must be called on the same thread as Init().
954 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
955 "Channel::Terminate");
956
957 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
958
959 StopSend();
960 StopPlayout();
961
tommi0a2391f2017-03-21 02:31:51 -0700962 // The order to safely shutdown modules in a channel is:
963 // 1. De-register callbacks in modules
964 // 2. De-register modules in process thread
965 // 3. Destroy modules
966 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
967 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
968 "Terminate() failed to de-register transport callback"
969 " (Audio coding module)");
970 }
971
972 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
973 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
974 "Terminate() failed to de-register VAD callback"
975 " (Audio coding module)");
976 }
977
978 // De-register modules in process thread
979 if (_moduleProcessThreadPtr)
980 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
981
982 // End of modules shutdown
983}
984
kwiberg55b97fe2016-01-28 05:22:45 -0800985int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
986 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -0800987 ProcessThread& moduleProcessThread,
988 AudioDeviceModule& audioDeviceModule,
989 VoiceEngineObserver* voiceEngineObserver,
henrikaec6fbd22017-03-31 05:43:36 -0700990 rtc::CriticalSection* callbackCritSect,
991 rtc::TaskQueue* encoder_queue) {
992 RTC_DCHECK(encoder_queue);
993 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800994 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
995 "Channel::SetEngineInformation()");
996 _engineStatisticsPtr = &engineStatistics;
997 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -0800998 _moduleProcessThreadPtr = &moduleProcessThread;
999 _audioDeviceModulePtr = &audioDeviceModule;
1000 _voiceEngineObserverPtr = voiceEngineObserver;
1001 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -07001002 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -08001003 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001004}
1005
kwibergb7f89d62016-02-17 10:04:18 -08001006void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001007 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001008 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001009}
1010
ossu29b1a8d2016-06-13 07:34:51 -07001011const rtc::scoped_refptr<AudioDecoderFactory>&
1012Channel::GetAudioDecoderFactory() const {
1013 return decoder_factory_;
1014}
1015
kwiberg55b97fe2016-01-28 05:22:45 -08001016int32_t Channel::StartPlayout() {
1017 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1018 "Channel::StartPlayout()");
1019 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001020 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001021 }
1022
solenberge374e012017-02-14 04:55:00 -08001023 // Add participant as candidates for mixing.
1024 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1025 _engineStatisticsPtr->SetLastError(
1026 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1027 "StartPlayout() failed to add participant to mixer");
1028 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001029 }
1030
1031 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001032
1033 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001034}
1035
kwiberg55b97fe2016-01-28 05:22:45 -08001036int32_t Channel::StopPlayout() {
1037 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1038 "Channel::StopPlayout()");
1039 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001040 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001041 }
1042
solenberge374e012017-02-14 04:55:00 -08001043 // Remove participant as candidates for mixing
1044 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1045 _engineStatisticsPtr->SetLastError(
1046 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1047 "StopPlayout() failed to remove participant from mixer");
1048 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001049 }
1050
1051 channel_state_.SetPlaying(false);
1052 _outputAudioLevel.Clear();
1053
1054 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001055}
1056
kwiberg55b97fe2016-01-28 05:22:45 -08001057int32_t Channel::StartSend() {
1058 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1059 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001060 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001061 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001062 }
1063 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -07001064 {
1065 // It is now OK to start posting tasks to the encoder task queue.
1066 rtc::CritScope cs(&encoder_queue_lock_);
1067 encoder_queue_is_active_ = true;
1068 }
solenberg08b19df2017-02-15 00:42:31 -08001069 // Resume the previous sequence number which was reset by StopSend(). This
1070 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1071 if (send_sequence_number_) {
1072 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1073 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001074 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001075 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1076 _engineStatisticsPtr->SetLastError(
1077 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1078 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001079 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001080 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001081 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001082 return -1;
1083 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001084
kwiberg55b97fe2016-01-28 05:22:45 -08001085 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001086}
1087
henrikaec6fbd22017-03-31 05:43:36 -07001088void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -08001089 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1090 "Channel::StopSend()");
1091 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -07001092 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001093 }
1094 channel_state_.SetSending(false);
1095
henrikaec6fbd22017-03-31 05:43:36 -07001096 // Post a task to the encoder thread which sets an event when the task is
1097 // executed. We know that no more encoding tasks will be added to the task
1098 // queue for this channel since sending is now deactivated. It means that,
1099 // if we wait for the event to bet set, we know that no more pending tasks
1100 // exists and it is therfore guaranteed that the task queue will never try
1101 // to acccess and invalid channel object.
1102 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001103
henrikaec6fbd22017-03-31 05:43:36 -07001104 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001105 {
1106 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1107 // than this final "flush task" to be posted on the queue.
1108 rtc::CritScope cs(&encoder_queue_lock_);
1109 encoder_queue_is_active_ = false;
1110 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1111 }
henrikaec6fbd22017-03-31 05:43:36 -07001112 flush.Wait(rtc::Event::kForever);
1113
kwiberg55b97fe2016-01-28 05:22:45 -08001114 // Store the sequence number to be able to pick up the same sequence for
1115 // the next StartSend(). This is needed for restarting device, otherwise
1116 // it might cause libSRTP to complain about packets being replayed.
1117 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1118 // CL is landed. See issue
1119 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1120 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1121
1122 // Reset sending SSRC and sequence number and triggers direct transmission
1123 // of RTCP BYE
1124 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1125 _engineStatisticsPtr->SetLastError(
1126 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1127 "StartSend() RTP/RTCP failed to stop sending");
1128 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001129 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001130}
1131
ossu1ffbd6c2017-04-06 12:05:04 -07001132bool Channel::SetEncoder(int payload_type,
1133 std::unique_ptr<AudioEncoder> encoder) {
1134 RTC_DCHECK_GE(payload_type, 0);
1135 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001136 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1137 // one for for us to keep track of sample rate and number of channels, etc.
1138
1139 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1140 // as well as some other things, so we collect this info and send it along.
1141 CodecInst rtp_codec;
1142 rtp_codec.pltype = payload_type;
1143 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1144 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001145 // Seems unclear if it should be clock rate or sample rate. CodecInst
1146 // supposedly carries the sample rate, but only clock rate seems sensible to
1147 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001148 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1149 rtp_codec.pacsize = rtc::CheckedDivExact(
1150 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1151 100);
1152 rtp_codec.channels = encoder->NumChannels();
1153 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001154
ossu76d29f92017-06-09 07:30:13 -07001155 // For audio encoding we need, instead, the actual sample rate of the codec.
1156 // The rest of the information should be the same.
1157 CodecInst send_codec = rtp_codec;
1158 send_codec.plfreq = encoder->SampleRateHz();
1159 cached_send_codec_.emplace(send_codec);
1160
1161 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001162 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001163 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001164 WEBRTC_TRACE(
1165 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1166 "SetEncoder() failed to register codec to RTP/RTCP module");
1167 return false;
1168 }
1169 }
1170
1171 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001172 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001173 return true;
1174}
1175
ossu20a4b3f2017-04-27 02:08:52 -07001176void Channel::ModifyEncoder(
1177 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1178 audio_coding_->ModifyEncoder(modifier);
1179}
1180
kwiberg55b97fe2016-01-28 05:22:45 -08001181int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1182 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1183 "Channel::RegisterVoiceEngineObserver()");
1184 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001185
kwiberg55b97fe2016-01-28 05:22:45 -08001186 if (_voiceEngineObserverPtr) {
1187 _engineStatisticsPtr->SetLastError(
1188 VE_INVALID_OPERATION, kTraceError,
1189 "RegisterVoiceEngineObserver() observer already enabled");
1190 return -1;
1191 }
1192 _voiceEngineObserverPtr = &observer;
1193 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001194}
1195
kwiberg55b97fe2016-01-28 05:22:45 -08001196int32_t Channel::DeRegisterVoiceEngineObserver() {
1197 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1198 "Channel::DeRegisterVoiceEngineObserver()");
1199 rtc::CritScope cs(&_callbackCritSect);
1200
1201 if (!_voiceEngineObserverPtr) {
1202 _engineStatisticsPtr->SetLastError(
1203 VE_INVALID_OPERATION, kTraceWarning,
1204 "DeRegisterVoiceEngineObserver() observer already disabled");
1205 return 0;
1206 }
1207 _voiceEngineObserverPtr = NULL;
1208 return 0;
1209}
1210
1211int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001212 if (cached_send_codec_) {
1213 codec = *cached_send_codec_;
1214 return 0;
1215 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001216 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1217 if (send_codec) {
1218 codec = *send_codec;
1219 return 0;
1220 }
1221 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001222 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001223}
1224
kwiberg55b97fe2016-01-28 05:22:45 -08001225int32_t Channel::GetRecCodec(CodecInst& codec) {
1226 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001227}
1228
kwiberg55b97fe2016-01-28 05:22:45 -08001229int32_t Channel::SetSendCodec(const CodecInst& codec) {
1230 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1231 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001232
kwibergc8d071e2016-04-06 12:22:38 -07001233 if (!codec_manager_.RegisterEncoder(codec) ||
1234 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001235 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1236 "SetSendCodec() failed to register codec to ACM");
1237 return -1;
1238 }
1239
1240 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1241 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1242 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1243 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1244 "SetSendCodec() failed to register codec to"
1245 " RTP/RTCP module");
1246 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001247 }
kwiberg55b97fe2016-01-28 05:22:45 -08001248 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001249
ossu76d29f92017-06-09 07:30:13 -07001250 cached_send_codec_.reset();
1251
kwiberg55b97fe2016-01-28 05:22:45 -08001252 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001253}
1254
minyue78b4d562016-11-30 04:47:39 -08001255void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001256 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1257 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001258 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001259 if (*encoder) {
1260 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001261 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001262 }
1263 });
michaelt566d8202017-01-12 10:17:38 -08001264 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001265}
1266
elad.alond12a8e12017-03-23 11:04:48 -07001267void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1268 if (!use_twcc_plr_for_ana_)
1269 return;
minyue7e304322016-10-12 05:00:55 -07001270 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001271 if (*encoder) {
1272 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1273 }
1274 });
1275}
1276
elad.alondadb4dc2017-03-23 15:29:50 -07001277void Channel::OnRecoverableUplinkPacketLossRate(
1278 float recoverable_packet_loss_rate) {
1279 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1280 if (*encoder) {
1281 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1282 recoverable_packet_loss_rate);
1283 }
1284 });
1285}
1286
elad.alond12a8e12017-03-23 11:04:48 -07001287void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1288 if (use_twcc_plr_for_ana_)
1289 return;
1290 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1291 if (*encoder) {
1292 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1293 }
minyue7e304322016-10-12 05:00:55 -07001294 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001295}
1296
kwiberg1c07c702017-03-27 07:15:49 -07001297void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1298 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1299 audio_coding_->SetReceiveCodecs(codecs);
1300}
1301
minyue7e304322016-10-12 05:00:55 -07001302bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1303 bool success = false;
1304 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1305 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001306 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1307 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001308 }
1309 });
1310 return success;
1311}
1312
1313void Channel::DisableAudioNetworkAdaptor() {
1314 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1315 if (*encoder)
1316 (*encoder)->DisableAudioNetworkAdaptor();
1317 });
1318}
1319
1320void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1321 int max_frame_length_ms) {
1322 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1323 if (*encoder) {
1324 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1325 max_frame_length_ms);
1326 }
1327 });
1328}
1329
mflodman3d7db262016-04-29 00:57:13 -07001330int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001331 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001332 "Channel::RegisterExternalTransport()");
1333
kwiberg55b97fe2016-01-28 05:22:45 -08001334 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001335 if (_externalTransport) {
1336 _engineStatisticsPtr->SetLastError(
1337 VE_INVALID_OPERATION, kTraceError,
1338 "RegisterExternalTransport() external transport already enabled");
1339 return -1;
1340 }
1341 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001342 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001343 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001344}
1345
kwiberg55b97fe2016-01-28 05:22:45 -08001346int32_t Channel::DeRegisterExternalTransport() {
1347 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1348 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001349
kwiberg55b97fe2016-01-28 05:22:45 -08001350 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001351 if (_transportPtr) {
1352 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1353 "DeRegisterExternalTransport() all transport is disabled");
1354 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001355 _engineStatisticsPtr->SetLastError(
1356 VE_INVALID_OPERATION, kTraceWarning,
1357 "DeRegisterExternalTransport() external transport already "
1358 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001359 }
1360 _externalTransport = false;
1361 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001362 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001363}
1364
nisse657bab22017-02-21 06:28:10 -08001365void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1366 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg946d8862017-09-21 04:02:53 -07001367 "Channel::OnRtpPacket()");
nisse657bab22017-02-21 06:28:10 -08001368
1369 RTPHeader header;
1370 packet.GetHeader(&header);
solenberg946d8862017-09-21 04:02:53 -07001371
1372 // Store playout timestamp for the received RTP packet
1373 UpdatePlayoutTimestamp(false);
1374
1375 header.payload_type_frequency =
1376 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
1377 if (header.payload_type_frequency >= 0) {
1378 bool in_order = IsPacketInOrder(header);
1379 rtp_receive_statistics_->IncomingPacket(
1380 header, packet.size(), IsPacketRetransmitted(header, in_order));
1381 rtp_payload_registry_->SetIncomingPayloadType(header);
1382
1383 ReceivePacket(packet.data(), packet.size(), header, in_order);
1384 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001385}
1386
1387bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001388 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001389 const RTPHeader& header,
1390 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001391 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001392 assert(packet_length >= header.headerLength);
1393 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001394 PayloadUnion payload_specific;
1395 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001396 &payload_specific)) {
1397 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001398 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001399 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1400 payload_specific, in_order);
1401}
1402
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001403bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1404 StreamStatistician* statistician =
1405 rtp_receive_statistics_->GetStatistician(header.ssrc);
1406 if (!statistician)
1407 return false;
1408 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001409}
1410
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001411bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1412 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001413 StreamStatistician* statistician =
1414 rtp_receive_statistics_->GetStatistician(header.ssrc);
1415 if (!statistician)
1416 return false;
1417 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001418 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001419 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001420 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001421}
1422
mflodman3d7db262016-04-29 00:57:13 -07001423int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001424 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001425 "Channel::ReceivedRTCPPacket()");
1426 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001427 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001428
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001429 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001430 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001431
Minyue2013aec2015-05-13 14:14:42 +02001432 int64_t rtt = GetRTT(true);
1433 if (rtt == 0) {
1434 // Waiting for valid RTT.
1435 return 0;
1436 }
Erik Språng737336d2016-07-29 12:59:36 +02001437
1438 int64_t nack_window_ms = rtt;
1439 if (nack_window_ms < kMinRetransmissionWindowMs) {
1440 nack_window_ms = kMinRetransmissionWindowMs;
1441 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1442 nack_window_ms = kMaxRetransmissionWindowMs;
1443 }
1444 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1445
minyue7e304322016-10-12 05:00:55 -07001446 // Invoke audio encoders OnReceivedRtt().
1447 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1448 if (*encoder)
1449 (*encoder)->OnReceivedRtt(rtt);
1450 });
1451
Minyue2013aec2015-05-13 14:14:42 +02001452 uint32_t ntp_secs = 0;
1453 uint32_t ntp_frac = 0;
1454 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001455 if (0 !=
1456 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1457 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001458 // Waiting for RTCP.
1459 return 0;
1460 }
1461
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001462 {
tommi31fc21f2016-01-21 10:37:37 -08001463 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001464 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001465 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001466 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001467}
1468
solenberg8d73f8c2017-03-08 01:52:20 -08001469int Channel::GetSpeechOutputLevel() const {
1470 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001471}
1472
solenberg8d73f8c2017-03-08 01:52:20 -08001473int Channel::GetSpeechOutputLevelFullRange() const {
1474 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001475}
1476
zsteine76bd3a2017-07-14 12:17:49 -07001477double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001478 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001479}
1480
1481double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001482 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001483}
1484
solenberg8d73f8c2017-03-08 01:52:20 -08001485void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001486 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001487 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001488}
1489
solenberg1c2af8e2016-03-24 10:36:00 -07001490bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001491 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001492 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001493}
1494
solenberg8d73f8c2017-03-08 01:52:20 -08001495void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001496 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001497 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001498}
1499
solenberg8842c3e2016-03-11 03:06:41 -08001500int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001501 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001502 "Channel::SendTelephoneEventOutband(...)");
1503 RTC_DCHECK_LE(0, event);
1504 RTC_DCHECK_GE(255, event);
1505 RTC_DCHECK_LE(0, duration_ms);
1506 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001507 if (!Sending()) {
1508 return -1;
1509 }
solenberg8842c3e2016-03-11 03:06:41 -08001510 if (_rtpRtcpModule->SendTelephoneEventOutband(
1511 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001512 _engineStatisticsPtr->SetLastError(
1513 VE_SEND_DTMF_FAILED, kTraceWarning,
1514 "SendTelephoneEventOutband() failed to send event");
1515 return -1;
1516 }
1517 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001518}
1519
solenbergffbbcac2016-11-17 05:25:37 -08001520int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1521 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001522 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001523 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001524 RTC_DCHECK_LE(0, payload_type);
1525 RTC_DCHECK_GE(127, payload_type);
1526 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001527 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001528 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001529 memcpy(codec.plname, "telephone-event", 16);
1530 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1531 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1532 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1533 _engineStatisticsPtr->SetLastError(
1534 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1535 "SetSendTelephoneEventPayloadType() failed to register send"
1536 "payload type");
1537 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001538 }
kwiberg55b97fe2016-01-28 05:22:45 -08001539 }
kwiberg55b97fe2016-01-28 05:22:45 -08001540 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001541}
1542
kwiberg55b97fe2016-01-28 05:22:45 -08001543int Channel::SetLocalSSRC(unsigned int ssrc) {
1544 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1545 "Channel::SetLocalSSRC()");
1546 if (channel_state_.Get().sending) {
1547 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
1548 "SetLocalSSRC() already sending");
1549 return -1;
1550 }
1551 _rtpRtcpModule->SetSSRC(ssrc);
1552 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001553}
1554
kwiberg55b97fe2016-01-28 05:22:45 -08001555int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1556 ssrc = rtp_receiver_->SSRC();
1557 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001558}
1559
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001560int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001561 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001562 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001563}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001564
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001565int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1566 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001567 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1568 if (enable &&
1569 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1570 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001571 return -1;
1572 }
1573 return 0;
1574}
1575
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001576void Channel::EnableSendTransportSequenceNumber(int id) {
1577 int ret =
1578 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1579 RTC_DCHECK_EQ(0, ret);
1580}
1581
stefan3313ec92016-01-21 06:32:43 -08001582void Channel::EnableReceiveTransportSequenceNumber(int id) {
1583 rtp_header_parser_->DeregisterRtpHeaderExtension(
1584 kRtpExtensionTransportSequenceNumber);
1585 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1586 kRtpExtensionTransportSequenceNumber, id);
1587 RTC_DCHECK(ret);
1588}
1589
stefanbba9dec2016-02-01 04:39:55 -08001590void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001591 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001592 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001593 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1594 TransportFeedbackObserver* transport_feedback_observer =
1595 transport->transport_feedback_observer();
1596 PacketRouter* packet_router = transport->packet_router();
1597
stefanbba9dec2016-02-01 04:39:55 -08001598 RTC_DCHECK(rtp_packet_sender);
1599 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001600 RTC_DCHECK(packet_router);
1601 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001602 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001603 feedback_observer_proxy_->SetTransportFeedbackObserver(
1604 transport_feedback_observer);
1605 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1606 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1607 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001608 constexpr bool remb_candidate = false;
1609 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001610 packet_router_ = packet_router;
1611}
1612
stefanbba9dec2016-02-01 04:39:55 -08001613void Channel::RegisterReceiverCongestionControlObjects(
1614 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001615 RTC_DCHECK(packet_router);
1616 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001617 constexpr bool remb_candidate = false;
1618 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001619 packet_router_ = packet_router;
1620}
1621
nissefdbfdc92017-03-31 05:44:52 -07001622void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001623 RTC_DCHECK(packet_router_);
1624 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001625 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001626 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1627 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001628 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001629 packet_router_ = nullptr;
1630 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1631}
1632
nissefdbfdc92017-03-31 05:44:52 -07001633void Channel::ResetReceiverCongestionControlObjects() {
1634 RTC_DCHECK(packet_router_);
1635 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1636 packet_router_ = nullptr;
1637}
1638
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001639void Channel::SetRTCPStatus(bool enable) {
1640 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1641 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001642 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001643}
1644
kwiberg55b97fe2016-01-28 05:22:45 -08001645int Channel::SetRTCP_CNAME(const char cName[256]) {
1646 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1647 "Channel::SetRTCP_CNAME()");
1648 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
1649 _engineStatisticsPtr->SetLastError(
1650 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1651 "SetRTCP_CNAME() failed to set RTCP CNAME");
1652 return -1;
1653 }
1654 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001655}
1656
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001657int Channel::GetRemoteRTCPReportBlocks(
1658 std::vector<ReportBlock>* report_blocks) {
1659 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08001660 _engineStatisticsPtr->SetLastError(
1661 VE_INVALID_ARGUMENT, kTraceError,
1662 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001663 return -1;
1664 }
1665
1666 // Get the report blocks from the latest received RTCP Sender or Receiver
1667 // Report. Each element in the vector contains the sender's SSRC and a
1668 // report block according to RFC 3550.
1669 std::vector<RTCPReportBlock> rtcp_report_blocks;
1670 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001671 return -1;
1672 }
1673
1674 if (rtcp_report_blocks.empty())
1675 return 0;
1676
1677 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1678 for (; it != rtcp_report_blocks.end(); ++it) {
1679 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001680 report_block.sender_SSRC = it->sender_ssrc;
1681 report_block.source_SSRC = it->source_ssrc;
1682 report_block.fraction_lost = it->fraction_lost;
1683 report_block.cumulative_num_packets_lost = it->packets_lost;
1684 report_block.extended_highest_sequence_number =
1685 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001686 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001687 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1688 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001689 report_blocks->push_back(report_block);
1690 }
1691 return 0;
1692}
1693
kwiberg55b97fe2016-01-28 05:22:45 -08001694int Channel::GetRTPStatistics(CallStatistics& stats) {
1695 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001696
kwiberg55b97fe2016-01-28 05:22:45 -08001697 // The jitter statistics is updated for each received RTP packet and is
1698 // based on received packets.
1699 RtcpStatistics statistics;
1700 StreamStatistician* statistician =
1701 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001702 if (statistician) {
1703 statistician->GetStatistics(&statistics,
1704 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001705 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001706
kwiberg55b97fe2016-01-28 05:22:45 -08001707 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001708 stats.cumulativeLost = statistics.packets_lost;
1709 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001710 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001711
kwiberg55b97fe2016-01-28 05:22:45 -08001712 // --- RTT
1713 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001714
kwiberg55b97fe2016-01-28 05:22:45 -08001715 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001716
kwiberg55b97fe2016-01-28 05:22:45 -08001717 size_t bytesSent(0);
1718 uint32_t packetsSent(0);
1719 size_t bytesReceived(0);
1720 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001721
kwiberg55b97fe2016-01-28 05:22:45 -08001722 if (statistician) {
1723 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1724 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001725
kwiberg55b97fe2016-01-28 05:22:45 -08001726 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
1727 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1728 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
1729 " output will not be complete");
1730 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001731
kwiberg55b97fe2016-01-28 05:22:45 -08001732 stats.bytesSent = bytesSent;
1733 stats.packetsSent = packetsSent;
1734 stats.bytesReceived = bytesReceived;
1735 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001736
kwiberg55b97fe2016-01-28 05:22:45 -08001737 // --- Timestamps
1738 {
1739 rtc::CritScope lock(&ts_stats_lock_);
1740 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1741 }
1742 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001743}
1744
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001745void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1746 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001747 // If pacing is enabled we always store packets.
1748 if (!pacing_enabled_)
1749 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001750 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001751 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001752 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001753 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001754 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001755}
1756
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001757// Called when we are missing one or more packets.
1758int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001759 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1760}
1761
henrikaec6fbd22017-03-31 05:43:36 -07001762void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001763 // Avoid posting any new tasks if sending was already stopped in StopSend().
1764 rtc::CritScope cs(&encoder_queue_lock_);
1765 if (!encoder_queue_is_active_) {
1766 return;
1767 }
henrikaec6fbd22017-03-31 05:43:36 -07001768 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1769 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1770 // either into pool of frames or into the task itself.
1771 audio_frame->CopyFrom(audio_input);
1772 audio_frame->id_ = ChannelId();
1773 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1774 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001775}
1776
henrikaec6fbd22017-03-31 05:43:36 -07001777void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1778 int sample_rate,
1779 size_t number_of_frames,
1780 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001781 // Avoid posting as new task if sending was already stopped in StopSend().
1782 rtc::CritScope cs(&encoder_queue_lock_);
1783 if (!encoder_queue_is_active_) {
1784 return;
1785 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001786 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001787 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001788 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1789 audio_frame->id_ = ChannelId();
ossu950c1c92017-07-11 08:19:31 -07001790 // TODO(ossu): Investigate how this could happen. b/62909493
1791 if (result == 0) {
1792 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1793 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1794 } else {
1795 audio_frame->sample_rate_hz_ = sample_rate;
1796 audio_frame->num_channels_ = number_of_channels;
1797 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1798 RTC_NOTREACHED();
1799 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001800 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001801 sample_rate, &input_resampler_, audio_frame.get());
1802 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1803 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001804}
1805
henrikaec6fbd22017-03-31 05:43:36 -07001806void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1807 RTC_DCHECK_RUN_ON(encoder_queue_);
1808 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1809 RTC_DCHECK_LE(audio_input->num_channels_, 2);
1810 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08001811
henrikaec6fbd22017-03-31 05:43:36 -07001812 bool is_muted = InputMute();
1813 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001814
kwiberg55b97fe2016-01-28 05:22:45 -08001815 if (_includeAudioLevelIndication) {
1816 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001817 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001818 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001819 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001820 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001821 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001822 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001823 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001824 }
kwiberg55b97fe2016-01-28 05:22:45 -08001825 }
solenberg1c2af8e2016-03-24 10:36:00 -07001826 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001827
henrikaec6fbd22017-03-31 05:43:36 -07001828 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001829
kwiberg55b97fe2016-01-28 05:22:45 -08001830 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001831 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001832 // This call will trigger AudioPacketizationCallback::SendData if encoding
1833 // is done and payload is ready for packetization and transmission.
1834 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001835 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1836 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1837 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001838 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001839
henrikaec6fbd22017-03-31 05:43:36 -07001840 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001841}
1842
solenberg7602aab2016-11-14 11:30:07 -08001843void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1844 RTC_DCHECK(!channel.channel() ||
1845 channel.channel()->ChannelId() != _channelId);
1846 rtc::CritScope lock(&assoc_send_channel_lock_);
1847 associate_send_channel_ = channel;
1848}
1849
Minyue2013aec2015-05-13 14:14:42 +02001850void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001851 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001852 Channel* channel = associate_send_channel_.channel();
1853 if (channel && channel->ChannelId() == channel_id) {
1854 // If this channel is associated with a send channel of the specified
1855 // Channel ID, disassociate with it.
1856 ChannelOwner ref(NULL);
1857 associate_send_channel_ = ref;
1858 }
1859}
1860
ivoc14d5dbe2016-07-04 07:06:55 -07001861void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1862 event_log_proxy_->SetEventLog(event_log);
1863}
1864
michaelt9332b7d2016-11-30 07:51:13 -08001865void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1866 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1867}
1868
nisse284542b2017-01-10 08:58:32 -08001869void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001870 size_t overhead_per_packet =
1871 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001872 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1873 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001874 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001875 }
1876 });
1877}
1878
1879void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001880 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001881 transport_overhead_per_packet_ = transport_overhead_per_packet;
1882 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001883}
1884
hbos3fd31fe2017-02-28 05:43:16 -08001885// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001886void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001887 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001888 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1889 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001890}
1891
kwiberg55b97fe2016-01-28 05:22:45 -08001892int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1893 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001894}
1895
wu@webrtc.org24301a62013-12-13 19:17:43 +00001896void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1897 audio_coding_->GetDecodingCallStatistics(stats);
1898}
1899
ivoce1198e02017-09-08 08:13:19 -07001900ANAStats Channel::GetANAStatistics() const {
1901 return audio_coding_->GetANAStats();
1902}
1903
solenberg358057b2015-11-27 10:46:42 -08001904uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08001905 rtc::CritScope lock(&video_sync_lock_);
1906 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07001907}
1908
kwiberg55b97fe2016-01-28 05:22:45 -08001909int Channel::SetMinimumPlayoutDelay(int delayMs) {
1910 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1911 "Channel::SetMinimumPlayoutDelay()");
1912 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
1913 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
1914 _engineStatisticsPtr->SetLastError(
1915 VE_INVALID_ARGUMENT, kTraceError,
1916 "SetMinimumPlayoutDelay() invalid min delay");
1917 return -1;
1918 }
1919 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
1920 _engineStatisticsPtr->SetLastError(
1921 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1922 "SetMinimumPlayoutDelay() failed to set min playout delay");
1923 return -1;
1924 }
1925 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001926}
1927
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001928int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07001929 uint32_t playout_timestamp_rtp = 0;
1930 {
tommi31fc21f2016-01-21 10:37:37 -08001931 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07001932 playout_timestamp_rtp = playout_timestamp_rtp_;
1933 }
kwiberg55b97fe2016-01-28 05:22:45 -08001934 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001935 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07001936 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001937 "GetPlayoutTimestamp() failed to retrieve timestamp");
1938 return -1;
1939 }
deadbeef74375882015-08-13 12:09:10 -07001940 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001941 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001942}
1943
kwiberg55b97fe2016-01-28 05:22:45 -08001944int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
1945 RtpReceiver** rtp_receiver) const {
1946 *rtpRtcpModule = _rtpRtcpModule.get();
1947 *rtp_receiver = rtp_receiver_.get();
1948 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001949}
1950
deadbeef74375882015-08-13 12:09:10 -07001951void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001952 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07001953
henrik.lundin96bd5022016-04-06 04:13:56 -07001954 if (!jitter_buffer_playout_timestamp_) {
1955 // This can happen if this channel has not received any RTP packets. In
1956 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07001957 return;
1958 }
1959
1960 uint16_t delay_ms = 0;
1961 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001962 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001963 "Channel::UpdatePlayoutTimestamp() failed to read playout"
1964 " delay from the ADM");
1965 _engineStatisticsPtr->SetLastError(
1966 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
1967 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
1968 return;
1969 }
1970
henrik.lundin96bd5022016-04-06 04:13:56 -07001971 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1972 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07001973
1974 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07001975 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07001976
kwiberg55b97fe2016-01-28 05:22:45 -08001977 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07001978 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07001979 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07001980
1981 {
tommi31fc21f2016-01-21 10:37:37 -08001982 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08001983 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07001984 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07001985 }
1986 playout_delay_ms_ = delay_ms;
1987 }
1988}
1989
kwiberg55b97fe2016-01-28 05:22:45 -08001990void Channel::RegisterReceiveCodecsToRTPModule() {
1991 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1992 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001993
kwiberg55b97fe2016-01-28 05:22:45 -08001994 CodecInst codec;
1995 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00001996
kwiberg55b97fe2016-01-28 05:22:45 -08001997 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1998 // Open up the RTP/RTCP receiver for all supported codecs
1999 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08002000 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08002001 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2002 "Channel::RegisterReceiveCodecsToRTPModule() unable"
2003 " to register %s (%d/%d/%" PRIuS
2004 "/%d) to RTP/RTCP "
2005 "receiver",
2006 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2007 codec.rate);
2008 } else {
2009 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2010 "Channel::RegisterReceiveCodecsToRTPModule() %s "
2011 "(%d/%d/%" PRIuS
2012 "/%d) has been added to the RTP/RTCP "
2013 "receiver",
2014 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2015 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00002016 }
kwiberg55b97fe2016-01-28 05:22:45 -08002017 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002018}
2019
kwiberg55b97fe2016-01-28 05:22:45 -08002020int Channel::SetSendRtpHeaderExtension(bool enable,
2021 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002022 unsigned char id) {
2023 int error = 0;
2024 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
2025 if (enable) {
2026 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
2027 }
2028 return error;
2029}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002030
ossue280cde2016-10-12 11:04:10 -07002031int Channel::GetRtpTimestampRateHz() const {
2032 const auto format = audio_coding_->ReceiveFormat();
2033 // Default to the playout frequency if we've not gotten any packets yet.
2034 // TODO(ossu): Zero clockrate can only happen if we've added an external
2035 // decoder for a format we don't support internally. Remove once that way of
2036 // adding decoders is gone!
2037 return (format && format->clockrate_hz != 0)
2038 ? format->clockrate_hz
2039 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00002040}
2041
Minyue2013aec2015-05-13 14:14:42 +02002042int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07002043 RtcpMode method = _rtpRtcpModule->RTCP();
2044 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002045 return 0;
2046 }
2047 std::vector<RTCPReportBlock> report_blocks;
2048 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02002049
2050 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002051 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02002052 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08002053 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002054 Channel* channel = associate_send_channel_.channel();
2055 // Tries to get RTT from an associated channel. This is important for
2056 // receive-only channels.
2057 if (channel) {
2058 // To prevent infinite recursion and deadlock, calling GetRTT of
2059 // associate channel should always use "false" for argument:
2060 // |allow_associate_channel|.
2061 rtt = channel->GetRTT(false);
2062 }
2063 }
2064 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002065 }
2066
2067 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2068 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
2069 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07002070 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002071 break;
2072 }
2073 if (it == report_blocks.end()) {
2074 // We have not received packets with SSRC matching the report blocks.
2075 // To calculate RTT we try with the SSRC of the first report block.
2076 // This is very important for send-only channels where we don't know
2077 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07002078 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002079 }
Minyue2013aec2015-05-13 14:14:42 +02002080
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002081 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002082 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002083 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002084 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
2085 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002086 return 0;
2087 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002088 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002089}
2090
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00002091} // namespace voe
2092} // namespace webrtc