blob: e5435d6bda52a8b556f265b971995d172b42931c [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
kwiberg1c07c702017-03-27 07:15:49 -0700915 // Register a default set of send codecs.
916 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -0800917 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -0700918 CodecInst codec;
919 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
920
921 // Ensure that PCMU is used as default send codec.
922 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
923 SetSendCodec(codec);
924 }
925
926 // Register default PT for 'telephone-event'
927 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
928 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
929 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
930 "Channel::Init() failed to register outband "
931 "'telephone-event' (%d/%d) correctly",
932 codec.pltype, codec.plfreq);
933 }
934 }
935
936 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
937 if (!codec_manager_.RegisterEncoder(codec) ||
938 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
939 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
940 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
941 "Channel::Init() failed to register CN (%d/%d) "
942 "correctly - 1",
943 codec.pltype, codec.plfreq);
944 }
945 }
946 }
947
948 return 0;
949}
950
951void Channel::RegisterLegacyReceiveCodecs() {
952 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
953 for (int idx = 0; idx < nSupportedCodecs; idx++) {
954 CodecInst codec;
955 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
956
kwiberg55b97fe2016-01-28 05:22:45 -0800957 // Open up the RTP/RTCP receiver for all supported codecs
kwiberg1c07c702017-03-27 07:15:49 -0700958 if (rtp_receiver_->RegisterReceivePayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800959 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
960 "Channel::Init() unable to register %s "
961 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
962 codec.plname, codec.pltype, codec.plfreq, codec.channels,
963 codec.rate);
964 } else {
965 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
966 "Channel::Init() %s (%d/%d/%" PRIuS
967 "/%d) has been "
968 "added to the RTP/RTCP receiver",
969 codec.plname, codec.pltype, codec.plfreq, codec.channels,
970 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000971 }
972
kwiberg1c07c702017-03-27 07:15:49 -0700973 // Register default PT for 'telephone-event'
974 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
975 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
kwibergda2bf4e2016-10-24 13:47:09 -0700976 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800977 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
kwiberg1c07c702017-03-27 07:15:49 -0700978 "Channel::Init() failed to register inband "
kwiberg55b97fe2016-01-28 05:22:45 -0800979 "'telephone-event' (%d/%d) correctly",
980 codec.pltype, codec.plfreq);
981 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000982 }
983
kwiberg1c07c702017-03-27 07:15:49 -0700984 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
985 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
986 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800987 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
988 "Channel::Init() failed to register CN (%d/%d) "
989 "correctly - 1",
990 codec.pltype, codec.plfreq);
991 }
992 }
kwiberg55b97fe2016-01-28 05:22:45 -0800993 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000994}
995
tommi0a2391f2017-03-21 02:31:51 -0700996void Channel::Terminate() {
997 RTC_DCHECK(construction_thread_.CalledOnValidThread());
998 // Must be called on the same thread as Init().
999 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1000 "Channel::Terminate");
1001
1002 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1003
1004 StopSend();
1005 StopPlayout();
1006
tommi0a2391f2017-03-21 02:31:51 -07001007 // The order to safely shutdown modules in a channel is:
1008 // 1. De-register callbacks in modules
1009 // 2. De-register modules in process thread
1010 // 3. Destroy modules
1011 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1012 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1013 "Terminate() failed to de-register transport callback"
1014 " (Audio coding module)");
1015 }
1016
1017 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1018 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1019 "Terminate() failed to de-register VAD callback"
1020 " (Audio coding module)");
1021 }
1022
1023 // De-register modules in process thread
1024 if (_moduleProcessThreadPtr)
1025 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1026
1027 // End of modules shutdown
1028}
1029
kwiberg55b97fe2016-01-28 05:22:45 -08001030int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1031 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001032 ProcessThread& moduleProcessThread,
1033 AudioDeviceModule& audioDeviceModule,
1034 VoiceEngineObserver* voiceEngineObserver,
henrikaec6fbd22017-03-31 05:43:36 -07001035 rtc::CriticalSection* callbackCritSect,
1036 rtc::TaskQueue* encoder_queue) {
1037 RTC_DCHECK(encoder_queue);
1038 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -08001039 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1040 "Channel::SetEngineInformation()");
1041 _engineStatisticsPtr = &engineStatistics;
1042 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001043 _moduleProcessThreadPtr = &moduleProcessThread;
1044 _audioDeviceModulePtr = &audioDeviceModule;
1045 _voiceEngineObserverPtr = voiceEngineObserver;
1046 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -07001047 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -08001048 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001049}
1050
kwibergb7f89d62016-02-17 10:04:18 -08001051void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001052 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001053 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001054}
1055
ossu29b1a8d2016-06-13 07:34:51 -07001056const rtc::scoped_refptr<AudioDecoderFactory>&
1057Channel::GetAudioDecoderFactory() const {
1058 return decoder_factory_;
1059}
1060
kwiberg55b97fe2016-01-28 05:22:45 -08001061int32_t Channel::StartPlayout() {
1062 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1063 "Channel::StartPlayout()");
1064 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001065 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001066 }
1067
solenberge374e012017-02-14 04:55:00 -08001068 // Add participant as candidates for mixing.
1069 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1070 _engineStatisticsPtr->SetLastError(
1071 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1072 "StartPlayout() failed to add participant to mixer");
1073 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001074 }
1075
1076 channel_state_.SetPlaying(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001077
1078 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001079}
1080
kwiberg55b97fe2016-01-28 05:22:45 -08001081int32_t Channel::StopPlayout() {
1082 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1083 "Channel::StopPlayout()");
1084 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001085 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001086 }
1087
solenberge374e012017-02-14 04:55:00 -08001088 // Remove participant as candidates for mixing
1089 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1090 _engineStatisticsPtr->SetLastError(
1091 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1092 "StopPlayout() failed to remove participant from mixer");
1093 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001094 }
1095
1096 channel_state_.SetPlaying(false);
1097 _outputAudioLevel.Clear();
1098
1099 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001100}
1101
kwiberg55b97fe2016-01-28 05:22:45 -08001102int32_t Channel::StartSend() {
1103 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1104 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001105 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001106 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001107 }
1108 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -07001109 {
1110 // It is now OK to start posting tasks to the encoder task queue.
1111 rtc::CritScope cs(&encoder_queue_lock_);
1112 encoder_queue_is_active_ = true;
1113 }
solenberg08b19df2017-02-15 00:42:31 -08001114 // Resume the previous sequence number which was reset by StopSend(). This
1115 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1116 if (send_sequence_number_) {
1117 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1118 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001119 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001120 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1121 _engineStatisticsPtr->SetLastError(
1122 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1123 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001124 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001125 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001126 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001127 return -1;
1128 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001129
kwiberg55b97fe2016-01-28 05:22:45 -08001130 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001131}
1132
henrikaec6fbd22017-03-31 05:43:36 -07001133void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -08001134 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1135 "Channel::StopSend()");
1136 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -07001137 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001138 }
1139 channel_state_.SetSending(false);
1140
henrikaec6fbd22017-03-31 05:43:36 -07001141 // Post a task to the encoder thread which sets an event when the task is
1142 // executed. We know that no more encoding tasks will be added to the task
1143 // queue for this channel since sending is now deactivated. It means that,
1144 // if we wait for the event to bet set, we know that no more pending tasks
1145 // exists and it is therfore guaranteed that the task queue will never try
1146 // to acccess and invalid channel object.
1147 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001148
henrikaec6fbd22017-03-31 05:43:36 -07001149 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001150 {
1151 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1152 // than this final "flush task" to be posted on the queue.
1153 rtc::CritScope cs(&encoder_queue_lock_);
1154 encoder_queue_is_active_ = false;
1155 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1156 }
henrikaec6fbd22017-03-31 05:43:36 -07001157 flush.Wait(rtc::Event::kForever);
1158
kwiberg55b97fe2016-01-28 05:22:45 -08001159 // Store the sequence number to be able to pick up the same sequence for
1160 // the next StartSend(). This is needed for restarting device, otherwise
1161 // it might cause libSRTP to complain about packets being replayed.
1162 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1163 // CL is landed. See issue
1164 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1165 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1166
1167 // Reset sending SSRC and sequence number and triggers direct transmission
1168 // of RTCP BYE
1169 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1170 _engineStatisticsPtr->SetLastError(
1171 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1172 "StartSend() RTP/RTCP failed to stop sending");
1173 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001174 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001175}
1176
ossu1ffbd6c2017-04-06 12:05:04 -07001177bool Channel::SetEncoder(int payload_type,
1178 std::unique_ptr<AudioEncoder> encoder) {
1179 RTC_DCHECK_GE(payload_type, 0);
1180 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001181 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1182 // one for for us to keep track of sample rate and number of channels, etc.
1183
1184 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1185 // as well as some other things, so we collect this info and send it along.
1186 CodecInst rtp_codec;
1187 rtp_codec.pltype = payload_type;
1188 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1189 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001190 // Seems unclear if it should be clock rate or sample rate. CodecInst
1191 // supposedly carries the sample rate, but only clock rate seems sensible to
1192 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001193 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1194 rtp_codec.pacsize = rtc::CheckedDivExact(
1195 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1196 100);
1197 rtp_codec.channels = encoder->NumChannels();
1198 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001199
ossu76d29f92017-06-09 07:30:13 -07001200 // For audio encoding we need, instead, the actual sample rate of the codec.
1201 // The rest of the information should be the same.
1202 CodecInst send_codec = rtp_codec;
1203 send_codec.plfreq = encoder->SampleRateHz();
1204 cached_send_codec_.emplace(send_codec);
1205
1206 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001207 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001208 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001209 WEBRTC_TRACE(
1210 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1211 "SetEncoder() failed to register codec to RTP/RTCP module");
1212 return false;
1213 }
1214 }
1215
1216 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001217 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001218 return true;
1219}
1220
ossu20a4b3f2017-04-27 02:08:52 -07001221void Channel::ModifyEncoder(
1222 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1223 audio_coding_->ModifyEncoder(modifier);
1224}
1225
kwiberg55b97fe2016-01-28 05:22:45 -08001226int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1227 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1228 "Channel::RegisterVoiceEngineObserver()");
1229 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001230
kwiberg55b97fe2016-01-28 05:22:45 -08001231 if (_voiceEngineObserverPtr) {
1232 _engineStatisticsPtr->SetLastError(
1233 VE_INVALID_OPERATION, kTraceError,
1234 "RegisterVoiceEngineObserver() observer already enabled");
1235 return -1;
1236 }
1237 _voiceEngineObserverPtr = &observer;
1238 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001239}
1240
kwiberg55b97fe2016-01-28 05:22:45 -08001241int32_t Channel::DeRegisterVoiceEngineObserver() {
1242 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1243 "Channel::DeRegisterVoiceEngineObserver()");
1244 rtc::CritScope cs(&_callbackCritSect);
1245
1246 if (!_voiceEngineObserverPtr) {
1247 _engineStatisticsPtr->SetLastError(
1248 VE_INVALID_OPERATION, kTraceWarning,
1249 "DeRegisterVoiceEngineObserver() observer already disabled");
1250 return 0;
1251 }
1252 _voiceEngineObserverPtr = NULL;
1253 return 0;
1254}
1255
1256int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001257 if (cached_send_codec_) {
1258 codec = *cached_send_codec_;
1259 return 0;
1260 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001261 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1262 if (send_codec) {
1263 codec = *send_codec;
1264 return 0;
1265 }
1266 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001267 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001268}
1269
kwiberg55b97fe2016-01-28 05:22:45 -08001270int32_t Channel::GetRecCodec(CodecInst& codec) {
1271 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001272}
1273
kwiberg55b97fe2016-01-28 05:22:45 -08001274int32_t Channel::SetSendCodec(const CodecInst& codec) {
1275 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1276 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001277
kwibergc8d071e2016-04-06 12:22:38 -07001278 if (!codec_manager_.RegisterEncoder(codec) ||
1279 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001280 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1281 "SetSendCodec() failed to register codec to ACM");
1282 return -1;
1283 }
1284
1285 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1286 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1287 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1288 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1289 "SetSendCodec() failed to register codec to"
1290 " RTP/RTCP module");
1291 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001292 }
kwiberg55b97fe2016-01-28 05:22:45 -08001293 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001294
ossu76d29f92017-06-09 07:30:13 -07001295 cached_send_codec_.reset();
1296
kwiberg55b97fe2016-01-28 05:22:45 -08001297 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001298}
1299
minyue78b4d562016-11-30 04:47:39 -08001300void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001301 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1302 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001303 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001304 if (*encoder) {
1305 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001306 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001307 }
1308 });
michaelt566d8202017-01-12 10:17:38 -08001309 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001310}
1311
elad.alond12a8e12017-03-23 11:04:48 -07001312void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1313 if (!use_twcc_plr_for_ana_)
1314 return;
minyue7e304322016-10-12 05:00:55 -07001315 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001316 if (*encoder) {
1317 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1318 }
1319 });
1320}
1321
elad.alondadb4dc2017-03-23 15:29:50 -07001322void Channel::OnRecoverableUplinkPacketLossRate(
1323 float recoverable_packet_loss_rate) {
1324 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1325 if (*encoder) {
1326 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1327 recoverable_packet_loss_rate);
1328 }
1329 });
1330}
1331
elad.alond12a8e12017-03-23 11:04:48 -07001332void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1333 if (use_twcc_plr_for_ana_)
1334 return;
1335 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1336 if (*encoder) {
1337 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1338 }
minyue7e304322016-10-12 05:00:55 -07001339 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001340}
1341
kwiberg55b97fe2016-01-28 05:22:45 -08001342int32_t Channel::SetVADStatus(bool enableVAD,
1343 ACMVADMode mode,
1344 bool disableDTX) {
1345 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1346 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001347 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1348 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1349 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001350 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1351 kTraceError,
1352 "SetVADStatus() failed to set VAD");
1353 return -1;
1354 }
1355 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001356}
1357
kwiberg55b97fe2016-01-28 05:22:45 -08001358int32_t Channel::GetVADStatus(bool& enabledVAD,
1359 ACMVADMode& mode,
1360 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001361 const auto* params = codec_manager_.GetStackParams();
1362 enabledVAD = params->use_cng;
1363 mode = params->vad_mode;
1364 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001365 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001366}
1367
kwiberg1c07c702017-03-27 07:15:49 -07001368void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1369 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1370 audio_coding_->SetReceiveCodecs(codecs);
1371}
1372
kwiberg55b97fe2016-01-28 05:22:45 -08001373int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001374 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1375}
1376
1377int32_t Channel::SetRecPayloadType(int payload_type,
1378 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001379 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1380 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001381
kwiberg55b97fe2016-01-28 05:22:45 -08001382 if (channel_state_.Get().playing) {
1383 _engineStatisticsPtr->SetLastError(
1384 VE_ALREADY_PLAYING, kTraceError,
1385 "SetRecPayloadType() unable to set PT while playing");
1386 return -1;
1387 }
kwiberg55b97fe2016-01-28 05:22:45 -08001388
kwiberg09f090c2017-03-01 01:57:11 -08001389 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001390
1391 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001392 // De-register the selected codec (RTP/RTCP module and ACM)
1393
1394 int8_t pltype(-1);
1395 CodecInst rxCodec = codec;
1396
1397 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001398 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001399 rxCodec.pltype = pltype;
1400
1401 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1402 _engineStatisticsPtr->SetLastError(
1403 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1404 "SetRecPayloadType() RTP/RTCP-module deregistration "
1405 "failed");
1406 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001407 }
kwiberg55b97fe2016-01-28 05:22:45 -08001408 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1409 _engineStatisticsPtr->SetLastError(
1410 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1411 "SetRecPayloadType() ACM deregistration failed - 1");
1412 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001413 }
kwiberg55b97fe2016-01-28 05:22:45 -08001414 return 0;
1415 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001416
magjed56124bd2016-11-24 09:34:46 -08001417 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001418 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001419 // TODO(kwiberg): Retrying is probably not necessary, since
1420 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001421 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001422 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001423 _engineStatisticsPtr->SetLastError(
1424 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1425 "SetRecPayloadType() RTP/RTCP-module registration failed");
1426 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001427 }
kwiberg55b97fe2016-01-28 05:22:45 -08001428 }
kwibergd32bf752017-01-19 07:03:59 -08001429 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1430 audio_coding_->UnregisterReceiveCodec(payload_type);
1431 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001432 _engineStatisticsPtr->SetLastError(
1433 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1434 "SetRecPayloadType() ACM registration failed - 1");
1435 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001436 }
kwiberg55b97fe2016-01-28 05:22:45 -08001437 }
1438 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001439}
1440
kwiberg55b97fe2016-01-28 05:22:45 -08001441int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1442 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001443 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001444 _engineStatisticsPtr->SetLastError(
1445 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1446 "GetRecPayloadType() failed to retrieve RX payload type");
1447 return -1;
1448 }
1449 codec.pltype = payloadType;
1450 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001451}
1452
kwiberg55b97fe2016-01-28 05:22:45 -08001453int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1454 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1455 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001456
kwiberg55b97fe2016-01-28 05:22:45 -08001457 CodecInst codec;
1458 int32_t samplingFreqHz(-1);
1459 const size_t kMono = 1;
1460 if (frequency == kFreq32000Hz)
1461 samplingFreqHz = 32000;
1462 else if (frequency == kFreq16000Hz)
1463 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001464
kwiberg55b97fe2016-01-28 05:22:45 -08001465 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1466 _engineStatisticsPtr->SetLastError(
1467 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1468 "SetSendCNPayloadType() failed to retrieve default CN codec "
1469 "settings");
1470 return -1;
1471 }
1472
1473 // Modify the payload type (must be set to dynamic range)
1474 codec.pltype = type;
1475
kwibergc8d071e2016-04-06 12:22:38 -07001476 if (!codec_manager_.RegisterEncoder(codec) ||
1477 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001478 _engineStatisticsPtr->SetLastError(
1479 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1480 "SetSendCNPayloadType() failed to register CN to ACM");
1481 return -1;
1482 }
1483
1484 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1485 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1486 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1487 _engineStatisticsPtr->SetLastError(
1488 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1489 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1490 "module");
1491 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001492 }
kwiberg55b97fe2016-01-28 05:22:45 -08001493 }
1494 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001495}
1496
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001497int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001498 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001499 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001500
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001501 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001502 _engineStatisticsPtr->SetLastError(
1503 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001504 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001505 return -1;
1506 }
1507 return 0;
1508}
1509
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001510int Channel::SetOpusDtx(bool enable_dtx) {
1511 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1512 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001513 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001514 : audio_coding_->DisableOpusDtx();
1515 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001516 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1517 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001518 return -1;
1519 }
1520 return 0;
1521}
1522
ivoc85228d62016-07-27 04:53:47 -07001523int Channel::GetOpusDtx(bool* enabled) {
1524 int success = -1;
1525 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1526 if (encoder) {
1527 *enabled = encoder->GetDtx();
1528 success = 0;
1529 }
1530 });
1531 return success;
1532}
1533
minyue7e304322016-10-12 05:00:55 -07001534bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1535 bool success = false;
1536 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1537 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001538 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1539 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001540 }
1541 });
1542 return success;
1543}
1544
1545void Channel::DisableAudioNetworkAdaptor() {
1546 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1547 if (*encoder)
1548 (*encoder)->DisableAudioNetworkAdaptor();
1549 });
1550}
1551
1552void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1553 int max_frame_length_ms) {
1554 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1555 if (*encoder) {
1556 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1557 max_frame_length_ms);
1558 }
1559 });
1560}
1561
mflodman3d7db262016-04-29 00:57:13 -07001562int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001563 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001564 "Channel::RegisterExternalTransport()");
1565
kwiberg55b97fe2016-01-28 05:22:45 -08001566 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001567 if (_externalTransport) {
1568 _engineStatisticsPtr->SetLastError(
1569 VE_INVALID_OPERATION, kTraceError,
1570 "RegisterExternalTransport() external transport already enabled");
1571 return -1;
1572 }
1573 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001574 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001575 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001576}
1577
kwiberg55b97fe2016-01-28 05:22:45 -08001578int32_t Channel::DeRegisterExternalTransport() {
1579 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1580 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001581
kwiberg55b97fe2016-01-28 05:22:45 -08001582 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001583 if (_transportPtr) {
1584 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1585 "DeRegisterExternalTransport() all transport is disabled");
1586 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001587 _engineStatisticsPtr->SetLastError(
1588 VE_INVALID_OPERATION, kTraceWarning,
1589 "DeRegisterExternalTransport() external transport already "
1590 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001591 }
1592 _externalTransport = false;
1593 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001594 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001595}
1596
nisse657bab22017-02-21 06:28:10 -08001597// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1598// It's a temporary hack to support both ReceivedRTPPacket and
1599// OnRtpPacket interfaces without too much code duplication.
1600bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1601 size_t length,
1602 RTPHeader *header) {
1603 // Store playout timestamp for the received RTP packet
1604 UpdatePlayoutTimestamp(false);
1605
1606 header->payload_type_frequency =
1607 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1608 if (header->payload_type_frequency < 0)
1609 return false;
1610 bool in_order = IsPacketInOrder(*header);
1611 rtp_receive_statistics_->IncomingPacket(
1612 *header, length, IsPacketRetransmitted(*header, in_order));
1613 rtp_payload_registry_->SetIncomingPayloadType(*header);
1614
1615 return ReceivePacket(received_packet, length, *header, in_order);
1616}
1617
mflodman3d7db262016-04-29 00:57:13 -07001618int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001619 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001620 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001621 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001622 "Channel::ReceivedRTPPacket()");
1623
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001624 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001625 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1626 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1627 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001628 return -1;
1629 }
nisse657bab22017-02-21 06:28:10 -08001630 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1631}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001632
nisse657bab22017-02-21 06:28:10 -08001633void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1634 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1635 "Channel::ReceivedRTPPacket()");
1636
1637 RTPHeader header;
1638 packet.GetHeader(&header);
1639 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001640}
1641
1642bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001643 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001644 const RTPHeader& header,
1645 bool in_order) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001646 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001647 assert(packet_length >= header.headerLength);
1648 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001649 PayloadUnion payload_specific;
1650 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001651 &payload_specific)) {
1652 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001653 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001654 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1655 payload_specific, in_order);
1656}
1657
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001658bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1659 StreamStatistician* statistician =
1660 rtp_receive_statistics_->GetStatistician(header.ssrc);
1661 if (!statistician)
1662 return false;
1663 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001664}
1665
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001666bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1667 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001668 StreamStatistician* statistician =
1669 rtp_receive_statistics_->GetStatistician(header.ssrc);
1670 if (!statistician)
1671 return false;
1672 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001673 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001674 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001675 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001676}
1677
mflodman3d7db262016-04-29 00:57:13 -07001678int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001679 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001680 "Channel::ReceivedRTCPPacket()");
1681 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001682 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001683
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001684 // Deliver RTCP packet to RTP/RTCP module for parsing
nisse479d3d72017-09-13 07:53:37 -07001685 _rtpRtcpModule->IncomingRtcpPacket(data, length);
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001686
Minyue2013aec2015-05-13 14:14:42 +02001687 int64_t rtt = GetRTT(true);
1688 if (rtt == 0) {
1689 // Waiting for valid RTT.
1690 return 0;
1691 }
Erik Språng737336d2016-07-29 12:59:36 +02001692
1693 int64_t nack_window_ms = rtt;
1694 if (nack_window_ms < kMinRetransmissionWindowMs) {
1695 nack_window_ms = kMinRetransmissionWindowMs;
1696 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1697 nack_window_ms = kMaxRetransmissionWindowMs;
1698 }
1699 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1700
minyue7e304322016-10-12 05:00:55 -07001701 // Invoke audio encoders OnReceivedRtt().
1702 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1703 if (*encoder)
1704 (*encoder)->OnReceivedRtt(rtt);
1705 });
1706
Minyue2013aec2015-05-13 14:14:42 +02001707 uint32_t ntp_secs = 0;
1708 uint32_t ntp_frac = 0;
1709 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001710 if (0 !=
1711 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1712 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001713 // Waiting for RTCP.
1714 return 0;
1715 }
1716
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001717 {
tommi31fc21f2016-01-21 10:37:37 -08001718 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001719 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001720 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001721 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001722}
1723
solenberg8d73f8c2017-03-08 01:52:20 -08001724int Channel::GetSpeechOutputLevel() const {
1725 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00001726}
1727
solenberg8d73f8c2017-03-08 01:52:20 -08001728int Channel::GetSpeechOutputLevelFullRange() const {
1729 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08001730}
1731
zsteine76bd3a2017-07-14 12:17:49 -07001732double Channel::GetTotalOutputEnergy() const {
zstein3c451862017-07-20 09:57:42 -07001733 return _outputAudioLevel.TotalEnergy();
zsteine76bd3a2017-07-14 12:17:49 -07001734}
1735
1736double Channel::GetTotalOutputDuration() const {
zstein3c451862017-07-20 09:57:42 -07001737 return _outputAudioLevel.TotalDuration();
zsteine76bd3a2017-07-14 12:17:49 -07001738}
1739
solenberg8d73f8c2017-03-08 01:52:20 -08001740void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08001741 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001742 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00001743}
1744
solenberg1c2af8e2016-03-24 10:36:00 -07001745bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08001746 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07001747 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00001748}
1749
solenberg8d73f8c2017-03-08 01:52:20 -08001750void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08001751 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08001752 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00001753}
1754
solenberg8842c3e2016-03-11 03:06:41 -08001755int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08001756 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08001757 "Channel::SendTelephoneEventOutband(...)");
1758 RTC_DCHECK_LE(0, event);
1759 RTC_DCHECK_GE(255, event);
1760 RTC_DCHECK_LE(0, duration_ms);
1761 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08001762 if (!Sending()) {
1763 return -1;
1764 }
solenberg8842c3e2016-03-11 03:06:41 -08001765 if (_rtpRtcpModule->SendTelephoneEventOutband(
1766 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001767 _engineStatisticsPtr->SetLastError(
1768 VE_SEND_DTMF_FAILED, kTraceWarning,
1769 "SendTelephoneEventOutband() failed to send event");
1770 return -1;
1771 }
1772 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001773}
1774
solenbergffbbcac2016-11-17 05:25:37 -08001775int Channel::SetSendTelephoneEventPayloadType(int payload_type,
1776 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08001777 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001778 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07001779 RTC_DCHECK_LE(0, payload_type);
1780 RTC_DCHECK_GE(127, payload_type);
1781 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07001782 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08001783 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08001784 memcpy(codec.plname, "telephone-event", 16);
1785 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1786 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1787 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1788 _engineStatisticsPtr->SetLastError(
1789 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1790 "SetSendTelephoneEventPayloadType() failed to register send"
1791 "payload type");
1792 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001793 }
kwiberg55b97fe2016-01-28 05:22:45 -08001794 }
kwiberg55b97fe2016-01-28 05:22:45 -08001795 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001796}
1797
kwiberg55b97fe2016-01-28 05:22:45 -08001798int Channel::SetLocalSSRC(unsigned int ssrc) {
1799 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1800 "Channel::SetLocalSSRC()");
1801 if (channel_state_.Get().sending) {
1802 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
1803 "SetLocalSSRC() already sending");
1804 return -1;
1805 }
1806 _rtpRtcpModule->SetSSRC(ssrc);
1807 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001808}
1809
kwiberg55b97fe2016-01-28 05:22:45 -08001810int Channel::GetLocalSSRC(unsigned int& ssrc) {
1811 ssrc = _rtpRtcpModule->SSRC();
1812 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001813}
1814
kwiberg55b97fe2016-01-28 05:22:45 -08001815int Channel::GetRemoteSSRC(unsigned int& ssrc) {
1816 ssrc = rtp_receiver_->SSRC();
1817 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001818}
1819
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001820int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001821 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00001822 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00001823}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00001824
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001825int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
1826 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08001827 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1828 if (enable &&
1829 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
1830 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00001831 return -1;
1832 }
1833 return 0;
1834}
1835
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001836void Channel::EnableSendTransportSequenceNumber(int id) {
1837 int ret =
1838 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
1839 RTC_DCHECK_EQ(0, ret);
1840}
1841
stefan3313ec92016-01-21 06:32:43 -08001842void Channel::EnableReceiveTransportSequenceNumber(int id) {
1843 rtp_header_parser_->DeregisterRtpHeaderExtension(
1844 kRtpExtensionTransportSequenceNumber);
1845 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
1846 kRtpExtensionTransportSequenceNumber, id);
1847 RTC_DCHECK(ret);
1848}
1849
stefanbba9dec2016-02-01 04:39:55 -08001850void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07001851 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08001852 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07001853 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
1854 TransportFeedbackObserver* transport_feedback_observer =
1855 transport->transport_feedback_observer();
1856 PacketRouter* packet_router = transport->packet_router();
1857
stefanbba9dec2016-02-01 04:39:55 -08001858 RTC_DCHECK(rtp_packet_sender);
1859 RTC_DCHECK(transport_feedback_observer);
kwibergee89e782017-08-09 17:22:01 -07001860 RTC_DCHECK(packet_router);
1861 RTC_DCHECK(!packet_router_);
stefan7de8d642017-02-07 07:14:08 -08001862 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08001863 feedback_observer_proxy_->SetTransportFeedbackObserver(
1864 transport_feedback_observer);
1865 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
1866 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
1867 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
eladalon822ff2b2017-08-01 06:30:28 -07001868 constexpr bool remb_candidate = false;
1869 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
Stefan Holmerb86d4e42015-12-07 10:26:18 +01001870 packet_router_ = packet_router;
1871}
1872
stefanbba9dec2016-02-01 04:39:55 -08001873void Channel::RegisterReceiverCongestionControlObjects(
1874 PacketRouter* packet_router) {
kwibergee89e782017-08-09 17:22:01 -07001875 RTC_DCHECK(packet_router);
1876 RTC_DCHECK(!packet_router_);
eladalon822ff2b2017-08-01 06:30:28 -07001877 constexpr bool remb_candidate = false;
1878 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
stefanbba9dec2016-02-01 04:39:55 -08001879 packet_router_ = packet_router;
1880}
1881
nissefdbfdc92017-03-31 05:44:52 -07001882void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08001883 RTC_DCHECK(packet_router_);
1884 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08001885 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08001886 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
1887 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07001888 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08001889 packet_router_ = nullptr;
1890 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
1891}
1892
nissefdbfdc92017-03-31 05:44:52 -07001893void Channel::ResetReceiverCongestionControlObjects() {
1894 RTC_DCHECK(packet_router_);
1895 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
1896 packet_router_ = nullptr;
1897}
1898
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00001899void Channel::SetRTCPStatus(bool enable) {
1900 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1901 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07001902 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00001903}
1904
kwiberg55b97fe2016-01-28 05:22:45 -08001905int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07001906 RtcpMode method = _rtpRtcpModule->RTCP();
1907 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08001908 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001909}
1910
kwiberg55b97fe2016-01-28 05:22:45 -08001911int Channel::SetRTCP_CNAME(const char cName[256]) {
1912 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1913 "Channel::SetRTCP_CNAME()");
1914 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
1915 _engineStatisticsPtr->SetLastError(
1916 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1917 "SetRTCP_CNAME() failed to set RTCP CNAME");
1918 return -1;
1919 }
1920 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001921}
1922
kwiberg55b97fe2016-01-28 05:22:45 -08001923int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
1924 if (cName == NULL) {
1925 _engineStatisticsPtr->SetLastError(
1926 VE_INVALID_ARGUMENT, kTraceError,
1927 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
1928 return -1;
1929 }
1930 char cname[RTCP_CNAME_SIZE];
1931 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
1932 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
1933 _engineStatisticsPtr->SetLastError(
1934 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
1935 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
1936 return -1;
1937 }
1938 strcpy(cName, cname);
1939 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001940}
1941
kwiberg55b97fe2016-01-28 05:22:45 -08001942int Channel::SendApplicationDefinedRTCPPacket(
1943 unsigned char subType,
1944 unsigned int name,
1945 const char* data,
1946 unsigned short dataLengthInBytes) {
1947 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1948 "Channel::SendApplicationDefinedRTCPPacket()");
1949 if (!channel_state_.Get().sending) {
1950 _engineStatisticsPtr->SetLastError(
1951 VE_NOT_SENDING, kTraceError,
1952 "SendApplicationDefinedRTCPPacket() not sending");
1953 return -1;
1954 }
1955 if (NULL == data) {
1956 _engineStatisticsPtr->SetLastError(
1957 VE_INVALID_ARGUMENT, kTraceError,
1958 "SendApplicationDefinedRTCPPacket() invalid data value");
1959 return -1;
1960 }
1961 if (dataLengthInBytes % 4 != 0) {
1962 _engineStatisticsPtr->SetLastError(
1963 VE_INVALID_ARGUMENT, kTraceError,
1964 "SendApplicationDefinedRTCPPacket() invalid length value");
1965 return -1;
1966 }
1967 RtcpMode status = _rtpRtcpModule->RTCP();
1968 if (status == RtcpMode::kOff) {
1969 _engineStatisticsPtr->SetLastError(
1970 VE_RTCP_ERROR, kTraceError,
1971 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
1972 return -1;
1973 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001974
kwiberg55b97fe2016-01-28 05:22:45 -08001975 // Create and schedule the RTCP APP packet for transmission
1976 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
1977 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
1978 _engineStatisticsPtr->SetLastError(
1979 VE_SEND_ERROR, kTraceError,
1980 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
1981 return -1;
1982 }
1983 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001984}
1985
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001986int Channel::GetRemoteRTCPReportBlocks(
1987 std::vector<ReportBlock>* report_blocks) {
1988 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08001989 _engineStatisticsPtr->SetLastError(
1990 VE_INVALID_ARGUMENT, kTraceError,
1991 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00001992 return -1;
1993 }
1994
1995 // Get the report blocks from the latest received RTCP Sender or Receiver
1996 // Report. Each element in the vector contains the sender's SSRC and a
1997 // report block according to RFC 3550.
1998 std::vector<RTCPReportBlock> rtcp_report_blocks;
1999 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002000 return -1;
2001 }
2002
2003 if (rtcp_report_blocks.empty())
2004 return 0;
2005
2006 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2007 for (; it != rtcp_report_blocks.end(); ++it) {
2008 ReportBlock report_block;
srte3e69e5c2017-08-09 06:13:45 -07002009 report_block.sender_SSRC = it->sender_ssrc;
2010 report_block.source_SSRC = it->source_ssrc;
2011 report_block.fraction_lost = it->fraction_lost;
2012 report_block.cumulative_num_packets_lost = it->packets_lost;
2013 report_block.extended_highest_sequence_number =
2014 it->extended_highest_sequence_number;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002015 report_block.interarrival_jitter = it->jitter;
srte3e69e5c2017-08-09 06:13:45 -07002016 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
2017 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002018 report_blocks->push_back(report_block);
2019 }
2020 return 0;
2021}
2022
kwiberg55b97fe2016-01-28 05:22:45 -08002023int Channel::GetRTPStatistics(CallStatistics& stats) {
2024 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002025
kwiberg55b97fe2016-01-28 05:22:45 -08002026 // The jitter statistics is updated for each received RTP packet and is
2027 // based on received packets.
2028 RtcpStatistics statistics;
2029 StreamStatistician* statistician =
2030 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002031 if (statistician) {
2032 statistician->GetStatistics(&statistics,
2033 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002034 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002035
kwiberg55b97fe2016-01-28 05:22:45 -08002036 stats.fractionLost = statistics.fraction_lost;
srte186d9c32017-08-04 05:03:53 -07002037 stats.cumulativeLost = statistics.packets_lost;
2038 stats.extendedMax = statistics.extended_highest_sequence_number;
kwiberg55b97fe2016-01-28 05:22:45 -08002039 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002040
kwiberg55b97fe2016-01-28 05:22:45 -08002041 // --- RTT
2042 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002043
kwiberg55b97fe2016-01-28 05:22:45 -08002044 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002045
kwiberg55b97fe2016-01-28 05:22:45 -08002046 size_t bytesSent(0);
2047 uint32_t packetsSent(0);
2048 size_t bytesReceived(0);
2049 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002050
kwiberg55b97fe2016-01-28 05:22:45 -08002051 if (statistician) {
2052 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2053 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002054
kwiberg55b97fe2016-01-28 05:22:45 -08002055 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2056 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2057 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2058 " output will not be complete");
2059 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002060
kwiberg55b97fe2016-01-28 05:22:45 -08002061 stats.bytesSent = bytesSent;
2062 stats.packetsSent = packetsSent;
2063 stats.bytesReceived = bytesReceived;
2064 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002065
kwiberg55b97fe2016-01-28 05:22:45 -08002066 // --- Timestamps
2067 {
2068 rtc::CritScope lock(&ts_stats_lock_);
2069 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2070 }
2071 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002072}
2073
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002074int Channel::SetCodecFECStatus(bool enable) {
2075 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2076 "Channel::SetCodecFECStatus()");
2077
kwibergc8d071e2016-04-06 12:22:38 -07002078 if (!codec_manager_.SetCodecFEC(enable) ||
2079 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002080 _engineStatisticsPtr->SetLastError(
2081 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2082 "SetCodecFECStatus() failed to set FEC state");
2083 return -1;
2084 }
2085 return 0;
2086}
2087
2088bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002089 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002090}
2091
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002092void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2093 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002094 // If pacing is enabled we always store packets.
2095 if (!pacing_enabled_)
2096 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002097 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002098 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002099 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002100 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002101 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002102}
2103
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002104// Called when we are missing one or more packets.
2105int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002106 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2107}
2108
henrikaec6fbd22017-03-31 05:43:36 -07002109void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07002110 // Avoid posting any new tasks if sending was already stopped in StopSend().
2111 rtc::CritScope cs(&encoder_queue_lock_);
2112 if (!encoder_queue_is_active_) {
2113 return;
2114 }
henrikaec6fbd22017-03-31 05:43:36 -07002115 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2116 // TODO(henrika): try to avoid copying by moving ownership of audio frame
2117 // either into pool of frames or into the task itself.
2118 audio_frame->CopyFrom(audio_input);
2119 audio_frame->id_ = ChannelId();
2120 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2121 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00002122}
2123
henrikaec6fbd22017-03-31 05:43:36 -07002124void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
2125 int sample_rate,
2126 size_t number_of_frames,
2127 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07002128 // Avoid posting as new task if sending was already stopped in StopSend().
2129 rtc::CritScope cs(&encoder_queue_lock_);
2130 if (!encoder_queue_is_active_) {
2131 return;
2132 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002133 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07002134 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07002135 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2136 audio_frame->id_ = ChannelId();
ossu950c1c92017-07-11 08:19:31 -07002137 // TODO(ossu): Investigate how this could happen. b/62909493
2138 if (result == 0) {
2139 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2140 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
2141 } else {
2142 audio_frame->sample_rate_hz_ = sample_rate;
2143 audio_frame->num_channels_ = number_of_channels;
2144 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
2145 RTC_NOTREACHED();
2146 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002147 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07002148 sample_rate, &input_resampler_, audio_frame.get());
2149 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2150 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002151}
2152
henrikaec6fbd22017-03-31 05:43:36 -07002153void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
2154 RTC_DCHECK_RUN_ON(encoder_queue_);
2155 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
2156 RTC_DCHECK_LE(audio_input->num_channels_, 2);
2157 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08002158
henrikaec6fbd22017-03-31 05:43:36 -07002159 bool is_muted = InputMute();
2160 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002161
kwiberg55b97fe2016-01-28 05:22:45 -08002162 if (_includeAudioLevelIndication) {
2163 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07002164 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07002165 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07002166 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002167 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002168 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002169 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07002170 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002171 }
kwiberg55b97fe2016-01-28 05:22:45 -08002172 }
solenberg1c2af8e2016-03-24 10:36:00 -07002173 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002174
henrikaec6fbd22017-03-31 05:43:36 -07002175 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002176
kwiberg55b97fe2016-01-28 05:22:45 -08002177 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07002178 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08002179 // This call will trigger AudioPacketizationCallback::SendData if encoding
2180 // is done and payload is ready for packetization and transmission.
2181 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07002182 if (audio_coding_->Add10MsData(*audio_input) < 0) {
2183 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
2184 return;
kwiberg55b97fe2016-01-28 05:22:45 -08002185 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002186
henrikaec6fbd22017-03-31 05:43:36 -07002187 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00002188}
2189
solenberg7602aab2016-11-14 11:30:07 -08002190void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2191 RTC_DCHECK(!channel.channel() ||
2192 channel.channel()->ChannelId() != _channelId);
2193 rtc::CritScope lock(&assoc_send_channel_lock_);
2194 associate_send_channel_ = channel;
2195}
2196
Minyue2013aec2015-05-13 14:14:42 +02002197void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002198 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002199 Channel* channel = associate_send_channel_.channel();
2200 if (channel && channel->ChannelId() == channel_id) {
2201 // If this channel is associated with a send channel of the specified
2202 // Channel ID, disassociate with it.
2203 ChannelOwner ref(NULL);
2204 associate_send_channel_ = ref;
2205 }
2206}
2207
ivoc14d5dbe2016-07-04 07:06:55 -07002208void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2209 event_log_proxy_->SetEventLog(event_log);
2210}
2211
michaelt9332b7d2016-11-30 07:51:13 -08002212void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2213 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2214}
2215
nisse284542b2017-01-10 08:58:32 -08002216void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002217 size_t overhead_per_packet =
2218 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002219 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2220 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002221 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002222 }
2223 });
2224}
2225
2226void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002227 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002228 transport_overhead_per_packet_ = transport_overhead_per_packet;
2229 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002230}
2231
hbos3fd31fe2017-02-28 05:43:16 -08002232// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002233void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002234 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002235 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2236 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002237}
2238
kwiberg55b97fe2016-01-28 05:22:45 -08002239int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2240 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002241}
2242
wu@webrtc.org24301a62013-12-13 19:17:43 +00002243void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2244 audio_coding_->GetDecodingCallStatistics(stats);
2245}
2246
ivoce1198e02017-09-08 08:13:19 -07002247ANAStats Channel::GetANAStatistics() const {
2248 return audio_coding_->GetANAStats();
2249}
2250
solenberg358057b2015-11-27 10:46:42 -08002251uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002252 rtc::CritScope lock(&video_sync_lock_);
2253 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002254}
2255
kwiberg55b97fe2016-01-28 05:22:45 -08002256int Channel::SetMinimumPlayoutDelay(int delayMs) {
2257 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2258 "Channel::SetMinimumPlayoutDelay()");
2259 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2260 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2261 _engineStatisticsPtr->SetLastError(
2262 VE_INVALID_ARGUMENT, kTraceError,
2263 "SetMinimumPlayoutDelay() invalid min delay");
2264 return -1;
2265 }
2266 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2267 _engineStatisticsPtr->SetLastError(
2268 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2269 "SetMinimumPlayoutDelay() failed to set min playout delay");
2270 return -1;
2271 }
2272 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002273}
2274
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002275int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002276 uint32_t playout_timestamp_rtp = 0;
2277 {
tommi31fc21f2016-01-21 10:37:37 -08002278 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002279 playout_timestamp_rtp = playout_timestamp_rtp_;
2280 }
kwiberg55b97fe2016-01-28 05:22:45 -08002281 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002282 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002283 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002284 "GetPlayoutTimestamp() failed to retrieve timestamp");
2285 return -1;
2286 }
deadbeef74375882015-08-13 12:09:10 -07002287 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002288 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002289}
2290
kwiberg55b97fe2016-01-28 05:22:45 -08002291int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2292 RtpReceiver** rtp_receiver) const {
2293 *rtpRtcpModule = _rtpRtcpModule.get();
2294 *rtp_receiver = rtp_receiver_.get();
2295 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002296}
2297
deadbeef74375882015-08-13 12:09:10 -07002298void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002299 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07002300
henrik.lundin96bd5022016-04-06 04:13:56 -07002301 if (!jitter_buffer_playout_timestamp_) {
2302 // This can happen if this channel has not received any RTP packets. In
2303 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07002304 return;
2305 }
2306
2307 uint16_t delay_ms = 0;
2308 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002309 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002310 "Channel::UpdatePlayoutTimestamp() failed to read playout"
2311 " delay from the ADM");
2312 _engineStatisticsPtr->SetLastError(
2313 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
2314 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
2315 return;
2316 }
2317
henrik.lundin96bd5022016-04-06 04:13:56 -07002318 RTC_DCHECK(jitter_buffer_playout_timestamp_);
2319 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07002320
2321 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07002322 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07002323
kwiberg55b97fe2016-01-28 05:22:45 -08002324 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002325 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07002326 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07002327
2328 {
tommi31fc21f2016-01-21 10:37:37 -08002329 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08002330 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002331 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07002332 }
2333 playout_delay_ms_ = delay_ms;
2334 }
2335}
2336
kwiberg55b97fe2016-01-28 05:22:45 -08002337void Channel::RegisterReceiveCodecsToRTPModule() {
2338 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2339 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002340
kwiberg55b97fe2016-01-28 05:22:45 -08002341 CodecInst codec;
2342 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00002343
kwiberg55b97fe2016-01-28 05:22:45 -08002344 for (int idx = 0; idx < nSupportedCodecs; idx++) {
2345 // Open up the RTP/RTCP receiver for all supported codecs
2346 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08002347 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08002348 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2349 "Channel::RegisterReceiveCodecsToRTPModule() unable"
2350 " to register %s (%d/%d/%" PRIuS
2351 "/%d) to RTP/RTCP "
2352 "receiver",
2353 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2354 codec.rate);
2355 } else {
2356 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2357 "Channel::RegisterReceiveCodecsToRTPModule() %s "
2358 "(%d/%d/%" PRIuS
2359 "/%d) has been added to the RTP/RTCP "
2360 "receiver",
2361 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2362 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00002363 }
kwiberg55b97fe2016-01-28 05:22:45 -08002364 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002365}
2366
kwiberg55b97fe2016-01-28 05:22:45 -08002367int Channel::SetSendRtpHeaderExtension(bool enable,
2368 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002369 unsigned char id) {
2370 int error = 0;
2371 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
2372 if (enable) {
2373 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
2374 }
2375 return error;
2376}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002377
ossue280cde2016-10-12 11:04:10 -07002378int Channel::GetRtpTimestampRateHz() const {
2379 const auto format = audio_coding_->ReceiveFormat();
2380 // Default to the playout frequency if we've not gotten any packets yet.
2381 // TODO(ossu): Zero clockrate can only happen if we've added an external
2382 // decoder for a format we don't support internally. Remove once that way of
2383 // adding decoders is gone!
2384 return (format && format->clockrate_hz != 0)
2385 ? format->clockrate_hz
2386 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00002387}
2388
Minyue2013aec2015-05-13 14:14:42 +02002389int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07002390 RtcpMode method = _rtpRtcpModule->RTCP();
2391 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002392 return 0;
2393 }
2394 std::vector<RTCPReportBlock> report_blocks;
2395 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02002396
2397 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002398 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02002399 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08002400 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002401 Channel* channel = associate_send_channel_.channel();
2402 // Tries to get RTT from an associated channel. This is important for
2403 // receive-only channels.
2404 if (channel) {
2405 // To prevent infinite recursion and deadlock, calling GetRTT of
2406 // associate channel should always use "false" for argument:
2407 // |allow_associate_channel|.
2408 rtt = channel->GetRTT(false);
2409 }
2410 }
2411 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002412 }
2413
2414 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2415 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
2416 for (; it != report_blocks.end(); ++it) {
srte3e69e5c2017-08-09 06:13:45 -07002417 if (it->sender_ssrc == remoteSSRC)
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002418 break;
2419 }
2420 if (it == report_blocks.end()) {
2421 // We have not received packets with SSRC matching the report blocks.
2422 // To calculate RTT we try with the SSRC of the first report block.
2423 // This is very important for send-only channels where we don't know
2424 // the SSRC of the other end.
srte3e69e5c2017-08-09 06:13:45 -07002425 remoteSSRC = report_blocks[0].sender_ssrc;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002426 }
Minyue2013aec2015-05-13 14:14:42 +02002427
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002428 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002429 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002430 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002431 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
2432 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002433 return 0;
2434 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00002435 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002436}
2437
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00002438} // namespace voe
2439} // namespace webrtc