blob: 49bc381746e3eda384198f5ea07c0b4a830b2449 [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"
42#include "voice_engine/include/voe_rtp_rtcp.h"
43#include "voice_engine/output_mixer.h"
44#include "voice_engine/statistics.h"
45#include "voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000046
andrew@webrtc.org50419b02012-11-14 19:07:54 +000047namespace webrtc {
48namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000049
kwibergc8d071e2016-04-06 12:22:38 -070050namespace {
51
zsteine76bd3a2017-07-14 12:17:49 -070052constexpr double kAudioSampleDurationSeconds = 0.01;
Erik Språng737336d2016-07-29 12:59:36 +020053constexpr int64_t kMaxRetransmissionWindowMs = 1000;
54constexpr int64_t kMinRetransmissionWindowMs = 30;
55
kwibergc8d071e2016-04-06 12:22:38 -070056} // namespace
57
solenberg8842c3e2016-03-11 03:06:41 -080058const int kTelephoneEventAttenuationdB = 10;
59
ivoc14d5dbe2016-07-04 07:06:55 -070060class RtcEventLogProxy final : public webrtc::RtcEventLog {
61 public:
62 RtcEventLogProxy() : event_log_(nullptr) {}
63
64 bool StartLogging(const std::string& file_name,
65 int64_t max_size_bytes) override {
66 RTC_NOTREACHED();
67 return false;
68 }
69
70 bool StartLogging(rtc::PlatformFile log_file,
71 int64_t max_size_bytes) override {
72 RTC_NOTREACHED();
73 return false;
74 }
75
76 void StopLogging() override { RTC_NOTREACHED(); }
77
78 void LogVideoReceiveStreamConfig(
perkj09e71da2017-05-22 03:26:49 -070079 const webrtc::rtclog::StreamConfig&) override {
80 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070081 }
82
perkjc0876aa2017-05-22 04:08:28 -070083 void LogVideoSendStreamConfig(const webrtc::rtclog::StreamConfig&) override {
84 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070085 }
86
ivoce0928d82016-10-10 05:12:51 -070087 void LogAudioReceiveStreamConfig(
perkjac8f52d2017-05-22 09:36:28 -070088 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070089 rtc::CritScope lock(&crit_);
90 if (event_log_) {
91 event_log_->LogAudioReceiveStreamConfig(config);
92 }
93 }
94
95 void LogAudioSendStreamConfig(
perkjf4726992017-05-22 10:12:26 -070096 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070097 rtc::CritScope lock(&crit_);
98 if (event_log_) {
99 event_log_->LogAudioSendStreamConfig(config);
100 }
101 }
102
ivoc14d5dbe2016-07-04 07:06:55 -0700103 void LogRtpHeader(webrtc::PacketDirection direction,
ivoc14d5dbe2016-07-04 07:06:55 -0700104 const uint8_t* header,
105 size_t packet_length) override {
perkj77cd58e2017-05-30 03:52:10 -0700106 LogRtpHeader(direction, header, packet_length, PacedPacketInfo::kNotAProbe);
philipel32d00102017-02-27 02:18:46 -0800107 }
108
109 void LogRtpHeader(webrtc::PacketDirection direction,
philipel32d00102017-02-27 02:18:46 -0800110 const uint8_t* header,
111 size_t packet_length,
112 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700113 rtc::CritScope lock(&crit_);
114 if (event_log_) {
perkj77cd58e2017-05-30 03:52:10 -0700115 event_log_->LogRtpHeader(direction, header, packet_length,
philipel32d00102017-02-27 02:18:46 -0800116 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700117 }
118 }
119
120 void LogRtcpPacket(webrtc::PacketDirection direction,
ivoc14d5dbe2016-07-04 07:06:55 -0700121 const uint8_t* packet,
122 size_t length) override {
123 rtc::CritScope lock(&crit_);
124 if (event_log_) {
perkj77cd58e2017-05-30 03:52:10 -0700125 event_log_->LogRtcpPacket(direction, packet, length);
ivoc14d5dbe2016-07-04 07:06:55 -0700126 }
127 }
128
129 void LogAudioPlayout(uint32_t ssrc) override {
130 rtc::CritScope lock(&crit_);
131 if (event_log_) {
132 event_log_->LogAudioPlayout(ssrc);
133 }
134 }
135
terelius424e6cf2017-02-20 05:14:41 -0800136 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700137 uint8_t fraction_loss,
138 int32_t total_packets) override {
139 rtc::CritScope lock(&crit_);
140 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800141 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
142 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700143 }
144 }
145
terelius424e6cf2017-02-20 05:14:41 -0800146 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800147 BandwidthUsage detector_state) override {
148 rtc::CritScope lock(&crit_);
149 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800150 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800151 }
152 }
153
minyue4b7c9522017-01-24 04:54:59 -0800154 void LogAudioNetworkAdaptation(
michaeltcde46b72017-04-06 05:59:10 -0700155 const AudioEncoderRuntimeConfig& config) override {
minyue4b7c9522017-01-24 04:54:59 -0800156 rtc::CritScope lock(&crit_);
157 if (event_log_) {
158 event_log_->LogAudioNetworkAdaptation(config);
159 }
160 }
161
philipel32d00102017-02-27 02:18:46 -0800162 void LogProbeClusterCreated(int id,
163 int bitrate_bps,
164 int min_probes,
165 int min_bytes) override {
166 rtc::CritScope lock(&crit_);
167 if (event_log_) {
168 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
169 min_bytes);
170 }
171 };
172
173 void LogProbeResultSuccess(int id, int bitrate_bps) override {
174 rtc::CritScope lock(&crit_);
175 if (event_log_) {
176 event_log_->LogProbeResultSuccess(id, bitrate_bps);
177 }
178 };
179
180 void LogProbeResultFailure(int id,
181 ProbeFailureReason failure_reason) override {
182 rtc::CritScope lock(&crit_);
183 if (event_log_) {
184 event_log_->LogProbeResultFailure(id, failure_reason);
185 }
186 };
187
ivoc14d5dbe2016-07-04 07:06:55 -0700188 void SetEventLog(RtcEventLog* event_log) {
189 rtc::CritScope lock(&crit_);
190 event_log_ = event_log;
191 }
192
193 private:
194 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700195 RtcEventLog* event_log_ RTC_GUARDED_BY(crit_);
ivoc14d5dbe2016-07-04 07:06:55 -0700196 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
197};
198
michaelt9332b7d2016-11-30 07:51:13 -0800199class RtcpRttStatsProxy final : public RtcpRttStats {
200 public:
201 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
202
203 void OnRttUpdate(int64_t rtt) override {
204 rtc::CritScope lock(&crit_);
205 if (rtcp_rtt_stats_)
206 rtcp_rtt_stats_->OnRttUpdate(rtt);
207 }
208
209 int64_t LastProcessedRtt() const override {
210 rtc::CritScope lock(&crit_);
211 if (!rtcp_rtt_stats_)
212 return 0;
213 return rtcp_rtt_stats_->LastProcessedRtt();
214 }
215
216 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
217 rtc::CritScope lock(&crit_);
218 rtcp_rtt_stats_ = rtcp_rtt_stats;
219 }
220
221 private:
222 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700223 RtcpRttStats* rtcp_rtt_stats_ RTC_GUARDED_BY(crit_);
michaelt9332b7d2016-11-30 07:51:13 -0800224 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
225};
226
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100227class TransportFeedbackProxy : public TransportFeedbackObserver {
228 public:
229 TransportFeedbackProxy() : feedback_observer_(nullptr) {
230 pacer_thread_.DetachFromThread();
231 network_thread_.DetachFromThread();
232 }
233
234 void SetTransportFeedbackObserver(
235 TransportFeedbackObserver* feedback_observer) {
236 RTC_DCHECK(thread_checker_.CalledOnValidThread());
237 rtc::CritScope lock(&crit_);
238 feedback_observer_ = feedback_observer;
239 }
240
241 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700242 void AddPacket(uint32_t ssrc,
243 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100244 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800245 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100246 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
247 rtc::CritScope lock(&crit_);
248 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700249 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100250 }
philipel8aadd502017-02-23 02:56:13 -0800251
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100252 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
253 RTC_DCHECK(network_thread_.CalledOnValidThread());
254 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700255 if (feedback_observer_)
256 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200257 }
elad.alonf9490002017-03-06 05:32:21 -0800258 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200259 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800260 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100261 }
262
263 private:
264 rtc::CriticalSection crit_;
265 rtc::ThreadChecker thread_checker_;
266 rtc::ThreadChecker pacer_thread_;
267 rtc::ThreadChecker network_thread_;
danilchapa37de392017-09-09 04:17:22 -0700268 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100269};
270
271class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
272 public:
273 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
274 pacer_thread_.DetachFromThread();
275 }
276
277 void SetSequenceNumberAllocator(
278 TransportSequenceNumberAllocator* seq_num_allocator) {
279 RTC_DCHECK(thread_checker_.CalledOnValidThread());
280 rtc::CritScope lock(&crit_);
281 seq_num_allocator_ = seq_num_allocator;
282 }
283
284 // Implements TransportSequenceNumberAllocator.
285 uint16_t AllocateSequenceNumber() override {
286 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
287 rtc::CritScope lock(&crit_);
288 if (!seq_num_allocator_)
289 return 0;
290 return seq_num_allocator_->AllocateSequenceNumber();
291 }
292
293 private:
294 rtc::CriticalSection crit_;
295 rtc::ThreadChecker thread_checker_;
296 rtc::ThreadChecker pacer_thread_;
danilchapa37de392017-09-09 04:17:22 -0700297 TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100298};
299
300class RtpPacketSenderProxy : public RtpPacketSender {
301 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800302 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100303
304 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
305 RTC_DCHECK(thread_checker_.CalledOnValidThread());
306 rtc::CritScope lock(&crit_);
307 rtp_packet_sender_ = rtp_packet_sender;
308 }
309
310 // Implements RtpPacketSender.
311 void InsertPacket(Priority priority,
312 uint32_t ssrc,
313 uint16_t sequence_number,
314 int64_t capture_time_ms,
315 size_t bytes,
316 bool retransmission) override {
317 rtc::CritScope lock(&crit_);
318 if (rtp_packet_sender_) {
319 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
320 capture_time_ms, bytes, retransmission);
321 }
322 }
323
324 private:
325 rtc::ThreadChecker thread_checker_;
326 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700327 RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100328};
329
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000330class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000331 public:
stefan7de8d642017-02-07 07:14:08 -0800332 explicit VoERtcpObserver(Channel* owner)
333 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000334 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000335
stefan7de8d642017-02-07 07:14:08 -0800336 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
337 rtc::CritScope lock(&crit_);
338 bandwidth_observer_ = bandwidth_observer;
339 }
340
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000341 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800342 rtc::CritScope lock(&crit_);
343 if (bandwidth_observer_) {
344 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
345 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000346 }
347
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000348 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
349 int64_t rtt,
350 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800351 {
352 rtc::CritScope lock(&crit_);
353 if (bandwidth_observer_) {
354 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
355 now_ms);
356 }
357 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000358 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
359 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
360 // report for VoiceEngine?
361 if (report_blocks.empty())
362 return;
363
364 int fraction_lost_aggregate = 0;
365 int total_number_of_packets = 0;
366
367 // If receiving multiple report blocks, calculate the weighted average based
368 // on the number of packets a report refers to.
369 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
370 block_it != report_blocks.end(); ++block_it) {
371 // Find the previous extended high sequence number for this remote SSRC,
372 // to calculate the number of RTP packets this report refers to. Ignore if
373 // we haven't seen this SSRC before.
374 std::map<uint32_t, uint32_t>::iterator seq_num_it =
srte3e69e5c2017-08-09 06:13:45 -0700375 extended_max_sequence_number_.find(block_it->source_ssrc);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000376 int number_of_packets = 0;
377 if (seq_num_it != extended_max_sequence_number_.end()) {
srte3e69e5c2017-08-09 06:13:45 -0700378 number_of_packets =
379 block_it->extended_highest_sequence_number - seq_num_it->second;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000380 }
srte3e69e5c2017-08-09 06:13:45 -0700381 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000382 total_number_of_packets += number_of_packets;
383
srte3e69e5c2017-08-09 06:13:45 -0700384 extended_max_sequence_number_[block_it->source_ssrc] =
385 block_it->extended_highest_sequence_number;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000386 }
387 int weighted_fraction_lost = 0;
388 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800389 weighted_fraction_lost =
390 (fraction_lost_aggregate + total_number_of_packets / 2) /
391 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000392 }
elad.alond12a8e12017-03-23 11:04:48 -0700393 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000394 }
395
396 private:
397 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000398 // Maps remote side ssrc to extended highest sequence number received.
399 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800400 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -0700401 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000402};
403
henrikaec6fbd22017-03-31 05:43:36 -0700404class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
405 public:
406 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
407 Channel* channel)
408 : audio_frame_(std::move(audio_frame)), channel_(channel) {
409 RTC_DCHECK(channel_);
410 }
411
412 private:
413 bool Run() override {
414 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
415 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
416 return true;
417 }
418
419 std::unique_ptr<AudioFrame> audio_frame_;
420 Channel* const channel_;
421};
422
kwiberg55b97fe2016-01-28 05:22:45 -0800423int32_t Channel::SendData(FrameType frameType,
424 uint8_t payloadType,
425 uint32_t timeStamp,
426 const uint8_t* payloadData,
427 size_t payloadSize,
428 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700429 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800430 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
431 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
432 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
433 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000434
kwiberg55b97fe2016-01-28 05:22:45 -0800435 if (_includeAudioLevelIndication) {
436 // Store current audio level in the RTP/RTCP module.
437 // The level will be used in combination with voice-activity state
438 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800439 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800440 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000441
kwiberg55b97fe2016-01-28 05:22:45 -0800442 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
443 // packetization.
444 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700445 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800446 (FrameType&)frameType, payloadType, timeStamp,
447 // Leaving the time when this frame was
448 // received from the capture device as
449 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700450 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800451 _engineStatisticsPtr->SetLastError(
452 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
453 "Channel::SendData() failed to send data to RTP/RTCP module");
454 return -1;
455 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000456
kwiberg55b97fe2016-01-28 05:22:45 -0800457 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000458}
459
stefan1d8a5062015-10-02 03:39:33 -0700460bool Channel::SendRtp(const uint8_t* data,
461 size_t len,
462 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800463 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
464 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000465
kwiberg55b97fe2016-01-28 05:22:45 -0800466 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000467
kwiberg55b97fe2016-01-28 05:22:45 -0800468 if (_transportPtr == NULL) {
469 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
470 "Channel::SendPacket() failed to send RTP packet due to"
471 " invalid transport object");
472 return false;
473 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000474
kwiberg55b97fe2016-01-28 05:22:45 -0800475 uint8_t* bufferToSendPtr = (uint8_t*)data;
476 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000477
kwiberg55b97fe2016-01-28 05:22:45 -0800478 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
479 std::string transport_name =
480 _externalTransport ? "external transport" : "WebRtc sockets";
481 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
482 "Channel::SendPacket() RTP transmission using %s failed",
483 transport_name.c_str());
484 return false;
485 }
486 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000487}
488
kwiberg55b97fe2016-01-28 05:22:45 -0800489bool Channel::SendRtcp(const uint8_t* data, size_t len) {
490 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
491 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000492
kwiberg55b97fe2016-01-28 05:22:45 -0800493 rtc::CritScope cs(&_callbackCritSect);
494 if (_transportPtr == NULL) {
495 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
496 "Channel::SendRtcp() failed to send RTCP packet"
497 " due to invalid transport object");
498 return false;
499 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000500
kwiberg55b97fe2016-01-28 05:22:45 -0800501 uint8_t* bufferToSendPtr = (uint8_t*)data;
502 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000503
kwiberg55b97fe2016-01-28 05:22:45 -0800504 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
505 if (n < 0) {
506 std::string transport_name =
507 _externalTransport ? "external transport" : "WebRtc sockets";
508 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
509 "Channel::SendRtcp() transmission using %s failed",
510 transport_name.c_str());
511 return false;
512 }
513 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000514}
515
kwiberg55b97fe2016-01-28 05:22:45 -0800516void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
517 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
518 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000519
kwiberg55b97fe2016-01-28 05:22:45 -0800520 // Update ssrc so that NTP for AV sync can be updated.
521 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000522}
523
Peter Boströmac547a62015-09-17 23:03:57 +0200524void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
525 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
526 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
527 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000528}
529
Peter Boströmac547a62015-09-17 23:03:57 +0200530int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000531 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000532 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000533 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800534 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200535 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800536 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
537 "Channel::OnInitializeDecoder(payloadType=%d, "
538 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
539 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000540
kwiberg55b97fe2016-01-28 05:22:45 -0800541 CodecInst receiveCodec = {0};
542 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000543
kwiberg55b97fe2016-01-28 05:22:45 -0800544 receiveCodec.pltype = payloadType;
545 receiveCodec.plfreq = frequency;
546 receiveCodec.channels = channels;
547 receiveCodec.rate = rate;
548 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000549
kwiberg55b97fe2016-01-28 05:22:45 -0800550 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
551 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000552
kwiberg55b97fe2016-01-28 05:22:45 -0800553 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700554 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
555 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800556 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
557 "Channel::OnInitializeDecoder() invalid codec ("
558 "pt=%d, name=%s) received - 1",
559 payloadType, payloadName);
560 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
561 return -1;
562 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000563
kwiberg55b97fe2016-01-28 05:22:45 -0800564 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000565}
566
kwiberg55b97fe2016-01-28 05:22:45 -0800567int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
568 size_t payloadSize,
569 const WebRtcRTPHeader* rtpHeader) {
570 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
571 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
572 ","
573 " payloadType=%u, audioChannel=%" PRIuS ")",
574 payloadSize, rtpHeader->header.payloadType,
575 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000576
kwiberg55b97fe2016-01-28 05:22:45 -0800577 if (!channel_state_.Get().playing) {
578 // Avoid inserting into NetEQ when we are not playing. Count the
579 // packet as discarded.
580 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
581 "received packet is discarded since playing is not"
582 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000583 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800584 }
585
586 // Push the incoming payload (parsed and ready for decoding) into the ACM
587 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
588 0) {
589 _engineStatisticsPtr->SetLastError(
590 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
591 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
592 return -1;
593 }
594
kwiberg55b97fe2016-01-28 05:22:45 -0800595 int64_t round_trip_time = 0;
596 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
597 NULL);
598
599 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
600 if (!nack_list.empty()) {
601 // Can't use nack_list.data() since it's not supported by all
602 // compilers.
603 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
604 }
605 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000606}
607
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000608bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000609 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000610 RTPHeader header;
611 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
612 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
613 "IncomingPacket invalid RTP header");
614 return false;
615 }
616 header.payload_type_frequency =
617 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
618 if (header.payload_type_frequency < 0)
619 return false;
620 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
621}
622
henrik.lundin42dda502016-05-18 05:36:01 -0700623MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
624 int32_t id,
625 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700626 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800627 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700628 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800629 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700630 bool muted;
631 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
632 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800633 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
634 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
635 // In all likelihood, the audio in this frame is garbage. We return an
636 // error so that the audio mixer module doesn't add it to the mix. As
637 // a result, it won't be played out and the actions skipped here are
638 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700639 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800640 }
henrik.lundina89ab962016-05-18 08:52:45 -0700641
642 if (muted) {
643 // TODO(henrik.lundin): We should be able to do better than this. But we
644 // will have to go through all the cases below where the audio samples may
645 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800646 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700647 }
kwiberg55b97fe2016-01-28 05:22:45 -0800648
kwiberg55b97fe2016-01-28 05:22:45 -0800649 // Convert module ID to internal VoE channel ID
650 audioFrame->id_ = VoEChannelId(audioFrame->id_);
651 // Store speech type for dead-or-alive detection
652 _outputSpeechType = audioFrame->speech_type_;
653
kwiberg55b97fe2016-01-28 05:22:45 -0800654 {
655 // Pass the audio buffers to an optional sink callback, before applying
656 // scaling/panning, as that applies to the mix operation.
657 // External recipients of the audio (e.g. via AudioTrack), will do their
658 // own mixing/dynamic processing.
659 rtc::CritScope cs(&_callbackCritSect);
660 if (audio_sink_) {
661 AudioSinkInterface::Data data(
yujo36b1a5f2017-06-12 12:45:32 -0700662 audioFrame->data(), audioFrame->samples_per_channel_,
kwiberg55b97fe2016-01-28 05:22:45 -0800663 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
664 audioFrame->timestamp_);
665 audio_sink_->OnData(data);
666 }
667 }
668
669 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800670 {
671 rtc::CritScope cs(&volume_settings_critsect_);
672 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800673 }
674
675 // Output volume scaling
676 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800677 // TODO(solenberg): Combine with mute state - this can cause clicks!
oprypin67fdb802017-03-09 06:25:06 -0800678 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800679 }
680
kwiberg55b97fe2016-01-28 05:22:45 -0800681 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700682 // TODO(henrik.lundin) Use the |muted| information here too.
zstein3c451862017-07-20 09:57:42 -0700683 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
zsteine76bd3a2017-07-14 12:17:49 -0700684 // https://crbug.com/webrtc/7517).
zstein3c451862017-07-20 09:57:42 -0700685 _outputAudioLevel.ComputeLevel(*audioFrame, kAudioSampleDurationSeconds);
kwiberg55b97fe2016-01-28 05:22:45 -0800686
687 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
688 // The first frame with a valid rtp timestamp.
689 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
690 }
691
692 if (capture_start_rtp_time_stamp_ >= 0) {
693 // audioFrame.timestamp_ should be valid from now on.
694
695 // Compute elapsed time.
696 int64_t unwrap_timestamp =
697 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
698 audioFrame->elapsed_time_ms_ =
699 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700700 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800701
niklase@google.com470e71d2011-07-07 08:21:25 +0000702 {
kwiberg55b97fe2016-01-28 05:22:45 -0800703 rtc::CritScope lock(&ts_stats_lock_);
704 // Compute ntp time.
705 audioFrame->ntp_time_ms_ =
706 ntp_estimator_.Estimate(audioFrame->timestamp_);
707 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
708 if (audioFrame->ntp_time_ms_ > 0) {
709 // Compute |capture_start_ntp_time_ms_| so that
710 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
711 capture_start_ntp_time_ms_ =
712 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000713 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000714 }
kwiberg55b97fe2016-01-28 05:22:45 -0800715 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000716
henrik.lundin42dda502016-05-18 05:36:01 -0700717 return muted ? MixerParticipant::AudioFrameInfo::kMuted
718 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000719}
720
aleloi6c278492016-10-20 14:24:39 -0700721AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
722 int sample_rate_hz,
723 AudioFrame* audio_frame) {
724 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700725
aleloi6c278492016-10-20 14:24:39 -0700726 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700727
728 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
729 FrameInfo new_audio_frame_info = FrameInfo::kError;
730 switch (frame_info) {
731 case MixerParticipant::AudioFrameInfo::kNormal:
732 new_audio_frame_info = FrameInfo::kNormal;
733 break;
734 case MixerParticipant::AudioFrameInfo::kMuted:
735 new_audio_frame_info = FrameInfo::kMuted;
736 break;
737 case MixerParticipant::AudioFrameInfo::kError:
738 new_audio_frame_info = FrameInfo::kError;
739 break;
740 }
aleloi6c278492016-10-20 14:24:39 -0700741 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700742}
743
kwiberg55b97fe2016-01-28 05:22:45 -0800744int32_t Channel::NeededFrequency(int32_t id) const {
745 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
746 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000747
kwiberg55b97fe2016-01-28 05:22:45 -0800748 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000749
kwiberg55b97fe2016-01-28 05:22:45 -0800750 // Determine highest needed receive frequency
751 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000752
kwiberg55b97fe2016-01-28 05:22:45 -0800753 // Return the bigger of playout and receive frequency in the ACM.
754 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
755 highestNeeded = audio_coding_->PlayoutFrequency();
756 } else {
757 highestNeeded = receiveFrequency;
758 }
759
solenbergb63310a2017-09-18 03:04:12 -0700760 return highestNeeded;
niklase@google.com470e71d2011-07-07 08:21:25 +0000761}
762
henrikaec6fbd22017-03-31 05:43:36 -0700763int32_t Channel::CreateChannel(Channel*& channel,
764 int32_t channelId,
765 uint32_t instanceId,
766 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800767 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
768 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
769 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000770
solenberg88499ec2016-09-07 07:34:41 -0700771 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800772 if (channel == NULL) {
773 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
774 "Channel::CreateChannel() unable to allocate memory for"
775 " channel");
776 return -1;
777 }
778 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000779}
780
pbos@webrtc.org92135212013-05-14 08:31:39 +0000781Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000782 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700783 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800784 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100785 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700786 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800787 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100788 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800789 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100790 rtp_receive_statistics_(
791 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
792 rtp_receiver_(
793 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100794 this,
795 this,
796 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700797 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100798 _outputAudioLevel(),
799 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100800 _timeStamp(0), // This is just an offset, RTP module will add it's own
801 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100802 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100803 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100804 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100805 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100806 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
807 capture_start_rtp_time_stamp_(-1),
808 capture_start_ntp_time_ms_(-1),
809 _engineStatisticsPtr(NULL),
810 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100811 _moduleProcessThreadPtr(NULL),
812 _audioDeviceModulePtr(NULL),
813 _voiceEngineObserverPtr(NULL),
814 _callbackCritSectPtr(NULL),
815 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700816 input_mute_(false),
817 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100818 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100819 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800820 transport_overhead_per_packet_(0),
821 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100822 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100823 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100824 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700825 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800826 feedback_observer_proxy_(new TransportFeedbackProxy()),
827 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700828 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200829 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
830 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700831 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700832 use_twcc_plr_for_ana_(
833 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800834 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
835 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700836 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800837 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700838 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800839 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200840
kwiberg55b97fe2016-01-28 05:22:45 -0800841 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000842
kwiberg55b97fe2016-01-28 05:22:45 -0800843 RtpRtcp::Configuration configuration;
844 configuration.audio = true;
845 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800846 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800847 configuration.receive_statistics = rtp_receive_statistics_.get();
848 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800849 if (pacing_enabled_) {
850 configuration.paced_sender = rtp_packet_sender_proxy_.get();
851 configuration.transport_sequence_number_allocator =
852 seq_num_allocator_proxy_.get();
853 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
854 }
ivoc14d5dbe2016-07-04 07:06:55 -0700855 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800856 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200857 configuration.retransmission_rate_limiter =
858 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000859
kwiberg55b97fe2016-01-28 05:22:45 -0800860 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100861 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000862}
863
kwiberg55b97fe2016-01-28 05:22:45 -0800864Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700865 RTC_DCHECK(!channel_state_.Get().sending);
866 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000867}
868
kwiberg55b97fe2016-01-28 05:22:45 -0800869int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700870 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800871 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
872 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000873
kwiberg55b97fe2016-01-28 05:22:45 -0800874 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000875
kwiberg55b97fe2016-01-28 05:22:45 -0800876 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000877
kwiberg55b97fe2016-01-28 05:22:45 -0800878 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
879 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
880 "Channel::Init() must call SetEngineInformation() first");
881 return -1;
882 }
883
884 // --- Add modules to process thread (for periodic schedulation)
885
tommidea489f2017-03-03 03:20:24 -0800886 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800887
888 // --- ACM initialization
889
890 if (audio_coding_->InitializeReceiver() == -1) {
891 _engineStatisticsPtr->SetLastError(
892 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
893 "Channel::Init() unable to initialize the ACM - 1");
894 return -1;
895 }
896
897 // --- RTP/RTCP module initialization
898
899 // Ensure that RTCP is enabled by default for the created channel.
900 // Note that, the module will keep generating RTCP until it is explicitly
901 // disabled by the user.
902 // After StopListen (when no sockets exists), RTCP packets will no longer
903 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700904 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800905 // RTCP is enabled by default.
906 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
907 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800908 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800909 _engineStatisticsPtr->SetLastError(
910 VE_CANNOT_INIT_CHANNEL, kTraceError,
911 "Channel::Init() callbacks not registered");
912 return -1;
913 }
914
solenberg6dc20382017-09-18 05:22:39 -0700915 // TODO(solenberg): Remove?
kwiberg1c07c702017-03-27 07:15:49 -0700916 // Register a default set of send codecs.
917 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -0800918 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -0700919 CodecInst codec;
920 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
921
922 // Ensure that PCMU is used as default send codec.
923 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
924 SetSendCodec(codec);
925 }
926
927 // Register default PT for 'telephone-event'
928 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
929 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
930 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
931 "Channel::Init() failed to register outband "
932 "'telephone-event' (%d/%d) correctly",
933 codec.pltype, codec.plfreq);
934 }
935 }
936
937 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
938 if (!codec_manager_.RegisterEncoder(codec) ||
939 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
940 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
941 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
942 "Channel::Init() failed to register CN (%d/%d) "
943 "correctly - 1",
944 codec.pltype, codec.plfreq);
945 }
946 }
947 }
948
949 return 0;
950}
951
tommi0a2391f2017-03-21 02:31:51 -0700952void Channel::Terminate() {
953 RTC_DCHECK(construction_thread_.CalledOnValidThread());
954 // Must be called on the same thread as Init().
955 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
956 "Channel::Terminate");
957
958 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
959
960 StopSend();
961 StopPlayout();
962
tommi0a2391f2017-03-21 02:31:51 -0700963 // The order to safely shutdown modules in a channel is:
964 // 1. De-register callbacks in modules
965 // 2. De-register modules in process thread
966 // 3. Destroy modules
967 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
968 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
969 "Terminate() failed to de-register transport callback"
970 " (Audio coding module)");
971 }
972
973 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
974 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
975 "Terminate() failed to de-register VAD callback"
976 " (Audio coding module)");
977 }
978
979 // De-register modules in process thread
980 if (_moduleProcessThreadPtr)
981 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
982
983 // End of modules shutdown
984}
985
kwiberg55b97fe2016-01-28 05:22:45 -0800986int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
987 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -0800988 ProcessThread& moduleProcessThread,
989 AudioDeviceModule& audioDeviceModule,
990 VoiceEngineObserver* voiceEngineObserver,
henrikaec6fbd22017-03-31 05:43:36 -0700991 rtc::CriticalSection* callbackCritSect,
992 rtc::TaskQueue* encoder_queue) {
993 RTC_DCHECK(encoder_queue);
994 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800995 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
996 "Channel::SetEngineInformation()");
997 _engineStatisticsPtr = &engineStatistics;
998 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -0800999 _moduleProcessThreadPtr = &moduleProcessThread;
1000 _audioDeviceModulePtr = &audioDeviceModule;
1001 _voiceEngineObserverPtr = voiceEngineObserver;
1002 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -07001003 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -08001004 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001005}
1006
kwibergb7f89d62016-02-17 10:04:18 -08001007void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001008 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001009 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001010}
1011
ossu29b1a8d2016-06-13 07:34:51 -07001012const rtc::scoped_refptr<AudioDecoderFactory>&
1013Channel::GetAudioDecoderFactory() const {
1014 return decoder_factory_;
1015}
1016
kwiberg55b97fe2016-01-28 05:22:45 -08001017int32_t Channel::StartPlayout() {
1018 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1019 "Channel::StartPlayout()");
1020 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001021 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001022 }
1023
solenberge374e012017-02-14 04:55:00 -08001024 // Add participant as candidates for mixing.
1025 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1026 _engineStatisticsPtr->SetLastError(
1027 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1028 "StartPlayout() failed to add participant to mixer");
1029 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001030 }
1031
1032 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001033
1034 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001035}
1036
kwiberg55b97fe2016-01-28 05:22:45 -08001037int32_t Channel::StopPlayout() {
1038 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1039 "Channel::StopPlayout()");
1040 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001041 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001042 }
1043
solenberge374e012017-02-14 04:55:00 -08001044 // Remove participant as candidates for mixing
1045 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1046 _engineStatisticsPtr->SetLastError(
1047 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1048 "StopPlayout() failed to remove participant from mixer");
1049 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001050 }
1051
1052 channel_state_.SetPlaying(false);
1053 _outputAudioLevel.Clear();
1054
1055 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001056}
1057
kwiberg55b97fe2016-01-28 05:22:45 -08001058int32_t Channel::StartSend() {
1059 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1060 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001061 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001062 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001063 }
1064 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -07001065 {
1066 // It is now OK to start posting tasks to the encoder task queue.
1067 rtc::CritScope cs(&encoder_queue_lock_);
1068 encoder_queue_is_active_ = true;
1069 }
solenberg08b19df2017-02-15 00:42:31 -08001070 // Resume the previous sequence number which was reset by StopSend(). This
1071 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1072 if (send_sequence_number_) {
1073 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1074 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001075 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001076 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1077 _engineStatisticsPtr->SetLastError(
1078 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1079 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001080 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001081 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001082 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001083 return -1;
1084 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001085
kwiberg55b97fe2016-01-28 05:22:45 -08001086 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001087}
1088
henrikaec6fbd22017-03-31 05:43:36 -07001089void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -08001090 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1091 "Channel::StopSend()");
1092 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -07001093 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001094 }
1095 channel_state_.SetSending(false);
1096
henrikaec6fbd22017-03-31 05:43:36 -07001097 // Post a task to the encoder thread which sets an event when the task is
1098 // executed. We know that no more encoding tasks will be added to the task
1099 // queue for this channel since sending is now deactivated. It means that,
1100 // if we wait for the event to bet set, we know that no more pending tasks
1101 // exists and it is therfore guaranteed that the task queue will never try
1102 // to acccess and invalid channel object.
1103 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001104
henrikaec6fbd22017-03-31 05:43:36 -07001105 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001106 {
1107 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1108 // than this final "flush task" to be posted on the queue.
1109 rtc::CritScope cs(&encoder_queue_lock_);
1110 encoder_queue_is_active_ = false;
1111 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1112 }
henrikaec6fbd22017-03-31 05:43:36 -07001113 flush.Wait(rtc::Event::kForever);
1114
kwiberg55b97fe2016-01-28 05:22:45 -08001115 // Store the sequence number to be able to pick up the same sequence for
1116 // the next StartSend(). This is needed for restarting device, otherwise
1117 // it might cause libSRTP to complain about packets being replayed.
1118 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1119 // CL is landed. See issue
1120 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1121 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1122
1123 // Reset sending SSRC and sequence number and triggers direct transmission
1124 // of RTCP BYE
1125 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1126 _engineStatisticsPtr->SetLastError(
1127 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1128 "StartSend() RTP/RTCP failed to stop sending");
1129 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001130 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001131}
1132
ossu1ffbd6c2017-04-06 12:05:04 -07001133bool Channel::SetEncoder(int payload_type,
1134 std::unique_ptr<AudioEncoder> encoder) {
1135 RTC_DCHECK_GE(payload_type, 0);
1136 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001137 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1138 // one for for us to keep track of sample rate and number of channels, etc.
1139
1140 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1141 // as well as some other things, so we collect this info and send it along.
1142 CodecInst rtp_codec;
1143 rtp_codec.pltype = payload_type;
1144 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1145 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001146 // Seems unclear if it should be clock rate or sample rate. CodecInst
1147 // supposedly carries the sample rate, but only clock rate seems sensible to
1148 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001149 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1150 rtp_codec.pacsize = rtc::CheckedDivExact(
1151 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1152 100);
1153 rtp_codec.channels = encoder->NumChannels();
1154 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001155
ossu76d29f92017-06-09 07:30:13 -07001156 // For audio encoding we need, instead, the actual sample rate of the codec.
1157 // The rest of the information should be the same.
1158 CodecInst send_codec = rtp_codec;
1159 send_codec.plfreq = encoder->SampleRateHz();
1160 cached_send_codec_.emplace(send_codec);
1161
1162 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001163 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001164 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001165 WEBRTC_TRACE(
1166 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1167 "SetEncoder() failed to register codec to RTP/RTCP module");
1168 return false;
1169 }
1170 }
1171
1172 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001173 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001174 return true;
1175}
1176
ossu20a4b3f2017-04-27 02:08:52 -07001177void Channel::ModifyEncoder(
1178 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1179 audio_coding_->ModifyEncoder(modifier);
1180}
1181
kwiberg55b97fe2016-01-28 05:22:45 -08001182int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1183 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1184 "Channel::RegisterVoiceEngineObserver()");
1185 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001186
kwiberg55b97fe2016-01-28 05:22:45 -08001187 if (_voiceEngineObserverPtr) {
1188 _engineStatisticsPtr->SetLastError(
1189 VE_INVALID_OPERATION, kTraceError,
1190 "RegisterVoiceEngineObserver() observer already enabled");
1191 return -1;
1192 }
1193 _voiceEngineObserverPtr = &observer;
1194 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001195}
1196
kwiberg55b97fe2016-01-28 05:22:45 -08001197int32_t Channel::DeRegisterVoiceEngineObserver() {
1198 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1199 "Channel::DeRegisterVoiceEngineObserver()");
1200 rtc::CritScope cs(&_callbackCritSect);
1201
1202 if (!_voiceEngineObserverPtr) {
1203 _engineStatisticsPtr->SetLastError(
1204 VE_INVALID_OPERATION, kTraceWarning,
1205 "DeRegisterVoiceEngineObserver() observer already disabled");
1206 return 0;
1207 }
1208 _voiceEngineObserverPtr = NULL;
1209 return 0;
1210}
1211
1212int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001213 if (cached_send_codec_) {
1214 codec = *cached_send_codec_;
1215 return 0;
1216 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001217 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1218 if (send_codec) {
1219 codec = *send_codec;
1220 return 0;
1221 }
1222 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001223 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001224}
1225
kwiberg55b97fe2016-01-28 05:22:45 -08001226int32_t Channel::GetRecCodec(CodecInst& codec) {
1227 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001228}
1229
kwiberg55b97fe2016-01-28 05:22:45 -08001230int32_t Channel::SetSendCodec(const CodecInst& codec) {
1231 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1232 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001233
kwibergc8d071e2016-04-06 12:22:38 -07001234 if (!codec_manager_.RegisterEncoder(codec) ||
1235 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001236 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1237 "SetSendCodec() failed to register codec to ACM");
1238 return -1;
1239 }
1240
1241 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1242 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1243 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1244 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1245 "SetSendCodec() failed to register codec to"
1246 " RTP/RTCP module");
1247 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001248 }
kwiberg55b97fe2016-01-28 05:22:45 -08001249 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001250
ossu76d29f92017-06-09 07:30:13 -07001251 cached_send_codec_.reset();
1252
kwiberg55b97fe2016-01-28 05:22:45 -08001253 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001254}
1255
minyue78b4d562016-11-30 04:47:39 -08001256void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001257 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1258 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001259 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001260 if (*encoder) {
1261 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001262 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001263 }
1264 });
michaelt566d8202017-01-12 10:17:38 -08001265 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001266}
1267
elad.alond12a8e12017-03-23 11:04:48 -07001268void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1269 if (!use_twcc_plr_for_ana_)
1270 return;
minyue7e304322016-10-12 05:00:55 -07001271 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001272 if (*encoder) {
1273 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1274 }
1275 });
1276}
1277
elad.alondadb4dc2017-03-23 15:29:50 -07001278void Channel::OnRecoverableUplinkPacketLossRate(
1279 float recoverable_packet_loss_rate) {
1280 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1281 if (*encoder) {
1282 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1283 recoverable_packet_loss_rate);
1284 }
1285 });
1286}
1287
elad.alond12a8e12017-03-23 11:04:48 -07001288void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1289 if (use_twcc_plr_for_ana_)
1290 return;
1291 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1292 if (*encoder) {
1293 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1294 }
minyue7e304322016-10-12 05:00:55 -07001295 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001296}
1297
kwiberg1c07c702017-03-27 07:15:49 -07001298void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1299 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1300 audio_coding_->SetReceiveCodecs(codecs);
1301}
1302
minyue7e304322016-10-12 05:00:55 -07001303bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1304 bool success = false;
1305 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1306 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001307 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1308 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001309 }
1310 });
1311 return success;
1312}
1313
1314void Channel::DisableAudioNetworkAdaptor() {
1315 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1316 if (*encoder)
1317 (*encoder)->DisableAudioNetworkAdaptor();
1318 });
1319}
1320
1321void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1322 int max_frame_length_ms) {
1323 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1324 if (*encoder) {
1325 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1326 max_frame_length_ms);
1327 }
1328 });
1329}
1330
mflodman3d7db262016-04-29 00:57:13 -07001331int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001332 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001333 "Channel::RegisterExternalTransport()");
1334
kwiberg55b97fe2016-01-28 05:22:45 -08001335 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001336 if (_externalTransport) {
1337 _engineStatisticsPtr->SetLastError(
1338 VE_INVALID_OPERATION, kTraceError,
1339 "RegisterExternalTransport() external transport already enabled");
1340 return -1;
1341 }
1342 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001343 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001344 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001345}
1346
kwiberg55b97fe2016-01-28 05:22:45 -08001347int32_t Channel::DeRegisterExternalTransport() {
1348 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1349 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001350
kwiberg55b97fe2016-01-28 05:22:45 -08001351 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001352 if (_transportPtr) {
1353 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1354 "DeRegisterExternalTransport() all transport is disabled");
1355 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001356 _engineStatisticsPtr->SetLastError(
1357 VE_INVALID_OPERATION, kTraceWarning,
1358 "DeRegisterExternalTransport() external transport already "
1359 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001360 }
1361 _externalTransport = false;
1362 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001363 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001364}
1365
nisse657bab22017-02-21 06:28:10 -08001366// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1367// It's a temporary hack to support both ReceivedRTPPacket and
1368// OnRtpPacket interfaces without too much code duplication.
1369bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1370 size_t length,
1371 RTPHeader *header) {
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 return false;
1379 bool in_order = IsPacketInOrder(*header);
1380 rtp_receive_statistics_->IncomingPacket(
1381 *header, length, IsPacketRetransmitted(*header, in_order));
1382 rtp_payload_registry_->SetIncomingPayloadType(*header);
1383
1384 return ReceivePacket(received_packet, length, *header, in_order);
1385}
1386
mflodman3d7db262016-04-29 00:57:13 -07001387int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001388 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001389 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001390 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001391 "Channel::ReceivedRTPPacket()");
1392
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001393 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001394 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1395 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1396 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001397 return -1;
1398 }
nisse657bab22017-02-21 06:28:10 -08001399 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1400}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001401
nisse657bab22017-02-21 06:28:10 -08001402void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1403 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1404 "Channel::ReceivedRTPPacket()");
1405
1406 RTPHeader header;
1407 packet.GetHeader(&header);
1408 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001409}
1410
1411bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001412 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001413 const RTPHeader& header,
1414 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001415 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001416 assert(packet_length >= header.headerLength);
1417 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001418 PayloadUnion payload_specific;
1419 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001420 &payload_specific)) {
1421 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001422 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001423 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1424 payload_specific, in_order);
1425}
1426
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001427bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1428 StreamStatistician* statistician =
1429 rtp_receive_statistics_->GetStatistician(header.ssrc);
1430 if (!statistician)
1431 return false;
1432 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001433}
1434
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001435bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1436 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001437 StreamStatistician* statistician =
1438 rtp_receive_statistics_->GetStatistician(header.ssrc);
1439 if (!statistician)
1440 return false;
1441 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001442 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001443 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001444 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001445}
1446
mflodman3d7db262016-04-29 00:57:13 -07001447int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001448 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001449 "Channel::ReceivedRTCPPacket()");
1450 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001451 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001452
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001453 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001454 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001455
Minyue2013aec2015-05-13 14:14:42 +02001456 int64_t rtt = GetRTT(true);
1457 if (rtt == 0) {
1458 // Waiting for valid RTT.
1459 return 0;
1460 }
Erik Språng737336d2016-07-29 12:59:36 +02001461
1462 int64_t nack_window_ms = rtt;
1463 if (nack_window_ms < kMinRetransmissionWindowMs) {
1464 nack_window_ms = kMinRetransmissionWindowMs;
1465 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1466 nack_window_ms = kMaxRetransmissionWindowMs;
1467 }
1468 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1469
minyue7e304322016-10-12 05:00:55 -07001470 // Invoke audio encoders OnReceivedRtt().
1471 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1472 if (*encoder)
1473 (*encoder)->OnReceivedRtt(rtt);
1474 });
1475
Minyue2013aec2015-05-13 14:14:42 +02001476 uint32_t ntp_secs = 0;
1477 uint32_t ntp_frac = 0;
1478 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001479 if (0 !=
1480 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1481 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001482 // Waiting for RTCP.
1483 return 0;
1484 }
1485
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001486 {
tommi31fc21f2016-01-21 10:37:37 -08001487 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001488 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001489 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001490 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001491}
1492
solenberg8d73f8c2017-03-08 01:52:20 -08001493int Channel::GetSpeechOutputLevel() const {
1494 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001495}
1496
solenberg8d73f8c2017-03-08 01:52:20 -08001497int Channel::GetSpeechOutputLevelFullRange() const {
1498 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001499}
1500
zsteine76bd3a2017-07-14 12:17:49 -07001501double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001502 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001503}
1504
1505double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001506 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001507}
1508
solenberg8d73f8c2017-03-08 01:52:20 -08001509void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001510 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001511 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001512}
1513
solenberg1c2af8e2016-03-24 10:36:00 -07001514bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001515 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001516 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001517}
1518
solenberg8d73f8c2017-03-08 01:52:20 -08001519void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001520 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001521 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001522}
1523
solenberg8842c3e2016-03-11 03:06:41 -08001524int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001525 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001526 "Channel::SendTelephoneEventOutband(...)");
1527 RTC_DCHECK_LE(0, event);
1528 RTC_DCHECK_GE(255, event);
1529 RTC_DCHECK_LE(0, duration_ms);
1530 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001531 if (!Sending()) {
1532 return -1;
1533 }
solenberg8842c3e2016-03-11 03:06:41 -08001534 if (_rtpRtcpModule->SendTelephoneEventOutband(
1535 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001536 _engineStatisticsPtr->SetLastError(
1537 VE_SEND_DTMF_FAILED, kTraceWarning,
1538 "SendTelephoneEventOutband() failed to send event");
1539 return -1;
1540 }
1541 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001542}
1543
solenbergffbbcac2016-11-17 05:25:37 -08001544int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1545 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001546 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001547 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001548 RTC_DCHECK_LE(0, payload_type);
1549 RTC_DCHECK_GE(127, payload_type);
1550 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001551 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001552 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001553 memcpy(codec.plname, "telephone-event", 16);
1554 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1555 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1556 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1557 _engineStatisticsPtr->SetLastError(
1558 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1559 "SetSendTelephoneEventPayloadType() failed to register send"
1560 "payload type");
1561 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001562 }
kwiberg55b97fe2016-01-28 05:22:45 -08001563 }
kwiberg55b97fe2016-01-28 05:22:45 -08001564 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001565}
1566
kwiberg55b97fe2016-01-28 05:22:45 -08001567int Channel::SetLocalSSRC(unsigned int ssrc) {
1568 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1569 "Channel::SetLocalSSRC()");
1570 if (channel_state_.Get().sending) {
1571 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
1572 "SetLocalSSRC() already sending");
1573 return -1;
1574 }
1575 _rtpRtcpModule->SetSSRC(ssrc);
1576 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001577}
1578
kwiberg55b97fe2016-01-28 05:22:45 -08001579int Channel::GetLocalSSRC(unsigned int& ssrc) {
1580 ssrc = _rtpRtcpModule->SSRC();
1581 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001582}
1583
kwiberg55b97fe2016-01-28 05:22:45 -08001584int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1585 ssrc = rtp_receiver_->SSRC();
1586 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001587}
1588
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001589int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001590 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001591 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001592}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001593
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001594int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1595 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001596 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1597 if (enable &&
1598 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1599 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001600 return -1;
1601 }
1602 return 0;
1603}
1604
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001605void Channel::EnableSendTransportSequenceNumber(int id) {
1606 int ret =
1607 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1608 RTC_DCHECK_EQ(0, ret);
1609}
1610
stefan3313ec92016-01-21 06:32:43 -08001611void Channel::EnableReceiveTransportSequenceNumber(int id) {
1612 rtp_header_parser_->DeregisterRtpHeaderExtension(
1613 kRtpExtensionTransportSequenceNumber);
1614 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1615 kRtpExtensionTransportSequenceNumber, id);
1616 RTC_DCHECK(ret);
1617}
1618
stefanbba9dec2016-02-01 04:39:55 -08001619void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001620 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001621 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001622 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1623 TransportFeedbackObserver* transport_feedback_observer =
1624 transport->transport_feedback_observer();
1625 PacketRouter* packet_router = transport->packet_router();
1626
stefanbba9dec2016-02-01 04:39:55 -08001627 RTC_DCHECK(rtp_packet_sender);
1628 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001629 RTC_DCHECK(packet_router);
1630 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001631 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001632 feedback_observer_proxy_->SetTransportFeedbackObserver(
1633 transport_feedback_observer);
1634 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1635 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1636 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001637 constexpr bool remb_candidate = false;
1638 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001639 packet_router_ = packet_router;
1640}
1641
stefanbba9dec2016-02-01 04:39:55 -08001642void Channel::RegisterReceiverCongestionControlObjects(
1643 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001644 RTC_DCHECK(packet_router);
1645 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001646 constexpr bool remb_candidate = false;
1647 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001648 packet_router_ = packet_router;
1649}
1650
nissefdbfdc92017-03-31 05:44:52 -07001651void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001652 RTC_DCHECK(packet_router_);
1653 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001654 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001655 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1656 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001657 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001658 packet_router_ = nullptr;
1659 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1660}
1661
nissefdbfdc92017-03-31 05:44:52 -07001662void Channel::ResetReceiverCongestionControlObjects() {
1663 RTC_DCHECK(packet_router_);
1664 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1665 packet_router_ = nullptr;
1666}
1667
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001668void Channel::SetRTCPStatus(bool enable) {
1669 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1670 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001671 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001672}
1673
kwiberg55b97fe2016-01-28 05:22:45 -08001674int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07001675 RtcpMode method = _rtpRtcpModule->RTCP();
1676 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001677 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001678}
1679
kwiberg55b97fe2016-01-28 05:22:45 -08001680int Channel::SetRTCP_CNAME(const char cName[256]) {
1681 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1682 "Channel::SetRTCP_CNAME()");
1683 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
1684 _engineStatisticsPtr->SetLastError(
1685 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1686 "SetRTCP_CNAME() failed to set RTCP CNAME");
1687 return -1;
1688 }
1689 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001690}
1691
kwiberg55b97fe2016-01-28 05:22:45 -08001692int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
1693 if (cName == NULL) {
1694 _engineStatisticsPtr->SetLastError(
1695 VE_INVALID_ARGUMENT, kTraceError,
1696 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
1697 return -1;
1698 }
1699 char cname[RTCP_CNAME_SIZE];
1700 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
1701 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
1702 _engineStatisticsPtr->SetLastError(
1703 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
1704 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
1705 return -1;
1706 }
1707 strcpy(cName, cname);
1708 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001709}
1710
kwiberg55b97fe2016-01-28 05:22:45 -08001711int Channel::SendApplicationDefinedRTCPPacket(
1712 unsigned char subType,
1713 unsigned int name,
1714 const char* data,
1715 unsigned short dataLengthInBytes) {
1716 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1717 "Channel::SendApplicationDefinedRTCPPacket()");
1718 if (!channel_state_.Get().sending) {
1719 _engineStatisticsPtr->SetLastError(
1720 VE_NOT_SENDING, kTraceError,
1721 "SendApplicationDefinedRTCPPacket() not sending");
1722 return -1;
1723 }
1724 if (NULL == data) {
1725 _engineStatisticsPtr->SetLastError(
1726 VE_INVALID_ARGUMENT, kTraceError,
1727 "SendApplicationDefinedRTCPPacket() invalid data value");
1728 return -1;
1729 }
1730 if (dataLengthInBytes % 4 != 0) {
1731 _engineStatisticsPtr->SetLastError(
1732 VE_INVALID_ARGUMENT, kTraceError,
1733 "SendApplicationDefinedRTCPPacket() invalid length value");
1734 return -1;
1735 }
1736 RtcpMode status = _rtpRtcpModule->RTCP();
1737 if (status == RtcpMode::kOff) {
1738 _engineStatisticsPtr->SetLastError(
1739 VE_RTCP_ERROR, kTraceError,
1740 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
1741 return -1;
1742 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001743
kwiberg55b97fe2016-01-28 05:22:45 -08001744 // Create and schedule the RTCP APP packet for transmission
1745 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
1746 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
1747 _engineStatisticsPtr->SetLastError(
1748 VE_SEND_ERROR, kTraceError,
1749 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
1750 return -1;
1751 }
1752 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001753}
1754
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001755int Channel::GetRemoteRTCPReportBlocks(
1756 std::vector<ReportBlock>* report_blocks) {
1757 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08001758 _engineStatisticsPtr->SetLastError(
1759 VE_INVALID_ARGUMENT, kTraceError,
1760 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001761 return -1;
1762 }
1763
1764 // Get the report blocks from the latest received RTCP Sender or Receiver
1765 // Report. Each element in the vector contains the sender's SSRC and a
1766 // report block according to RFC 3550.
1767 std::vector<RTCPReportBlock> rtcp_report_blocks;
1768 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001769 return -1;
1770 }
1771
1772 if (rtcp_report_blocks.empty())
1773 return 0;
1774
1775 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
1776 for (; it != rtcp_report_blocks.end(); ++it) {
1777 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07001778 report_block.sender_SSRC = it->sender_ssrc;
1779 report_block.source_SSRC = it->source_ssrc;
1780 report_block.fraction_lost = it->fraction_lost;
1781 report_block.cumulative_num_packets_lost = it->packets_lost;
1782 report_block.extended_highest_sequence_number =
1783 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001784 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07001785 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
1786 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001787 report_blocks->push_back(report_block);
1788 }
1789 return 0;
1790}
1791
kwiberg55b97fe2016-01-28 05:22:45 -08001792int Channel::GetRTPStatistics(CallStatistics& stats) {
1793 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00001794
kwiberg55b97fe2016-01-28 05:22:45 -08001795 // The jitter statistics is updated for each received RTP packet and is
1796 // based on received packets.
1797 RtcpStatistics statistics;
1798 StreamStatistician* statistician =
1799 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01001800 if (statistician) {
1801 statistician->GetStatistics(&statistics,
1802 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001803 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001804
kwiberg55b97fe2016-01-28 05:22:45 -08001805 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07001806 stats.cumulativeLost = statistics.packets_lost;
1807 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08001808 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00001809
kwiberg55b97fe2016-01-28 05:22:45 -08001810 // --- RTT
1811 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001812
kwiberg55b97fe2016-01-28 05:22:45 -08001813 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00001814
kwiberg55b97fe2016-01-28 05:22:45 -08001815 size_t bytesSent(0);
1816 uint32_t packetsSent(0);
1817 size_t bytesReceived(0);
1818 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001819
kwiberg55b97fe2016-01-28 05:22:45 -08001820 if (statistician) {
1821 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
1822 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001823
kwiberg55b97fe2016-01-28 05:22:45 -08001824 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
1825 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1826 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
1827 " output will not be complete");
1828 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001829
kwiberg55b97fe2016-01-28 05:22:45 -08001830 stats.bytesSent = bytesSent;
1831 stats.packetsSent = packetsSent;
1832 stats.bytesReceived = bytesReceived;
1833 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00001834
kwiberg55b97fe2016-01-28 05:22:45 -08001835 // --- Timestamps
1836 {
1837 rtc::CritScope lock(&ts_stats_lock_);
1838 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
1839 }
1840 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001841}
1842
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001843void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
1844 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001845 // If pacing is enabled we always store packets.
1846 if (!pacing_enabled_)
1847 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001848 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001849 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001850 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001851 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00001852 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001853}
1854
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00001855// Called when we are missing one or more packets.
1856int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00001857 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
1858}
1859
henrikaec6fbd22017-03-31 05:43:36 -07001860void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07001861 // Avoid posting any new tasks if sending was already stopped in StopSend().
1862 rtc::CritScope cs(&encoder_queue_lock_);
1863 if (!encoder_queue_is_active_) {
1864 return;
1865 }
henrikaec6fbd22017-03-31 05:43:36 -07001866 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1867 // TODO(henrika): try to avoid copying by moving ownership of audio frame
1868 // either into pool of frames or into the task itself.
1869 audio_frame->CopyFrom(audio_input);
1870 audio_frame->id_ = ChannelId();
1871 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1872 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00001873}
1874
henrikaec6fbd22017-03-31 05:43:36 -07001875void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
1876 int sample_rate,
1877 size_t number_of_frames,
1878 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07001879 // Avoid posting as new task if sending was already stopped in StopSend().
1880 rtc::CritScope cs(&encoder_queue_lock_);
1881 if (!encoder_queue_is_active_) {
1882 return;
1883 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001884 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07001885 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07001886 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
1887 audio_frame->id_ = ChannelId();
ossu950c1c92017-07-11 08:19:31 -07001888 // TODO(ossu): Investigate how this could happen. b/62909493
1889 if (result == 0) {
1890 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
1891 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
1892 } else {
1893 audio_frame->sample_rate_hz_ = sample_rate;
1894 audio_frame->num_channels_ = number_of_channels;
1895 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
1896 RTC_NOTREACHED();
1897 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07001898 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07001899 sample_rate, &input_resampler_, audio_frame.get());
1900 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
1901 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00001902}
1903
henrikaec6fbd22017-03-31 05:43:36 -07001904void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
1905 RTC_DCHECK_RUN_ON(encoder_queue_);
1906 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
1907 RTC_DCHECK_LE(audio_input->num_channels_, 2);
1908 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08001909
henrikaec6fbd22017-03-31 05:43:36 -07001910 bool is_muted = InputMute();
1911 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08001912
kwiberg55b97fe2016-01-28 05:22:45 -08001913 if (_includeAudioLevelIndication) {
1914 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07001915 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001916 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07001917 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08001918 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08001919 } else {
henrik.lundin50499422016-11-29 04:26:24 -08001920 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07001921 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00001922 }
kwiberg55b97fe2016-01-28 05:22:45 -08001923 }
solenberg1c2af8e2016-03-24 10:36:00 -07001924 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00001925
henrikaec6fbd22017-03-31 05:43:36 -07001926 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00001927
kwiberg55b97fe2016-01-28 05:22:45 -08001928 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07001929 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08001930 // This call will trigger AudioPacketizationCallback::SendData if encoding
1931 // is done and payload is ready for packetization and transmission.
1932 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07001933 if (audio_coding_->Add10MsData(*audio_input) < 0) {
1934 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
1935 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001936 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001937
henrikaec6fbd22017-03-31 05:43:36 -07001938 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001939}
1940
solenberg7602aab2016-11-14 11:30:07 -08001941void Channel::set_associate_send_channel(const ChannelOwner& channel) {
1942 RTC_DCHECK(!channel.channel() ||
1943 channel.channel()->ChannelId() != _channelId);
1944 rtc::CritScope lock(&assoc_send_channel_lock_);
1945 associate_send_channel_ = channel;
1946}
1947
Minyue2013aec2015-05-13 14:14:42 +02001948void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08001949 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02001950 Channel* channel = associate_send_channel_.channel();
1951 if (channel && channel->ChannelId() == channel_id) {
1952 // If this channel is associated with a send channel of the specified
1953 // Channel ID, disassociate with it.
1954 ChannelOwner ref(NULL);
1955 associate_send_channel_ = ref;
1956 }
1957}
1958
ivoc14d5dbe2016-07-04 07:06:55 -07001959void Channel::SetRtcEventLog(RtcEventLog* event_log) {
1960 event_log_proxy_->SetEventLog(event_log);
1961}
1962
michaelt9332b7d2016-11-30 07:51:13 -08001963void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
1964 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
1965}
1966
nisse284542b2017-01-10 08:58:32 -08001967void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08001968 size_t overhead_per_packet =
1969 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08001970 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1971 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08001972 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08001973 }
1974 });
1975}
1976
1977void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001978 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001979 transport_overhead_per_packet_ = transport_overhead_per_packet;
1980 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08001981}
1982
hbos3fd31fe2017-02-28 05:43:16 -08001983// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08001984void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08001985 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08001986 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
1987 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08001988}
1989
kwiberg55b97fe2016-01-28 05:22:45 -08001990int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
1991 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00001992}
1993
wu@webrtc.org24301a62013-12-13 19:17:43 +00001994void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
1995 audio_coding_->GetDecodingCallStatistics(stats);
1996}
1997
ivoce1198e02017-09-08 08:13:19 -07001998ANAStats Channel::GetANAStatistics() const {
1999 return audio_coding_->GetANAStats();
2000}
2001
solenberg358057b2015-11-27 10:46:42 -08002002uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002003 rtc::CritScope lock(&video_sync_lock_);
2004 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002005}
2006
kwiberg55b97fe2016-01-28 05:22:45 -08002007int Channel::SetMinimumPlayoutDelay(int delayMs) {
2008 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2009 "Channel::SetMinimumPlayoutDelay()");
2010 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2011 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2012 _engineStatisticsPtr->SetLastError(
2013 VE_INVALID_ARGUMENT, kTraceError,
2014 "SetMinimumPlayoutDelay() invalid min delay");
2015 return -1;
2016 }
2017 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2018 _engineStatisticsPtr->SetLastError(
2019 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2020 "SetMinimumPlayoutDelay() failed to set min playout delay");
2021 return -1;
2022 }
2023 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002024}
2025
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002026int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002027 uint32_t playout_timestamp_rtp = 0;
2028 {
tommi31fc21f2016-01-21 10:37:37 -08002029 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002030 playout_timestamp_rtp = playout_timestamp_rtp_;
2031 }
kwiberg55b97fe2016-01-28 05:22:45 -08002032 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002033 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002034 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002035 "GetPlayoutTimestamp() failed to retrieve timestamp");
2036 return -1;
2037 }
deadbeef74375882015-08-13 12:09:10 -07002038 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002039 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002040}
2041
kwiberg55b97fe2016-01-28 05:22:45 -08002042int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2043 RtpReceiver** rtp_receiver) const {
2044 *rtpRtcpModule = _rtpRtcpModule.get();
2045 *rtp_receiver = rtp_receiver_.get();
2046 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002047}
2048
deadbeef74375882015-08-13 12:09:10 -07002049void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002050 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07002051
henrik.lundin96bd5022016-04-06 04:13:56 -07002052 if (!jitter_buffer_playout_timestamp_) {
2053 // This can happen if this channel has not received any RTP packets. In
2054 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07002055 return;
2056 }
2057
2058 uint16_t delay_ms = 0;
2059 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002060 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002061 "Channel::UpdatePlayoutTimestamp() failed to read playout"
2062 " delay from the ADM");
2063 _engineStatisticsPtr->SetLastError(
2064 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
2065 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
2066 return;
2067 }
2068
henrik.lundin96bd5022016-04-06 04:13:56 -07002069 RTC_DCHECK(jitter_buffer_playout_timestamp_);
2070 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07002071
2072 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07002073 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07002074
kwiberg55b97fe2016-01-28 05:22:45 -08002075 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002076 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07002077 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07002078
2079 {
tommi31fc21f2016-01-21 10:37:37 -08002080 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08002081 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002082 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07002083 }
2084 playout_delay_ms_ = delay_ms;
2085 }
2086}
2087
kwiberg55b97fe2016-01-28 05:22:45 -08002088void Channel::RegisterReceiveCodecsToRTPModule() {
2089 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2090 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002091
kwiberg55b97fe2016-01-28 05:22:45 -08002092 CodecInst codec;
2093 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00002094
kwiberg55b97fe2016-01-28 05:22:45 -08002095 for (int idx = 0; idx < nSupportedCodecs; idx++) {
2096 // Open up the RTP/RTCP receiver for all supported codecs
2097 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08002098 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08002099 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2100 "Channel::RegisterReceiveCodecsToRTPModule() unable"
2101 " to register %s (%d/%d/%" PRIuS
2102 "/%d) to RTP/RTCP "
2103 "receiver",
2104 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2105 codec.rate);
2106 } else {
2107 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2108 "Channel::RegisterReceiveCodecsToRTPModule() %s "
2109 "(%d/%d/%" PRIuS
2110 "/%d) has been added to the RTP/RTCP "
2111 "receiver",
2112 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2113 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00002114 }
kwiberg55b97fe2016-01-28 05:22:45 -08002115 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002116}
2117
kwiberg55b97fe2016-01-28 05:22:45 -08002118int Channel::SetSendRtpHeaderExtension(bool enable,
2119 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002120 unsigned char id) {
2121 int error = 0;
2122 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
2123 if (enable) {
2124 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
2125 }
2126 return error;
2127}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002128
ossue280cde2016-10-12 11:04:10 -07002129int Channel::GetRtpTimestampRateHz() const {
2130 const auto format = audio_coding_->ReceiveFormat();
2131 // Default to the playout frequency if we've not gotten any packets yet.
2132 // TODO(ossu): Zero clockrate can only happen if we've added an external
2133 // decoder for a format we don't support internally. Remove once that way of
2134 // adding decoders is gone!
2135 return (format && format->clockrate_hz != 0)
2136 ? format->clockrate_hz
2137 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00002138}
2139
Minyue2013aec2015-05-13 14:14:42 +02002140int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07002141 RtcpMode method = _rtpRtcpModule->RTCP();
2142 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002143 return 0;
2144 }
2145 std::vector<RTCPReportBlock> report_blocks;
2146 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02002147
2148 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002149 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02002150 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08002151 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002152 Channel* channel = associate_send_channel_.channel();
2153 // Tries to get RTT from an associated channel. This is important for
2154 // receive-only channels.
2155 if (channel) {
2156 // To prevent infinite recursion and deadlock, calling GetRTT of
2157 // associate channel should always use "false" for argument:
2158 // |allow_associate_channel|.
2159 rtt = channel->GetRTT(false);
2160 }
2161 }
2162 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002163 }
2164
2165 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2166 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
2167 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07002168 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002169 break;
2170 }
2171 if (it == report_blocks.end()) {
2172 // We have not received packets with SSRC matching the report blocks.
2173 // To calculate RTT we try with the SSRC of the first report block.
2174 // This is very important for send-only channels where we don't know
2175 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07002176 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002177 }
Minyue2013aec2015-05-13 14:14:42 +02002178
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002179 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002180 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002181 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002182 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
2183 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002184 return 0;
2185 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002186 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002187}
2188
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00002189} // namespace voe
2190} // namespace webrtc