blob: 29ee30195d2979f38a701fcd07d1ecea4aa4f78c [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
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000011#include "webrtc/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
Ivo Creusenae856f22015-09-17 16:30:16 +020016#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080017#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000018#include "webrtc/base/format_macros.h"
pbosad856222015-11-27 09:48:36 -080019#include "webrtc/base/logging.h"
Erik Språng737336d2016-07-29 12:59:36 +020020#include "webrtc/base/rate_limiter.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010021#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000022#include "webrtc/base/timeutils.h"
ivoc14d5dbe2016-07-04 07:06:55 -070023#include "webrtc/call/rtc_event_log.h"
minyue@webrtc.orge509f942013-09-12 17:03:00 +000024#include "webrtc/common.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020025#include "webrtc/config.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000026#include "webrtc/modules/audio_device/include/audio_device.h"
27#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010028#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010029#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010030#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
31#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
32#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000033#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010034#include "webrtc/modules/utility/include/audio_frame_operations.h"
35#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010036#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000037#include "webrtc/voice_engine/include/voe_base.h"
38#include "webrtc/voice_engine/include/voe_external_media.h"
39#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
40#include "webrtc/voice_engine/output_mixer.h"
41#include "webrtc/voice_engine/statistics.h"
42#include "webrtc/voice_engine/transmit_mixer.h"
43#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000044
andrew@webrtc.org50419b02012-11-14 19:07:54 +000045namespace webrtc {
46namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000047
kwibergc8d071e2016-04-06 12:22:38 -070048namespace {
49
Erik Språng737336d2016-07-29 12:59:36 +020050constexpr int64_t kMaxRetransmissionWindowMs = 1000;
51constexpr int64_t kMinRetransmissionWindowMs = 30;
52
kwibergc8d071e2016-04-06 12:22:38 -070053bool RegisterReceiveCodec(std::unique_ptr<AudioCodingModule>* acm,
54 acm2::RentACodec* rac,
55 const CodecInst& ci) {
kwibergabe95ba2016-06-02 02:58:59 -070056 const int result = (*acm)->RegisterReceiveCodec(
57 ci, [&] { return rac->RentIsacDecoder(ci.plfreq); });
kwibergc8d071e2016-04-06 12:22:38 -070058 return result == 0;
59}
60
61} // namespace
62
solenberg8842c3e2016-03-11 03:06:41 -080063const int kTelephoneEventAttenuationdB = 10;
64
ivoc14d5dbe2016-07-04 07:06:55 -070065class RtcEventLogProxy final : public webrtc::RtcEventLog {
66 public:
67 RtcEventLogProxy() : event_log_(nullptr) {}
68
69 bool StartLogging(const std::string& file_name,
70 int64_t max_size_bytes) override {
71 RTC_NOTREACHED();
72 return false;
73 }
74
75 bool StartLogging(rtc::PlatformFile log_file,
76 int64_t max_size_bytes) override {
77 RTC_NOTREACHED();
78 return false;
79 }
80
81 void StopLogging() override { RTC_NOTREACHED(); }
82
83 void LogVideoReceiveStreamConfig(
84 const webrtc::VideoReceiveStream::Config& config) override {
85 rtc::CritScope lock(&crit_);
86 if (event_log_) {
87 event_log_->LogVideoReceiveStreamConfig(config);
88 }
89 }
90
91 void LogVideoSendStreamConfig(
92 const webrtc::VideoSendStream::Config& config) override {
93 rtc::CritScope lock(&crit_);
94 if (event_log_) {
95 event_log_->LogVideoSendStreamConfig(config);
96 }
97 }
98
99 void LogRtpHeader(webrtc::PacketDirection direction,
100 webrtc::MediaType media_type,
101 const uint8_t* header,
102 size_t packet_length) override {
103 rtc::CritScope lock(&crit_);
104 if (event_log_) {
105 event_log_->LogRtpHeader(direction, media_type, header, packet_length);
106 }
107 }
108
109 void LogRtcpPacket(webrtc::PacketDirection direction,
110 webrtc::MediaType media_type,
111 const uint8_t* packet,
112 size_t length) override {
113 rtc::CritScope lock(&crit_);
114 if (event_log_) {
115 event_log_->LogRtcpPacket(direction, media_type, packet, length);
116 }
117 }
118
119 void LogAudioPlayout(uint32_t ssrc) override {
120 rtc::CritScope lock(&crit_);
121 if (event_log_) {
122 event_log_->LogAudioPlayout(ssrc);
123 }
124 }
125
126 void LogBwePacketLossEvent(int32_t bitrate,
127 uint8_t fraction_loss,
128 int32_t total_packets) override {
129 rtc::CritScope lock(&crit_);
130 if (event_log_) {
131 event_log_->LogBwePacketLossEvent(bitrate, fraction_loss, total_packets);
132 }
133 }
134
135 void SetEventLog(RtcEventLog* event_log) {
136 rtc::CritScope lock(&crit_);
137 event_log_ = event_log;
138 }
139
140 private:
141 rtc::CriticalSection crit_;
142 RtcEventLog* event_log_ GUARDED_BY(crit_);
143 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
144};
145
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100146class TransportFeedbackProxy : public TransportFeedbackObserver {
147 public:
148 TransportFeedbackProxy() : feedback_observer_(nullptr) {
149 pacer_thread_.DetachFromThread();
150 network_thread_.DetachFromThread();
151 }
152
153 void SetTransportFeedbackObserver(
154 TransportFeedbackObserver* feedback_observer) {
155 RTC_DCHECK(thread_checker_.CalledOnValidThread());
156 rtc::CritScope lock(&crit_);
157 feedback_observer_ = feedback_observer;
158 }
159
160 // Implements TransportFeedbackObserver.
161 void AddPacket(uint16_t sequence_number,
162 size_t length,
philipela1ed0b32016-06-01 06:31:17 -0700163 int probe_cluster_id) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100164 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
165 rtc::CritScope lock(&crit_);
166 if (feedback_observer_)
pbos2169d8b2016-06-20 11:53:02 -0700167 feedback_observer_->AddPacket(sequence_number, length, probe_cluster_id);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100168 }
169 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
170 RTC_DCHECK(network_thread_.CalledOnValidThread());
171 rtc::CritScope lock(&crit_);
Stefan Holmer60e43462016-09-07 09:58:20 +0200172 feedback_observer_->OnTransportFeedback(feedback);
173 }
174 std::vector<PacketInfo> GetTransportFeedbackVector() const override {
175 RTC_NOTREACHED();
176 return std::vector<PacketInfo>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100177 }
178
179 private:
180 rtc::CriticalSection crit_;
181 rtc::ThreadChecker thread_checker_;
182 rtc::ThreadChecker pacer_thread_;
183 rtc::ThreadChecker network_thread_;
184 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
185};
186
187class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
188 public:
189 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
190 pacer_thread_.DetachFromThread();
191 }
192
193 void SetSequenceNumberAllocator(
194 TransportSequenceNumberAllocator* seq_num_allocator) {
195 RTC_DCHECK(thread_checker_.CalledOnValidThread());
196 rtc::CritScope lock(&crit_);
197 seq_num_allocator_ = seq_num_allocator;
198 }
199
200 // Implements TransportSequenceNumberAllocator.
201 uint16_t AllocateSequenceNumber() override {
202 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
203 rtc::CritScope lock(&crit_);
204 if (!seq_num_allocator_)
205 return 0;
206 return seq_num_allocator_->AllocateSequenceNumber();
207 }
208
209 private:
210 rtc::CriticalSection crit_;
211 rtc::ThreadChecker thread_checker_;
212 rtc::ThreadChecker pacer_thread_;
213 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
214};
215
216class RtpPacketSenderProxy : public RtpPacketSender {
217 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800218 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100219
220 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
221 RTC_DCHECK(thread_checker_.CalledOnValidThread());
222 rtc::CritScope lock(&crit_);
223 rtp_packet_sender_ = rtp_packet_sender;
224 }
225
226 // Implements RtpPacketSender.
227 void InsertPacket(Priority priority,
228 uint32_t ssrc,
229 uint16_t sequence_number,
230 int64_t capture_time_ms,
231 size_t bytes,
232 bool retransmission) override {
233 rtc::CritScope lock(&crit_);
234 if (rtp_packet_sender_) {
235 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
236 capture_time_ms, bytes, retransmission);
237 }
238 }
239
240 private:
241 rtc::ThreadChecker thread_checker_;
242 rtc::CriticalSection crit_;
243 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
244};
245
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000246// Extend the default RTCP statistics struct with max_jitter, defined as the
247// maximum jitter value seen in an RTCP report block.
248struct ChannelStatistics : public RtcpStatistics {
249 ChannelStatistics() : rtcp(), max_jitter(0) {}
250
251 RtcpStatistics rtcp;
252 uint32_t max_jitter;
253};
254
255// Statistics callback, called at each generation of a new RTCP report block.
256class StatisticsProxy : public RtcpStatisticsCallback {
257 public:
tommi31fc21f2016-01-21 10:37:37 -0800258 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000259 virtual ~StatisticsProxy() {}
260
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000261 void StatisticsUpdated(const RtcpStatistics& statistics,
262 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000263 if (ssrc != ssrc_)
264 return;
265
tommi31fc21f2016-01-21 10:37:37 -0800266 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000267 stats_.rtcp = statistics;
268 if (statistics.jitter > stats_.max_jitter) {
269 stats_.max_jitter = statistics.jitter;
270 }
271 }
272
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000273 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000274
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000275 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800276 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000277 return stats_;
278 }
279
280 private:
281 // StatisticsUpdated calls are triggered from threads in the RTP module,
282 // while GetStats calls can be triggered from the public voice engine API,
283 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800284 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000285 const uint32_t ssrc_;
286 ChannelStatistics stats_;
287};
288
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000289class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000290 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000291 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
292 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000293
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000294 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
295 // Not used for Voice Engine.
296 }
297
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000298 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
299 int64_t rtt,
300 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000301 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
302 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
303 // report for VoiceEngine?
304 if (report_blocks.empty())
305 return;
306
307 int fraction_lost_aggregate = 0;
308 int total_number_of_packets = 0;
309
310 // If receiving multiple report blocks, calculate the weighted average based
311 // on the number of packets a report refers to.
312 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
313 block_it != report_blocks.end(); ++block_it) {
314 // Find the previous extended high sequence number for this remote SSRC,
315 // to calculate the number of RTP packets this report refers to. Ignore if
316 // we haven't seen this SSRC before.
317 std::map<uint32_t, uint32_t>::iterator seq_num_it =
318 extended_max_sequence_number_.find(block_it->sourceSSRC);
319 int number_of_packets = 0;
320 if (seq_num_it != extended_max_sequence_number_.end()) {
321 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
322 }
323 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
324 total_number_of_packets += number_of_packets;
325
326 extended_max_sequence_number_[block_it->sourceSSRC] =
327 block_it->extendedHighSeqNum;
328 }
329 int weighted_fraction_lost = 0;
330 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800331 weighted_fraction_lost =
332 (fraction_lost_aggregate + total_number_of_packets / 2) /
333 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000334 }
335 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000336 }
337
338 private:
339 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000340 // Maps remote side ssrc to extended highest sequence number received.
341 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000342};
343
kwiberg55b97fe2016-01-28 05:22:45 -0800344int32_t Channel::SendData(FrameType frameType,
345 uint8_t payloadType,
346 uint32_t timeStamp,
347 const uint8_t* payloadData,
348 size_t payloadSize,
349 const RTPFragmentationHeader* fragmentation) {
350 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
351 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
352 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
353 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000354
kwiberg55b97fe2016-01-28 05:22:45 -0800355 if (_includeAudioLevelIndication) {
356 // Store current audio level in the RTP/RTCP module.
357 // The level will be used in combination with voice-activity state
358 // (frameType) to add an RTP header extension
359 _rtpRtcpModule->SetAudioLevel(rms_level_.RMS());
360 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000361
kwiberg55b97fe2016-01-28 05:22:45 -0800362 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
363 // packetization.
364 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700365 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800366 (FrameType&)frameType, payloadType, timeStamp,
367 // Leaving the time when this frame was
368 // received from the capture device as
369 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700370 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800371 _engineStatisticsPtr->SetLastError(
372 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
373 "Channel::SendData() failed to send data to RTP/RTCP module");
374 return -1;
375 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000376
kwiberg55b97fe2016-01-28 05:22:45 -0800377 _lastLocalTimeStamp = timeStamp;
378 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000379
kwiberg55b97fe2016-01-28 05:22:45 -0800380 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000381}
382
kwiberg55b97fe2016-01-28 05:22:45 -0800383int32_t Channel::InFrameType(FrameType frame_type) {
384 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
385 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000386
kwiberg55b97fe2016-01-28 05:22:45 -0800387 rtc::CritScope cs(&_callbackCritSect);
388 _sendFrameType = (frame_type == kAudioFrameSpeech);
389 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000390}
391
kwiberg55b97fe2016-01-28 05:22:45 -0800392int32_t Channel::OnRxVadDetected(int vadDecision) {
393 rtc::CritScope cs(&_callbackCritSect);
394 if (_rxVadObserverPtr) {
395 _rxVadObserverPtr->OnRxVad(_channelId, vadDecision);
396 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000397
kwiberg55b97fe2016-01-28 05:22:45 -0800398 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000399}
400
stefan1d8a5062015-10-02 03:39:33 -0700401bool Channel::SendRtp(const uint8_t* data,
402 size_t len,
403 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800404 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
405 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000406
kwiberg55b97fe2016-01-28 05:22:45 -0800407 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000408
kwiberg55b97fe2016-01-28 05:22:45 -0800409 if (_transportPtr == NULL) {
410 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
411 "Channel::SendPacket() failed to send RTP packet due to"
412 " invalid transport object");
413 return false;
414 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000415
kwiberg55b97fe2016-01-28 05:22:45 -0800416 uint8_t* bufferToSendPtr = (uint8_t*)data;
417 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000418
kwiberg55b97fe2016-01-28 05:22:45 -0800419 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
420 std::string transport_name =
421 _externalTransport ? "external transport" : "WebRtc sockets";
422 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
423 "Channel::SendPacket() RTP transmission using %s failed",
424 transport_name.c_str());
425 return false;
426 }
427 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000428}
429
kwiberg55b97fe2016-01-28 05:22:45 -0800430bool Channel::SendRtcp(const uint8_t* data, size_t len) {
431 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
432 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000433
kwiberg55b97fe2016-01-28 05:22:45 -0800434 rtc::CritScope cs(&_callbackCritSect);
435 if (_transportPtr == NULL) {
436 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
437 "Channel::SendRtcp() failed to send RTCP packet"
438 " due to invalid transport object");
439 return false;
440 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000441
kwiberg55b97fe2016-01-28 05:22:45 -0800442 uint8_t* bufferToSendPtr = (uint8_t*)data;
443 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000444
kwiberg55b97fe2016-01-28 05:22:45 -0800445 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
446 if (n < 0) {
447 std::string transport_name =
448 _externalTransport ? "external transport" : "WebRtc sockets";
449 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
450 "Channel::SendRtcp() transmission using %s failed",
451 transport_name.c_str());
452 return false;
453 }
454 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000455}
456
kwiberg55b97fe2016-01-28 05:22:45 -0800457void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
458 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
459 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000460
kwiberg55b97fe2016-01-28 05:22:45 -0800461 // Update ssrc so that NTP for AV sync can be updated.
462 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000463}
464
Peter Boströmac547a62015-09-17 23:03:57 +0200465void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
466 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
467 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
468 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000469}
470
Peter Boströmac547a62015-09-17 23:03:57 +0200471int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000472 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000473 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000474 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800475 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200476 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800477 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
478 "Channel::OnInitializeDecoder(payloadType=%d, "
479 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
480 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000481
kwiberg55b97fe2016-01-28 05:22:45 -0800482 CodecInst receiveCodec = {0};
483 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000484
kwiberg55b97fe2016-01-28 05:22:45 -0800485 receiveCodec.pltype = payloadType;
486 receiveCodec.plfreq = frequency;
487 receiveCodec.channels = channels;
488 receiveCodec.rate = rate;
489 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000490
kwiberg55b97fe2016-01-28 05:22:45 -0800491 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
492 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000493
kwiberg55b97fe2016-01-28 05:22:45 -0800494 // Register the new codec to the ACM
kwibergc8d071e2016-04-06 12:22:38 -0700495 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, receiveCodec)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800496 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
497 "Channel::OnInitializeDecoder() invalid codec ("
498 "pt=%d, name=%s) received - 1",
499 payloadType, payloadName);
500 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
501 return -1;
502 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000503
kwiberg55b97fe2016-01-28 05:22:45 -0800504 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000505}
506
kwiberg55b97fe2016-01-28 05:22:45 -0800507int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
508 size_t payloadSize,
509 const WebRtcRTPHeader* rtpHeader) {
510 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
511 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
512 ","
513 " payloadType=%u, audioChannel=%" PRIuS ")",
514 payloadSize, rtpHeader->header.payloadType,
515 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000516
kwiberg55b97fe2016-01-28 05:22:45 -0800517 if (!channel_state_.Get().playing) {
518 // Avoid inserting into NetEQ when we are not playing. Count the
519 // packet as discarded.
520 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
521 "received packet is discarded since playing is not"
522 " activated");
523 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000524 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800525 }
526
527 // Push the incoming payload (parsed and ready for decoding) into the ACM
528 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
529 0) {
530 _engineStatisticsPtr->SetLastError(
531 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
532 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
533 return -1;
534 }
535
kwiberg55b97fe2016-01-28 05:22:45 -0800536 int64_t round_trip_time = 0;
537 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
538 NULL);
539
540 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
541 if (!nack_list.empty()) {
542 // Can't use nack_list.data() since it's not supported by all
543 // compilers.
544 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
545 }
546 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000547}
548
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000549bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000550 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000551 RTPHeader header;
552 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
553 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
554 "IncomingPacket invalid RTP header");
555 return false;
556 }
557 header.payload_type_frequency =
558 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
559 if (header.payload_type_frequency < 0)
560 return false;
561 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
562}
563
henrik.lundin42dda502016-05-18 05:36:01 -0700564MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
565 int32_t id,
566 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700567 unsigned int ssrc;
568 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
569 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800570 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700571 bool muted;
572 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
573 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800574 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
575 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
576 // In all likelihood, the audio in this frame is garbage. We return an
577 // error so that the audio mixer module doesn't add it to the mix. As
578 // a result, it won't be played out and the actions skipped here are
579 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700580 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800581 }
henrik.lundina89ab962016-05-18 08:52:45 -0700582
583 if (muted) {
584 // TODO(henrik.lundin): We should be able to do better than this. But we
585 // will have to go through all the cases below where the audio samples may
586 // be used, and handle the muted case in some way.
587 audioFrame->Mute();
588 }
kwiberg55b97fe2016-01-28 05:22:45 -0800589
590 if (_RxVadDetection) {
591 UpdateRxVadDetection(*audioFrame);
592 }
593
594 // Convert module ID to internal VoE channel ID
595 audioFrame->id_ = VoEChannelId(audioFrame->id_);
596 // Store speech type for dead-or-alive detection
597 _outputSpeechType = audioFrame->speech_type_;
598
599 ChannelState::State state = channel_state_.Get();
600
601 if (state.rx_apm_is_enabled) {
602 int err = rx_audioproc_->ProcessStream(audioFrame);
603 if (err) {
604 LOG(LS_ERROR) << "ProcessStream() error: " << err;
605 assert(false);
Ivo Creusenae856f22015-09-17 16:30:16 +0200606 }
kwiberg55b97fe2016-01-28 05:22:45 -0800607 }
608
609 {
610 // Pass the audio buffers to an optional sink callback, before applying
611 // scaling/panning, as that applies to the mix operation.
612 // External recipients of the audio (e.g. via AudioTrack), will do their
613 // own mixing/dynamic processing.
614 rtc::CritScope cs(&_callbackCritSect);
615 if (audio_sink_) {
616 AudioSinkInterface::Data data(
617 &audioFrame->data_[0], audioFrame->samples_per_channel_,
618 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
619 audioFrame->timestamp_);
620 audio_sink_->OnData(data);
621 }
622 }
623
624 float output_gain = 1.0f;
625 float left_pan = 1.0f;
626 float right_pan = 1.0f;
627 {
628 rtc::CritScope cs(&volume_settings_critsect_);
629 output_gain = _outputGain;
630 left_pan = _panLeft;
631 right_pan = _panRight;
632 }
633
634 // Output volume scaling
635 if (output_gain < 0.99f || output_gain > 1.01f) {
636 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
637 }
638
639 // Scale left and/or right channel(s) if stereo and master balance is
640 // active
641
642 if (left_pan != 1.0f || right_pan != 1.0f) {
643 if (audioFrame->num_channels_ == 1) {
644 // Emulate stereo mode since panning is active.
645 // The mono signal is copied to both left and right channels here.
646 AudioFrameOperations::MonoToStereo(audioFrame);
647 }
648 // For true stereo mode (when we are receiving a stereo signal), no
649 // action is needed.
650
651 // Do the panning operation (the audio frame contains stereo at this
652 // stage)
653 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
654 }
655
656 // Mix decoded PCM output with file if file mixing is enabled
657 if (state.output_file_playing) {
658 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700659 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800660 }
661
662 // External media
663 if (_outputExternalMedia) {
664 rtc::CritScope cs(&_callbackCritSect);
665 const bool isStereo = (audioFrame->num_channels_ == 2);
666 if (_outputExternalMediaCallbackPtr) {
667 _outputExternalMediaCallbackPtr->Process(
668 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
669 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
670 isStereo);
671 }
672 }
673
674 // Record playout if enabled
675 {
676 rtc::CritScope cs(&_fileCritSect);
677
kwiberg5a25d952016-08-17 07:31:12 -0700678 if (_outputFileRecording && output_file_recorder_) {
679 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800680 }
681 }
682
683 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700684 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800685 _outputAudioLevel.ComputeLevel(*audioFrame);
686
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_) /
700 (GetPlayoutFrequency() / 1000);
701
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
kwiberg55b97fe2016-01-28 05:22:45 -0800721int32_t Channel::NeededFrequency(int32_t id) const {
722 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
723 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000724
kwiberg55b97fe2016-01-28 05:22:45 -0800725 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000726
kwiberg55b97fe2016-01-28 05:22:45 -0800727 // Determine highest needed receive frequency
728 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000729
kwiberg55b97fe2016-01-28 05:22:45 -0800730 // Return the bigger of playout and receive frequency in the ACM.
731 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
732 highestNeeded = audio_coding_->PlayoutFrequency();
733 } else {
734 highestNeeded = receiveFrequency;
735 }
736
737 // Special case, if we're playing a file on the playout side
738 // we take that frequency into consideration as well
739 // This is not needed on sending side, since the codec will
740 // limit the spectrum anyway.
741 if (channel_state_.Get().output_file_playing) {
742 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700743 if (output_file_player_) {
744 if (output_file_player_->Frequency() > highestNeeded) {
745 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800746 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000747 }
kwiberg55b97fe2016-01-28 05:22:45 -0800748 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000749
kwiberg55b97fe2016-01-28 05:22:45 -0800750 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000751}
752
ossu5f7cfa52016-05-30 08:11:28 -0700753int32_t Channel::CreateChannel(
754 Channel*& channel,
755 int32_t channelId,
756 uint32_t instanceId,
ossu5f7cfa52016-05-30 08:11:28 -0700757 const Config& config,
758 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory) {
kwiberg55b97fe2016-01-28 05:22:45 -0800759 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
760 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
761 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000762
ivoc14d5dbe2016-07-04 07:06:55 -0700763 channel = new Channel(channelId, instanceId, config, decoder_factory);
kwiberg55b97fe2016-01-28 05:22:45 -0800764 if (channel == NULL) {
765 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
766 "Channel::CreateChannel() unable to allocate memory for"
767 " channel");
768 return -1;
769 }
770 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000771}
772
kwiberg55b97fe2016-01-28 05:22:45 -0800773void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
774 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
775 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
776 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000777
kwiberg55b97fe2016-01-28 05:22:45 -0800778 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000779}
780
kwiberg55b97fe2016-01-28 05:22:45 -0800781void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
782 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
783 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
784 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000785
kwiberg55b97fe2016-01-28 05:22:45 -0800786 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000787}
788
kwiberg55b97fe2016-01-28 05:22:45 -0800789void Channel::PlayFileEnded(int32_t id) {
790 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
791 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000792
kwiberg55b97fe2016-01-28 05:22:45 -0800793 if (id == _inputFilePlayerId) {
794 channel_state_.SetInputFilePlaying(false);
795 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
796 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000797 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800798 } else if (id == _outputFilePlayerId) {
799 channel_state_.SetOutputFilePlaying(false);
800 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
801 "Channel::PlayFileEnded() => output file player module is"
802 " shutdown");
803 }
804}
805
806void Channel::RecordFileEnded(int32_t id) {
807 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
808 "Channel::RecordFileEnded(id=%d)", id);
809
810 assert(id == _outputFileRecorderId);
811
812 rtc::CritScope cs(&_fileCritSect);
813
814 _outputFileRecording = false;
815 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
816 "Channel::RecordFileEnded() => output file recorder module is"
817 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000818}
819
pbos@webrtc.org92135212013-05-14 08:31:39 +0000820Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000821 uint32_t instanceId,
ossu5f7cfa52016-05-30 08:11:28 -0700822 const Config& config,
823 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
tommi31fc21f2016-01-21 10:37:37 -0800824 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100825 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700826 event_log_proxy_(new RtcEventLogProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100827 rtp_header_parser_(RtpHeaderParser::Create()),
828 rtp_payload_registry_(
829 new RTPPayloadRegistry(RTPPayloadStrategy::CreateStrategy(true))),
830 rtp_receive_statistics_(
831 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
832 rtp_receiver_(
833 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100834 this,
835 this,
836 rtp_payload_registry_.get())),
837 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
838 _outputAudioLevel(),
839 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100840 // Avoid conflict with other channels by adding 1024 - 1026,
841 // won't use as much as 1024 channels.
842 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
843 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
844 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
845 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100846 _outputExternalMedia(false),
847 _inputExternalMediaCallbackPtr(NULL),
848 _outputExternalMediaCallbackPtr(NULL),
849 _timeStamp(0), // This is just an offset, RTP module will add it's own
850 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100851 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100852 playout_timestamp_rtp_(0),
853 playout_timestamp_rtcp_(0),
854 playout_delay_ms_(0),
855 _numberOfDiscardedPackets(0),
856 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100857 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
858 capture_start_rtp_time_stamp_(-1),
859 capture_start_ntp_time_ms_(-1),
860 _engineStatisticsPtr(NULL),
861 _outputMixerPtr(NULL),
862 _transmitMixerPtr(NULL),
863 _moduleProcessThreadPtr(NULL),
864 _audioDeviceModulePtr(NULL),
865 _voiceEngineObserverPtr(NULL),
866 _callbackCritSectPtr(NULL),
867 _transportPtr(NULL),
868 _rxVadObserverPtr(NULL),
869 _oldVadDecision(-1),
870 _sendFrameType(0),
871 _externalMixing(false),
872 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700873 input_mute_(false),
874 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100875 _panLeft(1.0f),
876 _panRight(1.0f),
877 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100878 _lastLocalTimeStamp(0),
879 _lastPayloadType(0),
880 _includeAudioLevelIndication(false),
881 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100882 _RxVadDetection(false),
883 _rxAgcIsEnabled(false),
884 _rxNsIsEnabled(false),
885 restored_packet_in_use_(false),
886 rtcp_observer_(new VoERtcpObserver(this)),
887 network_predictor_(new NetworkPredictor(Clock::GetRealTimeClock())),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100888 associate_send_channel_(ChannelOwner(nullptr)),
889 pacing_enabled_(config.Get<VoicePacing>().enabled),
stefanbba9dec2016-02-01 04:39:55 -0800890 feedback_observer_proxy_(new TransportFeedbackProxy()),
891 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700892 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200893 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
894 kMaxRetransmissionWindowMs)),
ossu29b1a8d2016-06-13 07:34:51 -0700895 decoder_factory_(decoder_factory) {
kwiberg55b97fe2016-01-28 05:22:45 -0800896 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
897 "Channel::Channel() - ctor");
898 AudioCodingModule::Config acm_config;
899 acm_config.id = VoEModuleId(instanceId, channelId);
900 if (config.Get<NetEqCapacityConfig>().enabled) {
901 // Clamping the buffer capacity at 20 packets. While going lower will
902 // probably work, it makes little sense.
903 acm_config.neteq_config.max_packets_in_buffer =
904 std::max(20, config.Get<NetEqCapacityConfig>().capacity);
905 }
906 acm_config.neteq_config.enable_fast_accelerate =
907 config.Get<NetEqFastAccelerate>().enabled;
henrik.lundina89ab962016-05-18 08:52:45 -0700908 acm_config.neteq_config.enable_muted_state = true;
ossu5f7cfa52016-05-30 08:11:28 -0700909 acm_config.decoder_factory = decoder_factory;
kwiberg55b97fe2016-01-28 05:22:45 -0800910 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200911
kwiberg55b97fe2016-01-28 05:22:45 -0800912 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000913
kwiberg55b97fe2016-01-28 05:22:45 -0800914 RtpRtcp::Configuration configuration;
915 configuration.audio = true;
916 configuration.outgoing_transport = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800917 configuration.receive_statistics = rtp_receive_statistics_.get();
918 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800919 if (pacing_enabled_) {
920 configuration.paced_sender = rtp_packet_sender_proxy_.get();
921 configuration.transport_sequence_number_allocator =
922 seq_num_allocator_proxy_.get();
923 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
924 }
ivoc14d5dbe2016-07-04 07:06:55 -0700925 configuration.event_log = &(*event_log_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200926 configuration.retransmission_rate_limiter =
927 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000928
kwiberg55b97fe2016-01-28 05:22:45 -0800929 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100930 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000931
kwiberg55b97fe2016-01-28 05:22:45 -0800932 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
933 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
934 statistics_proxy_.get());
aluebs@webrtc.orgf927fd62014-04-16 11:58:18 +0000935
kwiberg55b97fe2016-01-28 05:22:45 -0800936 Config audioproc_config;
937 audioproc_config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
938 rx_audioproc_.reset(AudioProcessing::Create(audioproc_config));
niklase@google.com470e71d2011-07-07 08:21:25 +0000939}
940
kwiberg55b97fe2016-01-28 05:22:45 -0800941Channel::~Channel() {
942 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
943 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
944 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000945
kwiberg55b97fe2016-01-28 05:22:45 -0800946 if (_outputExternalMedia) {
947 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
948 }
949 if (channel_state_.Get().input_external_media) {
950 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
951 }
952 StopSend();
953 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000954
kwiberg55b97fe2016-01-28 05:22:45 -0800955 {
956 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700957 if (input_file_player_) {
958 input_file_player_->RegisterModuleFileCallback(NULL);
959 input_file_player_->StopPlayingFile();
niklase@google.com470e71d2011-07-07 08:21:25 +0000960 }
kwiberg5a25d952016-08-17 07:31:12 -0700961 if (output_file_player_) {
962 output_file_player_->RegisterModuleFileCallback(NULL);
963 output_file_player_->StopPlayingFile();
kwiberg55b97fe2016-01-28 05:22:45 -0800964 }
kwiberg5a25d952016-08-17 07:31:12 -0700965 if (output_file_recorder_) {
966 output_file_recorder_->RegisterModuleFileCallback(NULL);
967 output_file_recorder_->StopRecording();
kwiberg55b97fe2016-01-28 05:22:45 -0800968 }
969 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000970
kwiberg55b97fe2016-01-28 05:22:45 -0800971 // The order to safely shutdown modules in a channel is:
972 // 1. De-register callbacks in modules
973 // 2. De-register modules in process thread
974 // 3. Destroy modules
975 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
976 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
977 "~Channel() failed to de-register transport callback"
978 " (Audio coding module)");
979 }
980 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
981 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
982 "~Channel() failed to de-register VAD callback"
983 " (Audio coding module)");
984 }
985 // De-register modules in process thread
986 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +0000987
kwiberg55b97fe2016-01-28 05:22:45 -0800988 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +0000989}
990
kwiberg55b97fe2016-01-28 05:22:45 -0800991int32_t Channel::Init() {
992 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
993 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000994
kwiberg55b97fe2016-01-28 05:22:45 -0800995 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000996
kwiberg55b97fe2016-01-28 05:22:45 -0800997 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000998
kwiberg55b97fe2016-01-28 05:22:45 -0800999 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
1000 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1001 "Channel::Init() must call SetEngineInformation() first");
1002 return -1;
1003 }
1004
1005 // --- Add modules to process thread (for periodic schedulation)
1006
1007 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
1008
1009 // --- ACM initialization
1010
1011 if (audio_coding_->InitializeReceiver() == -1) {
1012 _engineStatisticsPtr->SetLastError(
1013 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1014 "Channel::Init() unable to initialize the ACM - 1");
1015 return -1;
1016 }
1017
1018 // --- RTP/RTCP module initialization
1019
1020 // Ensure that RTCP is enabled by default for the created channel.
1021 // Note that, the module will keep generating RTCP until it is explicitly
1022 // disabled by the user.
1023 // After StopListen (when no sockets exists), RTCP packets will no longer
1024 // be transmitted since the Transport object will then be invalid.
1025 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
1026 // RTCP is enabled by default.
1027 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1028 // --- Register all permanent callbacks
1029 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
1030 (audio_coding_->RegisterVADCallback(this) == -1);
1031
1032 if (fail) {
1033 _engineStatisticsPtr->SetLastError(
1034 VE_CANNOT_INIT_CHANNEL, kTraceError,
1035 "Channel::Init() callbacks not registered");
1036 return -1;
1037 }
1038
1039 // --- Register all supported codecs to the receiving side of the
1040 // RTP/RTCP module
1041
1042 CodecInst codec;
1043 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1044
1045 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1046 // Open up the RTP/RTCP receiver for all supported codecs
1047 if ((audio_coding_->Codec(idx, &codec) == -1) ||
1048 (rtp_receiver_->RegisterReceivePayload(
1049 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1050 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
1051 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1052 "Channel::Init() unable to register %s "
1053 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1054 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1055 codec.rate);
1056 } else {
1057 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1058 "Channel::Init() %s (%d/%d/%" PRIuS
1059 "/%d) has been "
1060 "added to the RTP/RTCP receiver",
1061 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1062 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001063 }
1064
kwiberg55b97fe2016-01-28 05:22:45 -08001065 // Ensure that PCMU is used as default codec on the sending side
1066 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1067 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001068 }
1069
kwiberg55b97fe2016-01-28 05:22:45 -08001070 // Register default PT for outband 'telephone-event'
1071 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001072 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
1073 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001074 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1075 "Channel::Init() failed to register outband "
1076 "'telephone-event' (%d/%d) correctly",
1077 codec.pltype, codec.plfreq);
1078 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001079 }
1080
kwiberg55b97fe2016-01-28 05:22:45 -08001081 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001082 if (!codec_manager_.RegisterEncoder(codec) ||
1083 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1084 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec) ||
1085 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001086 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1087 "Channel::Init() failed to register CN (%d/%d) "
1088 "correctly - 1",
1089 codec.pltype, codec.plfreq);
1090 }
1091 }
kwiberg55b97fe2016-01-28 05:22:45 -08001092 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001093
kwiberg55b97fe2016-01-28 05:22:45 -08001094 if (rx_audioproc_->noise_suppression()->set_level(kDefaultNsMode) != 0) {
1095 LOG(LS_ERROR) << "noise_suppression()->set_level(kDefaultNsMode) failed.";
1096 return -1;
1097 }
1098 if (rx_audioproc_->gain_control()->set_mode(kDefaultRxAgcMode) != 0) {
1099 LOG(LS_ERROR) << "gain_control()->set_mode(kDefaultRxAgcMode) failed.";
1100 return -1;
1101 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001102
kwiberg55b97fe2016-01-28 05:22:45 -08001103 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001104}
1105
kwiberg55b97fe2016-01-28 05:22:45 -08001106int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1107 OutputMixer& outputMixer,
1108 voe::TransmitMixer& transmitMixer,
1109 ProcessThread& moduleProcessThread,
1110 AudioDeviceModule& audioDeviceModule,
1111 VoiceEngineObserver* voiceEngineObserver,
1112 rtc::CriticalSection* callbackCritSect) {
1113 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1114 "Channel::SetEngineInformation()");
1115 _engineStatisticsPtr = &engineStatistics;
1116 _outputMixerPtr = &outputMixer;
1117 _transmitMixerPtr = &transmitMixer,
1118 _moduleProcessThreadPtr = &moduleProcessThread;
1119 _audioDeviceModulePtr = &audioDeviceModule;
1120 _voiceEngineObserverPtr = voiceEngineObserver;
1121 _callbackCritSectPtr = callbackCritSect;
1122 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001123}
1124
kwiberg55b97fe2016-01-28 05:22:45 -08001125int32_t Channel::UpdateLocalTimeStamp() {
1126 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1127 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001128}
1129
kwibergb7f89d62016-02-17 10:04:18 -08001130void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001131 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001132 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001133}
1134
ossu29b1a8d2016-06-13 07:34:51 -07001135const rtc::scoped_refptr<AudioDecoderFactory>&
1136Channel::GetAudioDecoderFactory() const {
1137 return decoder_factory_;
1138}
1139
kwiberg55b97fe2016-01-28 05:22:45 -08001140int32_t Channel::StartPlayout() {
1141 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1142 "Channel::StartPlayout()");
1143 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001144 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001145 }
1146
1147 if (!_externalMixing) {
1148 // Add participant as candidates for mixing.
1149 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1150 _engineStatisticsPtr->SetLastError(
1151 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1152 "StartPlayout() failed to add participant to mixer");
1153 return -1;
1154 }
1155 }
1156
1157 channel_state_.SetPlaying(true);
1158 if (RegisterFilePlayingToMixer() != 0)
1159 return -1;
1160
1161 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001162}
1163
kwiberg55b97fe2016-01-28 05:22:45 -08001164int32_t Channel::StopPlayout() {
1165 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1166 "Channel::StopPlayout()");
1167 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001168 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001169 }
1170
1171 if (!_externalMixing) {
1172 // Remove participant as candidates for mixing
1173 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1174 _engineStatisticsPtr->SetLastError(
1175 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1176 "StopPlayout() failed to remove participant from mixer");
1177 return -1;
1178 }
1179 }
1180
1181 channel_state_.SetPlaying(false);
1182 _outputAudioLevel.Clear();
1183
1184 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001185}
1186
kwiberg55b97fe2016-01-28 05:22:45 -08001187int32_t Channel::StartSend() {
1188 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1189 "Channel::StartSend()");
1190 // Resume the previous sequence number which was reset by StopSend().
1191 // This needs to be done before |sending| is set to true.
1192 if (send_sequence_number_)
1193 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001194
kwiberg55b97fe2016-01-28 05:22:45 -08001195 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001196 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001197 }
1198 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001199
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001200 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001201 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1202 _engineStatisticsPtr->SetLastError(
1203 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1204 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001205 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001206 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001207 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001208 return -1;
1209 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001210
kwiberg55b97fe2016-01-28 05:22:45 -08001211 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001212}
1213
kwiberg55b97fe2016-01-28 05:22:45 -08001214int32_t Channel::StopSend() {
1215 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1216 "Channel::StopSend()");
1217 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001218 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001219 }
1220 channel_state_.SetSending(false);
1221
1222 // Store the sequence number to be able to pick up the same sequence for
1223 // the next StartSend(). This is needed for restarting device, otherwise
1224 // it might cause libSRTP to complain about packets being replayed.
1225 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1226 // CL is landed. See issue
1227 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1228 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1229
1230 // Reset sending SSRC and sequence number and triggers direct transmission
1231 // of RTCP BYE
1232 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1233 _engineStatisticsPtr->SetLastError(
1234 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1235 "StartSend() RTP/RTCP failed to stop sending");
1236 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001237 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001238
1239 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001240}
1241
kwiberg55b97fe2016-01-28 05:22:45 -08001242int32_t Channel::StartReceiving() {
1243 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1244 "Channel::StartReceiving()");
1245 if (channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001246 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001247 }
1248 channel_state_.SetReceiving(true);
1249 _numberOfDiscardedPackets = 0;
1250 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001251}
1252
kwiberg55b97fe2016-01-28 05:22:45 -08001253int32_t Channel::StopReceiving() {
1254 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1255 "Channel::StopReceiving()");
1256 if (!channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001257 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001258 }
1259
1260 channel_state_.SetReceiving(false);
1261 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001262}
1263
kwiberg55b97fe2016-01-28 05:22:45 -08001264int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1265 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1266 "Channel::RegisterVoiceEngineObserver()");
1267 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001268
kwiberg55b97fe2016-01-28 05:22:45 -08001269 if (_voiceEngineObserverPtr) {
1270 _engineStatisticsPtr->SetLastError(
1271 VE_INVALID_OPERATION, kTraceError,
1272 "RegisterVoiceEngineObserver() observer already enabled");
1273 return -1;
1274 }
1275 _voiceEngineObserverPtr = &observer;
1276 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001277}
1278
kwiberg55b97fe2016-01-28 05:22:45 -08001279int32_t Channel::DeRegisterVoiceEngineObserver() {
1280 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1281 "Channel::DeRegisterVoiceEngineObserver()");
1282 rtc::CritScope cs(&_callbackCritSect);
1283
1284 if (!_voiceEngineObserverPtr) {
1285 _engineStatisticsPtr->SetLastError(
1286 VE_INVALID_OPERATION, kTraceWarning,
1287 "DeRegisterVoiceEngineObserver() observer already disabled");
1288 return 0;
1289 }
1290 _voiceEngineObserverPtr = NULL;
1291 return 0;
1292}
1293
1294int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001295 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001296 if (send_codec) {
1297 codec = *send_codec;
1298 return 0;
1299 }
1300 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001301}
1302
kwiberg55b97fe2016-01-28 05:22:45 -08001303int32_t Channel::GetRecCodec(CodecInst& codec) {
1304 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001305}
1306
kwiberg55b97fe2016-01-28 05:22:45 -08001307int32_t Channel::SetSendCodec(const CodecInst& codec) {
1308 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1309 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001310
kwibergc8d071e2016-04-06 12:22:38 -07001311 if (!codec_manager_.RegisterEncoder(codec) ||
1312 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001313 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1314 "SetSendCodec() failed to register codec to ACM");
1315 return -1;
1316 }
1317
1318 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1319 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1320 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1321 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1322 "SetSendCodec() failed to register codec to"
1323 " RTP/RTCP module");
1324 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001325 }
kwiberg55b97fe2016-01-28 05:22:45 -08001326 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001327
kwiberg55b97fe2016-01-28 05:22:45 -08001328 if (_rtpRtcpModule->SetAudioPacketSize(codec.pacsize) != 0) {
1329 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1330 "SetSendCodec() failed to set audio packet size");
1331 return -1;
1332 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001333
kwiberg55b97fe2016-01-28 05:22:45 -08001334 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001335}
1336
Ivo Creusenadf89b72015-04-29 16:03:33 +02001337void Channel::SetBitRate(int bitrate_bps) {
1338 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1339 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
1340 audio_coding_->SetBitRate(bitrate_bps);
Erik Språng737336d2016-07-29 12:59:36 +02001341 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001342}
1343
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001344void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue@webrtc.org74aaf292014-07-16 21:28:26 +00001345 network_predictor_->UpdatePacketLossRate(fraction_lost);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001346 uint8_t average_fraction_loss = network_predictor_->GetLossRate();
1347
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001348 // Normalizes rate to 0 - 100.
kwiberg55b97fe2016-01-28 05:22:45 -08001349 if (audio_coding_->SetPacketLossRate(100 * average_fraction_loss / 255) !=
1350 0) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001351 assert(false); // This should not happen.
1352 }
1353}
1354
kwiberg55b97fe2016-01-28 05:22:45 -08001355int32_t Channel::SetVADStatus(bool enableVAD,
1356 ACMVADMode mode,
1357 bool disableDTX) {
1358 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1359 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001360 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1361 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1362 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001363 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1364 kTraceError,
1365 "SetVADStatus() failed to set VAD");
1366 return -1;
1367 }
1368 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001369}
1370
kwiberg55b97fe2016-01-28 05:22:45 -08001371int32_t Channel::GetVADStatus(bool& enabledVAD,
1372 ACMVADMode& mode,
1373 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001374 const auto* params = codec_manager_.GetStackParams();
1375 enabledVAD = params->use_cng;
1376 mode = params->vad_mode;
1377 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001378 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001379}
1380
kwiberg55b97fe2016-01-28 05:22:45 -08001381int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1382 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1383 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001384
kwiberg55b97fe2016-01-28 05:22:45 -08001385 if (channel_state_.Get().playing) {
1386 _engineStatisticsPtr->SetLastError(
1387 VE_ALREADY_PLAYING, kTraceError,
1388 "SetRecPayloadType() unable to set PT while playing");
1389 return -1;
1390 }
1391 if (channel_state_.Get().receiving) {
1392 _engineStatisticsPtr->SetLastError(
1393 VE_ALREADY_LISTENING, kTraceError,
1394 "SetRecPayloadType() unable to set PT while listening");
1395 return -1;
1396 }
1397
1398 if (codec.pltype == -1) {
1399 // De-register the selected codec (RTP/RTCP module and ACM)
1400
1401 int8_t pltype(-1);
1402 CodecInst rxCodec = codec;
1403
1404 // Get payload type for the given codec
1405 rtp_payload_registry_->ReceivePayloadType(
1406 rxCodec.plname, rxCodec.plfreq, rxCodec.channels,
1407 (rxCodec.rate < 0) ? 0 : rxCodec.rate, &pltype);
1408 rxCodec.pltype = pltype;
1409
1410 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1411 _engineStatisticsPtr->SetLastError(
1412 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1413 "SetRecPayloadType() RTP/RTCP-module deregistration "
1414 "failed");
1415 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001416 }
kwiberg55b97fe2016-01-28 05:22:45 -08001417 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1418 _engineStatisticsPtr->SetLastError(
1419 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1420 "SetRecPayloadType() ACM deregistration failed - 1");
1421 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001422 }
kwiberg55b97fe2016-01-28 05:22:45 -08001423 return 0;
1424 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001425
kwiberg55b97fe2016-01-28 05:22:45 -08001426 if (rtp_receiver_->RegisterReceivePayload(
1427 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1428 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1429 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001430 // TODO(kwiberg): Retrying is probably not necessary, since
1431 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001432 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001433 if (rtp_receiver_->RegisterReceivePayload(
kwiberg55b97fe2016-01-28 05:22:45 -08001434 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1435 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1436 _engineStatisticsPtr->SetLastError(
1437 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1438 "SetRecPayloadType() RTP/RTCP-module registration failed");
1439 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001440 }
kwiberg55b97fe2016-01-28 05:22:45 -08001441 }
kwibergc8d071e2016-04-06 12:22:38 -07001442 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001443 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergc8d071e2016-04-06 12:22:38 -07001444 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001445 _engineStatisticsPtr->SetLastError(
1446 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1447 "SetRecPayloadType() ACM registration failed - 1");
1448 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001449 }
kwiberg55b97fe2016-01-28 05:22:45 -08001450 }
1451 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001452}
1453
kwiberg55b97fe2016-01-28 05:22:45 -08001454int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1455 int8_t payloadType(-1);
1456 if (rtp_payload_registry_->ReceivePayloadType(
1457 codec.plname, codec.plfreq, codec.channels,
1458 (codec.rate < 0) ? 0 : codec.rate, &payloadType) != 0) {
1459 _engineStatisticsPtr->SetLastError(
1460 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1461 "GetRecPayloadType() failed to retrieve RX payload type");
1462 return -1;
1463 }
1464 codec.pltype = payloadType;
1465 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001466}
1467
kwiberg55b97fe2016-01-28 05:22:45 -08001468int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1469 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1470 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001471
kwiberg55b97fe2016-01-28 05:22:45 -08001472 CodecInst codec;
1473 int32_t samplingFreqHz(-1);
1474 const size_t kMono = 1;
1475 if (frequency == kFreq32000Hz)
1476 samplingFreqHz = 32000;
1477 else if (frequency == kFreq16000Hz)
1478 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001479
kwiberg55b97fe2016-01-28 05:22:45 -08001480 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1481 _engineStatisticsPtr->SetLastError(
1482 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1483 "SetSendCNPayloadType() failed to retrieve default CN codec "
1484 "settings");
1485 return -1;
1486 }
1487
1488 // Modify the payload type (must be set to dynamic range)
1489 codec.pltype = type;
1490
kwibergc8d071e2016-04-06 12:22:38 -07001491 if (!codec_manager_.RegisterEncoder(codec) ||
1492 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001493 _engineStatisticsPtr->SetLastError(
1494 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1495 "SetSendCNPayloadType() failed to register CN to ACM");
1496 return -1;
1497 }
1498
1499 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1500 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1501 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1502 _engineStatisticsPtr->SetLastError(
1503 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1504 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1505 "module");
1506 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001507 }
kwiberg55b97fe2016-01-28 05:22:45 -08001508 }
1509 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001510}
1511
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001512int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001513 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001514 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001515
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001516 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001517 _engineStatisticsPtr->SetLastError(
1518 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001519 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001520 return -1;
1521 }
1522 return 0;
1523}
1524
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001525int Channel::SetOpusDtx(bool enable_dtx) {
1526 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1527 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001528 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001529 : audio_coding_->DisableOpusDtx();
1530 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001531 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1532 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001533 return -1;
1534 }
1535 return 0;
1536}
1537
ivoc85228d62016-07-27 04:53:47 -07001538int Channel::GetOpusDtx(bool* enabled) {
1539 int success = -1;
1540 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1541 if (encoder) {
1542 *enabled = encoder->GetDtx();
1543 success = 0;
1544 }
1545 });
1546 return success;
1547}
1548
mflodman3d7db262016-04-29 00:57:13 -07001549int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001550 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001551 "Channel::RegisterExternalTransport()");
1552
kwiberg55b97fe2016-01-28 05:22:45 -08001553 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001554 if (_externalTransport) {
1555 _engineStatisticsPtr->SetLastError(
1556 VE_INVALID_OPERATION, kTraceError,
1557 "RegisterExternalTransport() external transport already enabled");
1558 return -1;
1559 }
1560 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001561 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001562 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001563}
1564
kwiberg55b97fe2016-01-28 05:22:45 -08001565int32_t Channel::DeRegisterExternalTransport() {
1566 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1567 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001568
kwiberg55b97fe2016-01-28 05:22:45 -08001569 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001570 if (_transportPtr) {
1571 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1572 "DeRegisterExternalTransport() all transport is disabled");
1573 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001574 _engineStatisticsPtr->SetLastError(
1575 VE_INVALID_OPERATION, kTraceWarning,
1576 "DeRegisterExternalTransport() external transport already "
1577 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001578 }
1579 _externalTransport = false;
1580 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001581 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001582}
1583
mflodman3d7db262016-04-29 00:57:13 -07001584int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001585 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001586 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001587 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001588 "Channel::ReceivedRTPPacket()");
1589
1590 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001591 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001592
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001593 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001594 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1595 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1596 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001597 return -1;
1598 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001599 header.payload_type_frequency =
1600 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001601 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001602 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001603 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001604 rtp_receive_statistics_->IncomingPacket(
1605 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001606 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001607
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001608 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001609}
1610
1611bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001612 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001613 const RTPHeader& header,
1614 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001615 if (rtp_payload_registry_->IsRtx(header)) {
1616 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001617 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001618 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001619 assert(packet_length >= header.headerLength);
1620 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001621 PayloadUnion payload_specific;
1622 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001623 &payload_specific)) {
1624 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001625 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001626 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1627 payload_specific, in_order);
1628}
1629
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001630bool Channel::HandleRtxPacket(const uint8_t* packet,
1631 size_t packet_length,
1632 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001633 if (!rtp_payload_registry_->IsRtx(header))
1634 return false;
1635
1636 // Remove the RTX header and parse the original RTP header.
1637 if (packet_length < header.headerLength)
1638 return false;
1639 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1640 return false;
1641 if (restored_packet_in_use_) {
1642 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1643 "Multiple RTX headers detected, dropping packet");
1644 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001645 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001646 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001647 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1648 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001649 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1650 "Incoming RTX packet: invalid RTP header");
1651 return false;
1652 }
1653 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001654 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001655 restored_packet_in_use_ = false;
1656 return ret;
1657}
1658
1659bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1660 StreamStatistician* statistician =
1661 rtp_receive_statistics_->GetStatistician(header.ssrc);
1662 if (!statistician)
1663 return false;
1664 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001665}
1666
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001667bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1668 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001669 // Retransmissions are handled separately if RTX is enabled.
1670 if (rtp_payload_registry_->RtxEnabled())
1671 return false;
1672 StreamStatistician* statistician =
1673 rtp_receive_statistics_->GetStatistician(header.ssrc);
1674 if (!statistician)
1675 return false;
1676 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001677 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001678 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001679 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001680}
1681
mflodman3d7db262016-04-29 00:57:13 -07001682int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001683 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001684 "Channel::ReceivedRTCPPacket()");
1685 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001686 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001687
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001688 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001689 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001690 _engineStatisticsPtr->SetLastError(
1691 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1692 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1693 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001694
Minyue2013aec2015-05-13 14:14:42 +02001695 int64_t rtt = GetRTT(true);
1696 if (rtt == 0) {
1697 // Waiting for valid RTT.
1698 return 0;
1699 }
Erik Språng737336d2016-07-29 12:59:36 +02001700
1701 int64_t nack_window_ms = rtt;
1702 if (nack_window_ms < kMinRetransmissionWindowMs) {
1703 nack_window_ms = kMinRetransmissionWindowMs;
1704 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1705 nack_window_ms = kMaxRetransmissionWindowMs;
1706 }
1707 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1708
Minyue2013aec2015-05-13 14:14:42 +02001709 uint32_t ntp_secs = 0;
1710 uint32_t ntp_frac = 0;
1711 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001712 if (0 !=
1713 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1714 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001715 // Waiting for RTCP.
1716 return 0;
1717 }
1718
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001719 {
tommi31fc21f2016-01-21 10:37:37 -08001720 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001721 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001722 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001723 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001724}
1725
niklase@google.com470e71d2011-07-07 08:21:25 +00001726int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001727 bool loop,
1728 FileFormats format,
1729 int startPosition,
1730 float volumeScaling,
1731 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001732 const CodecInst* codecInst) {
1733 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1734 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1735 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1736 "stopPosition=%d)",
1737 fileName, loop, format, volumeScaling, startPosition,
1738 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001739
kwiberg55b97fe2016-01-28 05:22:45 -08001740 if (channel_state_.Get().output_file_playing) {
1741 _engineStatisticsPtr->SetLastError(
1742 VE_ALREADY_PLAYING, kTraceError,
1743 "StartPlayingFileLocally() is already playing");
1744 return -1;
1745 }
1746
1747 {
1748 rtc::CritScope cs(&_fileCritSect);
1749
kwiberg5a25d952016-08-17 07:31:12 -07001750 if (output_file_player_) {
1751 output_file_player_->RegisterModuleFileCallback(NULL);
1752 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001753 }
1754
kwiberg5a25d952016-08-17 07:31:12 -07001755 output_file_player_ = FilePlayer::NewFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001756 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001757
kwiberg5a25d952016-08-17 07:31:12 -07001758 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001759 _engineStatisticsPtr->SetLastError(
1760 VE_INVALID_ARGUMENT, kTraceError,
1761 "StartPlayingFileLocally() filePlayer format is not correct");
1762 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001763 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001764
kwiberg55b97fe2016-01-28 05:22:45 -08001765 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001766
kwiberg5a25d952016-08-17 07:31:12 -07001767 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001768 fileName, loop, startPosition, volumeScaling, notificationTime,
1769 stopPosition, (const CodecInst*)codecInst) != 0) {
1770 _engineStatisticsPtr->SetLastError(
1771 VE_BAD_FILE, kTraceError,
1772 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001773 output_file_player_->StopPlayingFile();
1774 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001775 return -1;
1776 }
kwiberg5a25d952016-08-17 07:31:12 -07001777 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001778 channel_state_.SetOutputFilePlaying(true);
1779 }
1780
1781 if (RegisterFilePlayingToMixer() != 0)
1782 return -1;
1783
1784 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001785}
1786
1787int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001788 FileFormats format,
1789 int startPosition,
1790 float volumeScaling,
1791 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001792 const CodecInst* codecInst) {
1793 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1794 "Channel::StartPlayingFileLocally(format=%d,"
1795 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1796 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001797
kwiberg55b97fe2016-01-28 05:22:45 -08001798 if (stream == NULL) {
1799 _engineStatisticsPtr->SetLastError(
1800 VE_BAD_FILE, kTraceError,
1801 "StartPlayingFileLocally() NULL as input stream");
1802 return -1;
1803 }
1804
1805 if (channel_state_.Get().output_file_playing) {
1806 _engineStatisticsPtr->SetLastError(
1807 VE_ALREADY_PLAYING, kTraceError,
1808 "StartPlayingFileLocally() is already playing");
1809 return -1;
1810 }
1811
1812 {
1813 rtc::CritScope cs(&_fileCritSect);
1814
1815 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001816 if (output_file_player_) {
1817 output_file_player_->RegisterModuleFileCallback(NULL);
1818 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001819 }
1820
kwiberg55b97fe2016-01-28 05:22:45 -08001821 // Create the instance
kwiberg5a25d952016-08-17 07:31:12 -07001822 output_file_player_ = FilePlayer::NewFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001823 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001824
kwiberg5a25d952016-08-17 07:31:12 -07001825 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001826 _engineStatisticsPtr->SetLastError(
1827 VE_INVALID_ARGUMENT, kTraceError,
1828 "StartPlayingFileLocally() filePlayer format isnot correct");
1829 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001830 }
1831
kwiberg55b97fe2016-01-28 05:22:45 -08001832 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001833
kwiberg4ec01d92016-08-22 08:43:54 -07001834 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001835 volumeScaling, notificationTime,
1836 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001837 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1838 "StartPlayingFile() failed to "
1839 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001840 output_file_player_->StopPlayingFile();
1841 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001842 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001843 }
kwiberg5a25d952016-08-17 07:31:12 -07001844 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001845 channel_state_.SetOutputFilePlaying(true);
1846 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001847
kwiberg55b97fe2016-01-28 05:22:45 -08001848 if (RegisterFilePlayingToMixer() != 0)
1849 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001850
kwiberg55b97fe2016-01-28 05:22:45 -08001851 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001852}
1853
kwiberg55b97fe2016-01-28 05:22:45 -08001854int Channel::StopPlayingFileLocally() {
1855 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1856 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001857
kwiberg55b97fe2016-01-28 05:22:45 -08001858 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001859 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001860 }
1861
1862 {
1863 rtc::CritScope cs(&_fileCritSect);
1864
kwiberg5a25d952016-08-17 07:31:12 -07001865 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001866 _engineStatisticsPtr->SetLastError(
1867 VE_STOP_RECORDING_FAILED, kTraceError,
1868 "StopPlayingFile() could not stop playing");
1869 return -1;
1870 }
kwiberg5a25d952016-08-17 07:31:12 -07001871 output_file_player_->RegisterModuleFileCallback(NULL);
1872 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001873 channel_state_.SetOutputFilePlaying(false);
1874 }
1875 // _fileCritSect cannot be taken while calling
1876 // SetAnonymousMixibilityStatus. Refer to comments in
1877 // StartPlayingFileLocally(const char* ...) for more details.
1878 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1879 _engineStatisticsPtr->SetLastError(
1880 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1881 "StopPlayingFile() failed to stop participant from playing as"
1882 "file in the mixer");
1883 return -1;
1884 }
1885
1886 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001887}
1888
kwiberg55b97fe2016-01-28 05:22:45 -08001889int Channel::IsPlayingFileLocally() const {
1890 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001891}
1892
kwiberg55b97fe2016-01-28 05:22:45 -08001893int Channel::RegisterFilePlayingToMixer() {
1894 // Return success for not registering for file playing to mixer if:
1895 // 1. playing file before playout is started on that channel.
1896 // 2. starting playout without file playing on that channel.
1897 if (!channel_state_.Get().playing ||
1898 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001899 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001900 }
1901
1902 // |_fileCritSect| cannot be taken while calling
1903 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1904 // frames can be pulled by the mixer. Since the frames are generated from
1905 // the file, _fileCritSect will be taken. This would result in a deadlock.
1906 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1907 channel_state_.SetOutputFilePlaying(false);
1908 rtc::CritScope cs(&_fileCritSect);
1909 _engineStatisticsPtr->SetLastError(
1910 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1911 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001912 output_file_player_->StopPlayingFile();
1913 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001914 return -1;
1915 }
1916
1917 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001918}
1919
niklase@google.com470e71d2011-07-07 08:21:25 +00001920int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001921 bool loop,
1922 FileFormats format,
1923 int startPosition,
1924 float volumeScaling,
1925 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001926 const CodecInst* codecInst) {
1927 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1928 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1929 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1930 "stopPosition=%d)",
1931 fileName, loop, format, volumeScaling, startPosition,
1932 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001933
kwiberg55b97fe2016-01-28 05:22:45 -08001934 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001935
kwiberg55b97fe2016-01-28 05:22:45 -08001936 if (channel_state_.Get().input_file_playing) {
1937 _engineStatisticsPtr->SetLastError(
1938 VE_ALREADY_PLAYING, kTraceWarning,
1939 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001940 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001941 }
1942
1943 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001944 if (input_file_player_) {
1945 input_file_player_->RegisterModuleFileCallback(NULL);
1946 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001947 }
1948
1949 // Create the instance
kwiberg5a25d952016-08-17 07:31:12 -07001950 input_file_player_ = FilePlayer::NewFilePlayer(_inputFilePlayerId,
1951 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08001952
kwiberg5a25d952016-08-17 07:31:12 -07001953 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001954 _engineStatisticsPtr->SetLastError(
1955 VE_INVALID_ARGUMENT, kTraceError,
1956 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1957 return -1;
1958 }
1959
1960 const uint32_t notificationTime(0);
1961
kwiberg5a25d952016-08-17 07:31:12 -07001962 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001963 fileName, loop, startPosition, volumeScaling, notificationTime,
1964 stopPosition, (const CodecInst*)codecInst) != 0) {
1965 _engineStatisticsPtr->SetLastError(
1966 VE_BAD_FILE, kTraceError,
1967 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001968 input_file_player_->StopPlayingFile();
1969 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001970 return -1;
1971 }
kwiberg5a25d952016-08-17 07:31:12 -07001972 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001973 channel_state_.SetInputFilePlaying(true);
1974
1975 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001976}
1977
1978int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001979 FileFormats format,
1980 int startPosition,
1981 float volumeScaling,
1982 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001983 const CodecInst* codecInst) {
1984 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1985 "Channel::StartPlayingFileAsMicrophone(format=%d, "
1986 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1987 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001988
kwiberg55b97fe2016-01-28 05:22:45 -08001989 if (stream == NULL) {
1990 _engineStatisticsPtr->SetLastError(
1991 VE_BAD_FILE, kTraceError,
1992 "StartPlayingFileAsMicrophone NULL as input stream");
1993 return -1;
1994 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001995
kwiberg55b97fe2016-01-28 05:22:45 -08001996 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001997
kwiberg55b97fe2016-01-28 05:22:45 -08001998 if (channel_state_.Get().input_file_playing) {
1999 _engineStatisticsPtr->SetLastError(
2000 VE_ALREADY_PLAYING, kTraceWarning,
2001 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002002 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002003 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002004
kwiberg55b97fe2016-01-28 05:22:45 -08002005 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002006 if (input_file_player_) {
2007 input_file_player_->RegisterModuleFileCallback(NULL);
2008 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002009 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002010
kwiberg55b97fe2016-01-28 05:22:45 -08002011 // Create the instance
kwiberg5a25d952016-08-17 07:31:12 -07002012 input_file_player_ = FilePlayer::NewFilePlayer(_inputFilePlayerId,
2013 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002014
kwiberg5a25d952016-08-17 07:31:12 -07002015 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002016 _engineStatisticsPtr->SetLastError(
2017 VE_INVALID_ARGUMENT, kTraceError,
2018 "StartPlayingInputFile() filePlayer format isnot correct");
2019 return -1;
2020 }
2021
2022 const uint32_t notificationTime(0);
2023
kwiberg4ec01d92016-08-22 08:43:54 -07002024 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2025 notificationTime, stopPosition,
2026 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002027 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2028 "StartPlayingFile() failed to start "
2029 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002030 input_file_player_->StopPlayingFile();
2031 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002032 return -1;
2033 }
2034
kwiberg5a25d952016-08-17 07:31:12 -07002035 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002036 channel_state_.SetInputFilePlaying(true);
2037
2038 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002039}
2040
kwiberg55b97fe2016-01-28 05:22:45 -08002041int Channel::StopPlayingFileAsMicrophone() {
2042 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2043 "Channel::StopPlayingFileAsMicrophone()");
2044
2045 rtc::CritScope cs(&_fileCritSect);
2046
2047 if (!channel_state_.Get().input_file_playing) {
2048 return 0;
2049 }
2050
kwiberg5a25d952016-08-17 07:31:12 -07002051 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002052 _engineStatisticsPtr->SetLastError(
2053 VE_STOP_RECORDING_FAILED, kTraceError,
2054 "StopPlayingFile() could not stop playing");
2055 return -1;
2056 }
kwiberg5a25d952016-08-17 07:31:12 -07002057 input_file_player_->RegisterModuleFileCallback(NULL);
2058 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002059 channel_state_.SetInputFilePlaying(false);
2060
2061 return 0;
2062}
2063
2064int Channel::IsPlayingFileAsMicrophone() const {
2065 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002066}
2067
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002068int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002069 const CodecInst* codecInst) {
2070 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2071 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002072
kwiberg55b97fe2016-01-28 05:22:45 -08002073 if (_outputFileRecording) {
2074 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2075 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002076 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002077 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002078
kwiberg55b97fe2016-01-28 05:22:45 -08002079 FileFormats format;
2080 const uint32_t notificationTime(0); // Not supported in VoE
2081 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002082
kwiberg55b97fe2016-01-28 05:22:45 -08002083 if ((codecInst != NULL) &&
2084 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2085 _engineStatisticsPtr->SetLastError(
2086 VE_BAD_ARGUMENT, kTraceError,
2087 "StartRecordingPlayout() invalid compression");
2088 return (-1);
2089 }
2090 if (codecInst == NULL) {
2091 format = kFileFormatPcm16kHzFile;
2092 codecInst = &dummyCodec;
2093 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2094 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2095 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2096 format = kFileFormatWavFile;
2097 } else {
2098 format = kFileFormatCompressedFile;
2099 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002100
kwiberg55b97fe2016-01-28 05:22:45 -08002101 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002102
kwiberg55b97fe2016-01-28 05:22:45 -08002103 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002104 if (output_file_recorder_) {
2105 output_file_recorder_->RegisterModuleFileCallback(NULL);
2106 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002107 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002108
kwiberg5a25d952016-08-17 07:31:12 -07002109 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002110 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002111 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002112 _engineStatisticsPtr->SetLastError(
2113 VE_INVALID_ARGUMENT, kTraceError,
2114 "StartRecordingPlayout() fileRecorder format isnot correct");
2115 return -1;
2116 }
2117
kwiberg5a25d952016-08-17 07:31:12 -07002118 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002119 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2120 _engineStatisticsPtr->SetLastError(
2121 VE_BAD_FILE, kTraceError,
2122 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002123 output_file_recorder_->StopRecording();
2124 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002125 return -1;
2126 }
kwiberg5a25d952016-08-17 07:31:12 -07002127 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002128 _outputFileRecording = true;
2129
2130 return 0;
2131}
2132
2133int Channel::StartRecordingPlayout(OutStream* stream,
2134 const CodecInst* codecInst) {
2135 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2136 "Channel::StartRecordingPlayout()");
2137
2138 if (_outputFileRecording) {
2139 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2140 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002141 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002142 }
2143
2144 FileFormats format;
2145 const uint32_t notificationTime(0); // Not supported in VoE
2146 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2147
2148 if (codecInst != NULL && codecInst->channels != 1) {
2149 _engineStatisticsPtr->SetLastError(
2150 VE_BAD_ARGUMENT, kTraceError,
2151 "StartRecordingPlayout() invalid compression");
2152 return (-1);
2153 }
2154 if (codecInst == NULL) {
2155 format = kFileFormatPcm16kHzFile;
2156 codecInst = &dummyCodec;
2157 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2158 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2159 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2160 format = kFileFormatWavFile;
2161 } else {
2162 format = kFileFormatCompressedFile;
2163 }
2164
2165 rtc::CritScope cs(&_fileCritSect);
2166
2167 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002168 if (output_file_recorder_) {
2169 output_file_recorder_->RegisterModuleFileCallback(NULL);
2170 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002171 }
2172
kwiberg5a25d952016-08-17 07:31:12 -07002173 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002174 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002175 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002176 _engineStatisticsPtr->SetLastError(
2177 VE_INVALID_ARGUMENT, kTraceError,
2178 "StartRecordingPlayout() fileRecorder format isnot correct");
2179 return -1;
2180 }
2181
kwiberg4ec01d92016-08-22 08:43:54 -07002182 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002183 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002184 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2185 "StartRecordingPlayout() failed to "
2186 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002187 output_file_recorder_->StopRecording();
2188 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002189 return -1;
2190 }
2191
kwiberg5a25d952016-08-17 07:31:12 -07002192 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002193 _outputFileRecording = true;
2194
2195 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002196}
2197
kwiberg55b97fe2016-01-28 05:22:45 -08002198int Channel::StopRecordingPlayout() {
2199 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2200 "Channel::StopRecordingPlayout()");
2201
2202 if (!_outputFileRecording) {
2203 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2204 "StopRecordingPlayout() isnot recording");
2205 return -1;
2206 }
2207
2208 rtc::CritScope cs(&_fileCritSect);
2209
kwiberg5a25d952016-08-17 07:31:12 -07002210 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002211 _engineStatisticsPtr->SetLastError(
2212 VE_STOP_RECORDING_FAILED, kTraceError,
2213 "StopRecording() could not stop recording");
2214 return (-1);
2215 }
kwiberg5a25d952016-08-17 07:31:12 -07002216 output_file_recorder_->RegisterModuleFileCallback(NULL);
2217 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002218 _outputFileRecording = false;
2219
2220 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002221}
2222
kwiberg55b97fe2016-01-28 05:22:45 -08002223void Channel::SetMixWithMicStatus(bool mix) {
2224 rtc::CritScope cs(&_fileCritSect);
2225 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002226}
2227
kwiberg55b97fe2016-01-28 05:22:45 -08002228int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2229 int8_t currentLevel = _outputAudioLevel.Level();
2230 level = static_cast<int32_t>(currentLevel);
2231 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002232}
2233
kwiberg55b97fe2016-01-28 05:22:45 -08002234int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2235 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2236 level = static_cast<int32_t>(currentLevel);
2237 return 0;
2238}
2239
solenberg1c2af8e2016-03-24 10:36:00 -07002240int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002241 rtc::CritScope cs(&volume_settings_critsect_);
2242 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002243 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002244 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002245 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002246}
2247
solenberg1c2af8e2016-03-24 10:36:00 -07002248bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002249 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002250 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002251}
2252
kwiberg55b97fe2016-01-28 05:22:45 -08002253int Channel::SetOutputVolumePan(float left, float right) {
2254 rtc::CritScope cs(&volume_settings_critsect_);
2255 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002256 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002257 _panLeft = left;
2258 _panRight = right;
2259 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002260}
2261
kwiberg55b97fe2016-01-28 05:22:45 -08002262int Channel::GetOutputVolumePan(float& left, float& right) const {
2263 rtc::CritScope cs(&volume_settings_critsect_);
2264 left = _panLeft;
2265 right = _panRight;
2266 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002267}
2268
kwiberg55b97fe2016-01-28 05:22:45 -08002269int Channel::SetChannelOutputVolumeScaling(float scaling) {
2270 rtc::CritScope cs(&volume_settings_critsect_);
2271 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002272 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002273 _outputGain = scaling;
2274 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002275}
2276
kwiberg55b97fe2016-01-28 05:22:45 -08002277int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2278 rtc::CritScope cs(&volume_settings_critsect_);
2279 scaling = _outputGain;
2280 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002281}
2282
solenberg8842c3e2016-03-11 03:06:41 -08002283int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002284 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002285 "Channel::SendTelephoneEventOutband(...)");
2286 RTC_DCHECK_LE(0, event);
2287 RTC_DCHECK_GE(255, event);
2288 RTC_DCHECK_LE(0, duration_ms);
2289 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002290 if (!Sending()) {
2291 return -1;
2292 }
solenberg8842c3e2016-03-11 03:06:41 -08002293 if (_rtpRtcpModule->SendTelephoneEventOutband(
2294 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002295 _engineStatisticsPtr->SetLastError(
2296 VE_SEND_DTMF_FAILED, kTraceWarning,
2297 "SendTelephoneEventOutband() failed to send event");
2298 return -1;
2299 }
2300 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002301}
2302
solenberg31642aa2016-03-14 08:00:37 -07002303int Channel::SetSendTelephoneEventPayloadType(int payload_type) {
kwiberg55b97fe2016-01-28 05:22:45 -08002304 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002305 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002306 RTC_DCHECK_LE(0, payload_type);
2307 RTC_DCHECK_GE(127, payload_type);
2308 CodecInst codec = {0};
kwiberg55b97fe2016-01-28 05:22:45 -08002309 codec.plfreq = 8000;
solenberg31642aa2016-03-14 08:00:37 -07002310 codec.pltype = payload_type;
kwiberg55b97fe2016-01-28 05:22:45 -08002311 memcpy(codec.plname, "telephone-event", 16);
2312 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2313 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2314 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2315 _engineStatisticsPtr->SetLastError(
2316 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2317 "SetSendTelephoneEventPayloadType() failed to register send"
2318 "payload type");
2319 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002320 }
kwiberg55b97fe2016-01-28 05:22:45 -08002321 }
kwiberg55b97fe2016-01-28 05:22:45 -08002322 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002323}
2324
kwiberg55b97fe2016-01-28 05:22:45 -08002325int Channel::UpdateRxVadDetection(AudioFrame& audioFrame) {
2326 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2327 "Channel::UpdateRxVadDetection()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002328
kwiberg55b97fe2016-01-28 05:22:45 -08002329 int vadDecision = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002330
kwiberg55b97fe2016-01-28 05:22:45 -08002331 vadDecision = (audioFrame.vad_activity_ == AudioFrame::kVadActive) ? 1 : 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002332
kwiberg55b97fe2016-01-28 05:22:45 -08002333 if ((vadDecision != _oldVadDecision) && _rxVadObserverPtr) {
2334 OnRxVadDetected(vadDecision);
2335 _oldVadDecision = vadDecision;
2336 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002337
kwiberg55b97fe2016-01-28 05:22:45 -08002338 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2339 "Channel::UpdateRxVadDetection() => vadDecision=%d",
2340 vadDecision);
2341 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002342}
2343
kwiberg55b97fe2016-01-28 05:22:45 -08002344int Channel::RegisterRxVadObserver(VoERxVadCallback& observer) {
2345 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2346 "Channel::RegisterRxVadObserver()");
2347 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002348
kwiberg55b97fe2016-01-28 05:22:45 -08002349 if (_rxVadObserverPtr) {
2350 _engineStatisticsPtr->SetLastError(
2351 VE_INVALID_OPERATION, kTraceError,
2352 "RegisterRxVadObserver() observer already enabled");
2353 return -1;
2354 }
2355 _rxVadObserverPtr = &observer;
2356 _RxVadDetection = true;
2357 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002358}
2359
kwiberg55b97fe2016-01-28 05:22:45 -08002360int Channel::DeRegisterRxVadObserver() {
2361 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2362 "Channel::DeRegisterRxVadObserver()");
2363 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002364
kwiberg55b97fe2016-01-28 05:22:45 -08002365 if (!_rxVadObserverPtr) {
2366 _engineStatisticsPtr->SetLastError(
2367 VE_INVALID_OPERATION, kTraceWarning,
2368 "DeRegisterRxVadObserver() observer already disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00002369 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002370 }
2371 _rxVadObserverPtr = NULL;
2372 _RxVadDetection = false;
2373 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002374}
2375
kwiberg55b97fe2016-01-28 05:22:45 -08002376int Channel::VoiceActivityIndicator(int& activity) {
2377 activity = _sendFrameType;
2378 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002379}
2380
2381#ifdef WEBRTC_VOICE_ENGINE_AGC
2382
kwiberg55b97fe2016-01-28 05:22:45 -08002383int Channel::SetRxAgcStatus(bool enable, AgcModes mode) {
2384 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2385 "Channel::SetRxAgcStatus(enable=%d, mode=%d)", (int)enable,
2386 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002387
kwiberg55b97fe2016-01-28 05:22:45 -08002388 GainControl::Mode agcMode = kDefaultRxAgcMode;
2389 switch (mode) {
2390 case kAgcDefault:
2391 break;
2392 case kAgcUnchanged:
2393 agcMode = rx_audioproc_->gain_control()->mode();
2394 break;
2395 case kAgcFixedDigital:
2396 agcMode = GainControl::kFixedDigital;
2397 break;
2398 case kAgcAdaptiveDigital:
2399 agcMode = GainControl::kAdaptiveDigital;
2400 break;
2401 default:
2402 _engineStatisticsPtr->SetLastError(VE_INVALID_ARGUMENT, kTraceError,
2403 "SetRxAgcStatus() invalid Agc mode");
2404 return -1;
2405 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002406
kwiberg55b97fe2016-01-28 05:22:45 -08002407 if (rx_audioproc_->gain_control()->set_mode(agcMode) != 0) {
2408 _engineStatisticsPtr->SetLastError(
2409 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc mode");
2410 return -1;
2411 }
2412 if (rx_audioproc_->gain_control()->Enable(enable) != 0) {
2413 _engineStatisticsPtr->SetLastError(
2414 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc state");
2415 return -1;
2416 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002417
kwiberg55b97fe2016-01-28 05:22:45 -08002418 _rxAgcIsEnabled = enable;
2419 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002420
kwiberg55b97fe2016-01-28 05:22:45 -08002421 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002422}
2423
kwiberg55b97fe2016-01-28 05:22:45 -08002424int Channel::GetRxAgcStatus(bool& enabled, AgcModes& mode) {
2425 bool enable = rx_audioproc_->gain_control()->is_enabled();
2426 GainControl::Mode agcMode = rx_audioproc_->gain_control()->mode();
niklase@google.com470e71d2011-07-07 08:21:25 +00002427
kwiberg55b97fe2016-01-28 05:22:45 -08002428 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002429
kwiberg55b97fe2016-01-28 05:22:45 -08002430 switch (agcMode) {
2431 case GainControl::kFixedDigital:
2432 mode = kAgcFixedDigital;
2433 break;
2434 case GainControl::kAdaptiveDigital:
2435 mode = kAgcAdaptiveDigital;
2436 break;
2437 default:
2438 _engineStatisticsPtr->SetLastError(VE_APM_ERROR, kTraceError,
2439 "GetRxAgcStatus() invalid Agc mode");
2440 return -1;
2441 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002442
kwiberg55b97fe2016-01-28 05:22:45 -08002443 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002444}
2445
kwiberg55b97fe2016-01-28 05:22:45 -08002446int Channel::SetRxAgcConfig(AgcConfig config) {
2447 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2448 "Channel::SetRxAgcConfig()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002449
kwiberg55b97fe2016-01-28 05:22:45 -08002450 if (rx_audioproc_->gain_control()->set_target_level_dbfs(
2451 config.targetLeveldBOv) != 0) {
2452 _engineStatisticsPtr->SetLastError(
2453 VE_APM_ERROR, kTraceError,
2454 "SetRxAgcConfig() failed to set target peak |level|"
2455 "(or envelope) of the Agc");
2456 return -1;
2457 }
2458 if (rx_audioproc_->gain_control()->set_compression_gain_db(
2459 config.digitalCompressionGaindB) != 0) {
2460 _engineStatisticsPtr->SetLastError(
2461 VE_APM_ERROR, kTraceError,
2462 "SetRxAgcConfig() failed to set the range in |gain| the"
2463 " digital compression stage may apply");
2464 return -1;
2465 }
2466 if (rx_audioproc_->gain_control()->enable_limiter(config.limiterEnable) !=
2467 0) {
2468 _engineStatisticsPtr->SetLastError(
2469 VE_APM_ERROR, kTraceError,
2470 "SetRxAgcConfig() failed to set hard limiter to the signal");
2471 return -1;
2472 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002473
kwiberg55b97fe2016-01-28 05:22:45 -08002474 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002475}
2476
kwiberg55b97fe2016-01-28 05:22:45 -08002477int Channel::GetRxAgcConfig(AgcConfig& config) {
2478 config.targetLeveldBOv = rx_audioproc_->gain_control()->target_level_dbfs();
2479 config.digitalCompressionGaindB =
2480 rx_audioproc_->gain_control()->compression_gain_db();
2481 config.limiterEnable = rx_audioproc_->gain_control()->is_limiter_enabled();
niklase@google.com470e71d2011-07-07 08:21:25 +00002482
kwiberg55b97fe2016-01-28 05:22:45 -08002483 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002484}
2485
kwiberg55b97fe2016-01-28 05:22:45 -08002486#endif // #ifdef WEBRTC_VOICE_ENGINE_AGC
niklase@google.com470e71d2011-07-07 08:21:25 +00002487
2488#ifdef WEBRTC_VOICE_ENGINE_NR
2489
kwiberg55b97fe2016-01-28 05:22:45 -08002490int Channel::SetRxNsStatus(bool enable, NsModes mode) {
2491 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2492 "Channel::SetRxNsStatus(enable=%d, mode=%d)", (int)enable,
2493 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002494
kwiberg55b97fe2016-01-28 05:22:45 -08002495 NoiseSuppression::Level nsLevel = kDefaultNsMode;
2496 switch (mode) {
2497 case kNsDefault:
2498 break;
2499 case kNsUnchanged:
2500 nsLevel = rx_audioproc_->noise_suppression()->level();
2501 break;
2502 case kNsConference:
2503 nsLevel = NoiseSuppression::kHigh;
2504 break;
2505 case kNsLowSuppression:
2506 nsLevel = NoiseSuppression::kLow;
2507 break;
2508 case kNsModerateSuppression:
2509 nsLevel = NoiseSuppression::kModerate;
2510 break;
2511 case kNsHighSuppression:
2512 nsLevel = NoiseSuppression::kHigh;
2513 break;
2514 case kNsVeryHighSuppression:
2515 nsLevel = NoiseSuppression::kVeryHigh;
2516 break;
2517 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002518
kwiberg55b97fe2016-01-28 05:22:45 -08002519 if (rx_audioproc_->noise_suppression()->set_level(nsLevel) != 0) {
2520 _engineStatisticsPtr->SetLastError(
2521 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS level");
2522 return -1;
2523 }
2524 if (rx_audioproc_->noise_suppression()->Enable(enable) != 0) {
2525 _engineStatisticsPtr->SetLastError(
2526 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS state");
2527 return -1;
2528 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002529
kwiberg55b97fe2016-01-28 05:22:45 -08002530 _rxNsIsEnabled = enable;
2531 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002532
kwiberg55b97fe2016-01-28 05:22:45 -08002533 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002534}
2535
kwiberg55b97fe2016-01-28 05:22:45 -08002536int Channel::GetRxNsStatus(bool& enabled, NsModes& mode) {
2537 bool enable = rx_audioproc_->noise_suppression()->is_enabled();
2538 NoiseSuppression::Level ncLevel = rx_audioproc_->noise_suppression()->level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002539
kwiberg55b97fe2016-01-28 05:22:45 -08002540 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002541
kwiberg55b97fe2016-01-28 05:22:45 -08002542 switch (ncLevel) {
2543 case NoiseSuppression::kLow:
2544 mode = kNsLowSuppression;
2545 break;
2546 case NoiseSuppression::kModerate:
2547 mode = kNsModerateSuppression;
2548 break;
2549 case NoiseSuppression::kHigh:
2550 mode = kNsHighSuppression;
2551 break;
2552 case NoiseSuppression::kVeryHigh:
2553 mode = kNsVeryHighSuppression;
2554 break;
2555 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002556
kwiberg55b97fe2016-01-28 05:22:45 -08002557 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002558}
2559
kwiberg55b97fe2016-01-28 05:22:45 -08002560#endif // #ifdef WEBRTC_VOICE_ENGINE_NR
niklase@google.com470e71d2011-07-07 08:21:25 +00002561
kwiberg55b97fe2016-01-28 05:22:45 -08002562int Channel::SetLocalSSRC(unsigned int ssrc) {
2563 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2564 "Channel::SetLocalSSRC()");
2565 if (channel_state_.Get().sending) {
2566 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2567 "SetLocalSSRC() already sending");
2568 return -1;
2569 }
2570 _rtpRtcpModule->SetSSRC(ssrc);
2571 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002572}
2573
kwiberg55b97fe2016-01-28 05:22:45 -08002574int Channel::GetLocalSSRC(unsigned int& ssrc) {
2575 ssrc = _rtpRtcpModule->SSRC();
2576 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002577}
2578
kwiberg55b97fe2016-01-28 05:22:45 -08002579int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2580 ssrc = rtp_receiver_->SSRC();
2581 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002582}
2583
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002584int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002585 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002586 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002587}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002588
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002589int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2590 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002591 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2592 if (enable &&
2593 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2594 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002595 return -1;
2596 }
2597 return 0;
2598}
2599
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002600int Channel::SetSendAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2601 return SetSendRtpHeaderExtension(enable, kRtpExtensionAbsoluteSendTime, id);
2602}
2603
2604int Channel::SetReceiveAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2605 rtp_header_parser_->DeregisterRtpHeaderExtension(
2606 kRtpExtensionAbsoluteSendTime);
kwiberg55b97fe2016-01-28 05:22:45 -08002607 if (enable &&
2608 !rtp_header_parser_->RegisterRtpHeaderExtension(
2609 kRtpExtensionAbsoluteSendTime, id)) {
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00002610 return -1;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002611 }
2612 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002613}
2614
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002615void Channel::EnableSendTransportSequenceNumber(int id) {
2616 int ret =
2617 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2618 RTC_DCHECK_EQ(0, ret);
2619}
2620
stefan3313ec92016-01-21 06:32:43 -08002621void Channel::EnableReceiveTransportSequenceNumber(int id) {
2622 rtp_header_parser_->DeregisterRtpHeaderExtension(
2623 kRtpExtensionTransportSequenceNumber);
2624 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2625 kRtpExtensionTransportSequenceNumber, id);
2626 RTC_DCHECK(ret);
2627}
2628
stefanbba9dec2016-02-01 04:39:55 -08002629void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002630 RtpPacketSender* rtp_packet_sender,
2631 TransportFeedbackObserver* transport_feedback_observer,
2632 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002633 RTC_DCHECK(rtp_packet_sender);
2634 RTC_DCHECK(transport_feedback_observer);
2635 RTC_DCHECK(packet_router && !packet_router_);
2636 feedback_observer_proxy_->SetTransportFeedbackObserver(
2637 transport_feedback_observer);
2638 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2639 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2640 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002641 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002642 packet_router_ = packet_router;
2643}
2644
stefanbba9dec2016-02-01 04:39:55 -08002645void Channel::RegisterReceiverCongestionControlObjects(
2646 PacketRouter* packet_router) {
2647 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002648 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002649 packet_router_ = packet_router;
2650}
2651
2652void Channel::ResetCongestionControlObjects() {
2653 RTC_DCHECK(packet_router_);
2654 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2655 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2656 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002657 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002658 packet_router_ = nullptr;
2659 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2660}
2661
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002662void Channel::SetRTCPStatus(bool enable) {
2663 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2664 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002665 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002666}
2667
kwiberg55b97fe2016-01-28 05:22:45 -08002668int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002669 RtcpMode method = _rtpRtcpModule->RTCP();
2670 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002671 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002672}
2673
kwiberg55b97fe2016-01-28 05:22:45 -08002674int Channel::SetRTCP_CNAME(const char cName[256]) {
2675 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2676 "Channel::SetRTCP_CNAME()");
2677 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2678 _engineStatisticsPtr->SetLastError(
2679 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2680 "SetRTCP_CNAME() failed to set RTCP CNAME");
2681 return -1;
2682 }
2683 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002684}
2685
kwiberg55b97fe2016-01-28 05:22:45 -08002686int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2687 if (cName == NULL) {
2688 _engineStatisticsPtr->SetLastError(
2689 VE_INVALID_ARGUMENT, kTraceError,
2690 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2691 return -1;
2692 }
2693 char cname[RTCP_CNAME_SIZE];
2694 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2695 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2696 _engineStatisticsPtr->SetLastError(
2697 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2698 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2699 return -1;
2700 }
2701 strcpy(cName, cname);
2702 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002703}
2704
kwiberg55b97fe2016-01-28 05:22:45 -08002705int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2706 unsigned int& NTPLow,
2707 unsigned int& timestamp,
2708 unsigned int& playoutTimestamp,
2709 unsigned int* jitter,
2710 unsigned short* fractionLost) {
2711 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002712
kwiberg55b97fe2016-01-28 05:22:45 -08002713 RTCPSenderInfo senderInfo;
2714 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2715 _engineStatisticsPtr->SetLastError(
2716 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2717 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2718 "side");
2719 return -1;
2720 }
2721
2722 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2723 // and octet count)
2724 NTPHigh = senderInfo.NTPseconds;
2725 NTPLow = senderInfo.NTPfraction;
2726 timestamp = senderInfo.RTPtimeStamp;
2727
2728 // --- Locally derived information
2729
2730 // This value is updated on each incoming RTCP packet (0 when no packet
2731 // has been received)
2732 playoutTimestamp = playout_timestamp_rtcp_;
2733
2734 if (NULL != jitter || NULL != fractionLost) {
2735 // Get all RTCP receiver report blocks that have been received on this
2736 // channel. If we receive RTP packets from a remote source we know the
2737 // remote SSRC and use the report block from him.
2738 // Otherwise use the first report block.
2739 std::vector<RTCPReportBlock> remote_stats;
2740 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2741 remote_stats.empty()) {
2742 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2743 "GetRemoteRTCPData() failed to measure statistics due"
2744 " to lack of received RTP and/or RTCP packets");
2745 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002746 }
2747
kwiberg55b97fe2016-01-28 05:22:45 -08002748 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2749 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2750 for (; it != remote_stats.end(); ++it) {
2751 if (it->remoteSSRC == remoteSSRC)
2752 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002753 }
kwiberg55b97fe2016-01-28 05:22:45 -08002754
2755 if (it == remote_stats.end()) {
2756 // If we have not received any RTCP packets from this SSRC it probably
2757 // means that we have not received any RTP packets.
2758 // Use the first received report block instead.
2759 it = remote_stats.begin();
2760 remoteSSRC = it->remoteSSRC;
2761 }
2762
2763 if (jitter) {
2764 *jitter = it->jitter;
2765 }
2766
2767 if (fractionLost) {
2768 *fractionLost = it->fractionLost;
2769 }
2770 }
2771 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002772}
2773
kwiberg55b97fe2016-01-28 05:22:45 -08002774int Channel::SendApplicationDefinedRTCPPacket(
2775 unsigned char subType,
2776 unsigned int name,
2777 const char* data,
2778 unsigned short dataLengthInBytes) {
2779 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2780 "Channel::SendApplicationDefinedRTCPPacket()");
2781 if (!channel_state_.Get().sending) {
2782 _engineStatisticsPtr->SetLastError(
2783 VE_NOT_SENDING, kTraceError,
2784 "SendApplicationDefinedRTCPPacket() not sending");
2785 return -1;
2786 }
2787 if (NULL == data) {
2788 _engineStatisticsPtr->SetLastError(
2789 VE_INVALID_ARGUMENT, kTraceError,
2790 "SendApplicationDefinedRTCPPacket() invalid data value");
2791 return -1;
2792 }
2793 if (dataLengthInBytes % 4 != 0) {
2794 _engineStatisticsPtr->SetLastError(
2795 VE_INVALID_ARGUMENT, kTraceError,
2796 "SendApplicationDefinedRTCPPacket() invalid length value");
2797 return -1;
2798 }
2799 RtcpMode status = _rtpRtcpModule->RTCP();
2800 if (status == RtcpMode::kOff) {
2801 _engineStatisticsPtr->SetLastError(
2802 VE_RTCP_ERROR, kTraceError,
2803 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2804 return -1;
2805 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002806
kwiberg55b97fe2016-01-28 05:22:45 -08002807 // Create and schedule the RTCP APP packet for transmission
2808 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2809 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2810 _engineStatisticsPtr->SetLastError(
2811 VE_SEND_ERROR, kTraceError,
2812 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2813 return -1;
2814 }
2815 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002816}
2817
kwiberg55b97fe2016-01-28 05:22:45 -08002818int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2819 unsigned int& maxJitterMs,
2820 unsigned int& discardedPackets) {
2821 // The jitter statistics is updated for each received RTP packet and is
2822 // based on received packets.
2823 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2824 // If RTCP is off, there is no timed thread in the RTCP module regularly
2825 // generating new stats, trigger the update manually here instead.
2826 StreamStatistician* statistician =
2827 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2828 if (statistician) {
2829 // Don't use returned statistics, use data from proxy instead so that
2830 // max jitter can be fetched atomically.
2831 RtcpStatistics s;
2832 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002833 }
kwiberg55b97fe2016-01-28 05:22:45 -08002834 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002835
kwiberg55b97fe2016-01-28 05:22:45 -08002836 ChannelStatistics stats = statistics_proxy_->GetStats();
2837 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2838 if (playoutFrequency > 0) {
2839 // Scale RTP statistics given the current playout frequency
2840 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2841 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2842 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002843
kwiberg55b97fe2016-01-28 05:22:45 -08002844 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002845
kwiberg55b97fe2016-01-28 05:22:45 -08002846 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002847}
2848
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002849int Channel::GetRemoteRTCPReportBlocks(
2850 std::vector<ReportBlock>* report_blocks) {
2851 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002852 _engineStatisticsPtr->SetLastError(
2853 VE_INVALID_ARGUMENT, kTraceError,
2854 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002855 return -1;
2856 }
2857
2858 // Get the report blocks from the latest received RTCP Sender or Receiver
2859 // Report. Each element in the vector contains the sender's SSRC and a
2860 // report block according to RFC 3550.
2861 std::vector<RTCPReportBlock> rtcp_report_blocks;
2862 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002863 return -1;
2864 }
2865
2866 if (rtcp_report_blocks.empty())
2867 return 0;
2868
2869 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2870 for (; it != rtcp_report_blocks.end(); ++it) {
2871 ReportBlock report_block;
2872 report_block.sender_SSRC = it->remoteSSRC;
2873 report_block.source_SSRC = it->sourceSSRC;
2874 report_block.fraction_lost = it->fractionLost;
2875 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2876 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2877 report_block.interarrival_jitter = it->jitter;
2878 report_block.last_SR_timestamp = it->lastSR;
2879 report_block.delay_since_last_SR = it->delaySinceLastSR;
2880 report_blocks->push_back(report_block);
2881 }
2882 return 0;
2883}
2884
kwiberg55b97fe2016-01-28 05:22:45 -08002885int Channel::GetRTPStatistics(CallStatistics& stats) {
2886 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002887
kwiberg55b97fe2016-01-28 05:22:45 -08002888 // The jitter statistics is updated for each received RTP packet and is
2889 // based on received packets.
2890 RtcpStatistics statistics;
2891 StreamStatistician* statistician =
2892 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002893 if (statistician) {
2894 statistician->GetStatistics(&statistics,
2895 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002896 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002897
kwiberg55b97fe2016-01-28 05:22:45 -08002898 stats.fractionLost = statistics.fraction_lost;
2899 stats.cumulativeLost = statistics.cumulative_lost;
2900 stats.extendedMax = statistics.extended_max_sequence_number;
2901 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002902
kwiberg55b97fe2016-01-28 05:22:45 -08002903 // --- RTT
2904 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002905
kwiberg55b97fe2016-01-28 05:22:45 -08002906 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002907
kwiberg55b97fe2016-01-28 05:22:45 -08002908 size_t bytesSent(0);
2909 uint32_t packetsSent(0);
2910 size_t bytesReceived(0);
2911 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002912
kwiberg55b97fe2016-01-28 05:22:45 -08002913 if (statistician) {
2914 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2915 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002916
kwiberg55b97fe2016-01-28 05:22:45 -08002917 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2918 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2919 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2920 " output will not be complete");
2921 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002922
kwiberg55b97fe2016-01-28 05:22:45 -08002923 stats.bytesSent = bytesSent;
2924 stats.packetsSent = packetsSent;
2925 stats.bytesReceived = bytesReceived;
2926 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002927
kwiberg55b97fe2016-01-28 05:22:45 -08002928 // --- Timestamps
2929 {
2930 rtc::CritScope lock(&ts_stats_lock_);
2931 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2932 }
2933 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002934}
2935
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002936int Channel::SetCodecFECStatus(bool enable) {
2937 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2938 "Channel::SetCodecFECStatus()");
2939
kwibergc8d071e2016-04-06 12:22:38 -07002940 if (!codec_manager_.SetCodecFEC(enable) ||
2941 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002942 _engineStatisticsPtr->SetLastError(
2943 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2944 "SetCodecFECStatus() failed to set FEC state");
2945 return -1;
2946 }
2947 return 0;
2948}
2949
2950bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002951 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002952}
2953
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002954void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2955 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002956 // If pacing is enabled we always store packets.
2957 if (!pacing_enabled_)
2958 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002959 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002960 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002961 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002962 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002963 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002964}
2965
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002966// Called when we are missing one or more packets.
2967int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002968 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2969}
2970
kwiberg55b97fe2016-01-28 05:22:45 -08002971uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2972 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2973 "Channel::Demultiplex()");
2974 _audioFrame.CopyFrom(audioFrame);
2975 _audioFrame.id_ = _channelId;
2976 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002977}
2978
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002979void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002980 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002981 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002982 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002983 CodecInst codec;
2984 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002985
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002986 // Never upsample or upmix the capture signal here. This should be done at the
2987 // end of the send chain.
2988 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2989 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2990 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2991 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002992}
2993
kwiberg55b97fe2016-01-28 05:22:45 -08002994uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2995 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2996 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002997
kwiberg55b97fe2016-01-28 05:22:45 -08002998 if (_audioFrame.samples_per_channel_ == 0) {
2999 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3000 "Channel::PrepareEncodeAndSend() invalid audio frame");
3001 return 0xFFFFFFFF;
3002 }
3003
3004 if (channel_state_.Get().input_file_playing) {
3005 MixOrReplaceAudioWithFile(mixingFrequency);
3006 }
3007
solenberg1c2af8e2016-03-24 10:36:00 -07003008 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
3009 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08003010
3011 if (channel_state_.Get().input_external_media) {
3012 rtc::CritScope cs(&_callbackCritSect);
3013 const bool isStereo = (_audioFrame.num_channels_ == 2);
3014 if (_inputExternalMediaCallbackPtr) {
3015 _inputExternalMediaCallbackPtr->Process(
3016 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
3017 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
3018 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00003019 }
kwiberg55b97fe2016-01-28 05:22:45 -08003020 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003021
kwiberg55b97fe2016-01-28 05:22:45 -08003022 if (_includeAudioLevelIndication) {
3023 size_t length =
3024 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02003025 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07003026 if (is_muted && previous_frame_muted_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003027 rms_level_.ProcessMuted(length);
3028 } else {
3029 rms_level_.Process(_audioFrame.data_, length);
niklase@google.com470e71d2011-07-07 08:21:25 +00003030 }
kwiberg55b97fe2016-01-28 05:22:45 -08003031 }
solenberg1c2af8e2016-03-24 10:36:00 -07003032 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00003033
kwiberg55b97fe2016-01-28 05:22:45 -08003034 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003035}
3036
kwiberg55b97fe2016-01-28 05:22:45 -08003037uint32_t Channel::EncodeAndSend() {
3038 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
3039 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003040
kwiberg55b97fe2016-01-28 05:22:45 -08003041 assert(_audioFrame.num_channels_ <= 2);
3042 if (_audioFrame.samples_per_channel_ == 0) {
3043 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3044 "Channel::EncodeAndSend() invalid audio frame");
3045 return 0xFFFFFFFF;
3046 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003047
kwiberg55b97fe2016-01-28 05:22:45 -08003048 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00003049
kwiberg55b97fe2016-01-28 05:22:45 -08003050 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00003051
kwiberg55b97fe2016-01-28 05:22:45 -08003052 // The ACM resamples internally.
3053 _audioFrame.timestamp_ = _timeStamp;
3054 // This call will trigger AudioPacketizationCallback::SendData if encoding
3055 // is done and payload is ready for packetization and transmission.
3056 // Otherwise, it will return without invoking the callback.
3057 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
3058 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
3059 "Channel::EncodeAndSend() ACM encoding failed");
3060 return 0xFFFFFFFF;
3061 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003062
kwiberg55b97fe2016-01-28 05:22:45 -08003063 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
3064 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003065}
3066
Minyue2013aec2015-05-13 14:14:42 +02003067void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08003068 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003069 Channel* channel = associate_send_channel_.channel();
3070 if (channel && channel->ChannelId() == channel_id) {
3071 // If this channel is associated with a send channel of the specified
3072 // Channel ID, disassociate with it.
3073 ChannelOwner ref(NULL);
3074 associate_send_channel_ = ref;
3075 }
3076}
3077
ivoc14d5dbe2016-07-04 07:06:55 -07003078void Channel::SetRtcEventLog(RtcEventLog* event_log) {
3079 event_log_proxy_->SetEventLog(event_log);
3080}
3081
kwiberg55b97fe2016-01-28 05:22:45 -08003082int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
3083 VoEMediaProcess& processObject) {
3084 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3085 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003086
kwiberg55b97fe2016-01-28 05:22:45 -08003087 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003088
kwiberg55b97fe2016-01-28 05:22:45 -08003089 if (kPlaybackPerChannel == type) {
3090 if (_outputExternalMediaCallbackPtr) {
3091 _engineStatisticsPtr->SetLastError(
3092 VE_INVALID_OPERATION, kTraceError,
3093 "Channel::RegisterExternalMediaProcessing() "
3094 "output external media already enabled");
3095 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003096 }
kwiberg55b97fe2016-01-28 05:22:45 -08003097 _outputExternalMediaCallbackPtr = &processObject;
3098 _outputExternalMedia = true;
3099 } else if (kRecordingPerChannel == type) {
3100 if (_inputExternalMediaCallbackPtr) {
3101 _engineStatisticsPtr->SetLastError(
3102 VE_INVALID_OPERATION, kTraceError,
3103 "Channel::RegisterExternalMediaProcessing() "
3104 "output external media already enabled");
3105 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003106 }
kwiberg55b97fe2016-01-28 05:22:45 -08003107 _inputExternalMediaCallbackPtr = &processObject;
3108 channel_state_.SetInputExternalMedia(true);
3109 }
3110 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003111}
3112
kwiberg55b97fe2016-01-28 05:22:45 -08003113int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
3114 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3115 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003116
kwiberg55b97fe2016-01-28 05:22:45 -08003117 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003118
kwiberg55b97fe2016-01-28 05:22:45 -08003119 if (kPlaybackPerChannel == type) {
3120 if (!_outputExternalMediaCallbackPtr) {
3121 _engineStatisticsPtr->SetLastError(
3122 VE_INVALID_OPERATION, kTraceWarning,
3123 "Channel::DeRegisterExternalMediaProcessing() "
3124 "output external media already disabled");
3125 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003126 }
kwiberg55b97fe2016-01-28 05:22:45 -08003127 _outputExternalMedia = false;
3128 _outputExternalMediaCallbackPtr = NULL;
3129 } else if (kRecordingPerChannel == type) {
3130 if (!_inputExternalMediaCallbackPtr) {
3131 _engineStatisticsPtr->SetLastError(
3132 VE_INVALID_OPERATION, kTraceWarning,
3133 "Channel::DeRegisterExternalMediaProcessing() "
3134 "input external media already disabled");
3135 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003136 }
kwiberg55b97fe2016-01-28 05:22:45 -08003137 channel_state_.SetInputExternalMedia(false);
3138 _inputExternalMediaCallbackPtr = NULL;
3139 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003140
kwiberg55b97fe2016-01-28 05:22:45 -08003141 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003142}
3143
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003144int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08003145 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3146 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003147
kwiberg55b97fe2016-01-28 05:22:45 -08003148 if (channel_state_.Get().playing) {
3149 _engineStatisticsPtr->SetLastError(
3150 VE_INVALID_OPERATION, kTraceError,
3151 "Channel::SetExternalMixing() "
3152 "external mixing cannot be changed while playing.");
3153 return -1;
3154 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003155
kwiberg55b97fe2016-01-28 05:22:45 -08003156 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003157
kwiberg55b97fe2016-01-28 05:22:45 -08003158 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003159}
3160
kwiberg55b97fe2016-01-28 05:22:45 -08003161int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3162 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003163}
3164
wu@webrtc.org24301a62013-12-13 19:17:43 +00003165void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3166 audio_coding_->GetDecodingCallStatistics(stats);
3167}
3168
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003169bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3170 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003171 rtc::CritScope lock(&video_sync_lock_);
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07003172 *jitter_buffer_delay_ms = audio_coding_->FilteredCurrentDelayMs();
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003173 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003174 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003175}
3176
solenberg358057b2015-11-27 10:46:42 -08003177uint32_t Channel::GetDelayEstimate() const {
3178 int jitter_buffer_delay_ms = 0;
3179 int playout_buffer_delay_ms = 0;
3180 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3181 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3182}
3183
deadbeef74375882015-08-13 12:09:10 -07003184int Channel::LeastRequiredDelayMs() const {
3185 return audio_coding_->LeastRequiredDelayMs();
3186}
3187
kwiberg55b97fe2016-01-28 05:22:45 -08003188int Channel::SetMinimumPlayoutDelay(int delayMs) {
3189 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3190 "Channel::SetMinimumPlayoutDelay()");
3191 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3192 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3193 _engineStatisticsPtr->SetLastError(
3194 VE_INVALID_ARGUMENT, kTraceError,
3195 "SetMinimumPlayoutDelay() invalid min delay");
3196 return -1;
3197 }
3198 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3199 _engineStatisticsPtr->SetLastError(
3200 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3201 "SetMinimumPlayoutDelay() failed to set min playout delay");
3202 return -1;
3203 }
3204 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003205}
3206
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003207int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003208 uint32_t playout_timestamp_rtp = 0;
3209 {
tommi31fc21f2016-01-21 10:37:37 -08003210 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003211 playout_timestamp_rtp = playout_timestamp_rtp_;
3212 }
kwiberg55b97fe2016-01-28 05:22:45 -08003213 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003214 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07003215 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003216 "GetPlayoutTimestamp() failed to retrieve timestamp");
3217 return -1;
3218 }
deadbeef74375882015-08-13 12:09:10 -07003219 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003220 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003221}
3222
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003223int Channel::SetInitTimestamp(unsigned int timestamp) {
3224 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003225 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003226 if (channel_state_.Get().sending) {
3227 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3228 "SetInitTimestamp() already sending");
3229 return -1;
3230 }
3231 _rtpRtcpModule->SetStartTimestamp(timestamp);
3232 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003233}
3234
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003235int Channel::SetInitSequenceNumber(short sequenceNumber) {
3236 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3237 "Channel::SetInitSequenceNumber()");
3238 if (channel_state_.Get().sending) {
3239 _engineStatisticsPtr->SetLastError(
3240 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3241 return -1;
3242 }
3243 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3244 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003245}
3246
kwiberg55b97fe2016-01-28 05:22:45 -08003247int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3248 RtpReceiver** rtp_receiver) const {
3249 *rtpRtcpModule = _rtpRtcpModule.get();
3250 *rtp_receiver = rtp_receiver_.get();
3251 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003252}
3253
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003254// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3255// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003256int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003257 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003258 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003259
kwiberg55b97fe2016-01-28 05:22:45 -08003260 {
3261 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003262
kwiberg5a25d952016-08-17 07:31:12 -07003263 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003264 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3265 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3266 " doesnt exist");
3267 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003268 }
3269
kwiberg4ec01d92016-08-22 08:43:54 -07003270 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07003271 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003272 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3273 "Channel::MixOrReplaceAudioWithFile() file mixing "
3274 "failed");
3275 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003276 }
kwiberg55b97fe2016-01-28 05:22:45 -08003277 if (fileSamples == 0) {
3278 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3279 "Channel::MixOrReplaceAudioWithFile() file is ended");
3280 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003281 }
kwiberg55b97fe2016-01-28 05:22:45 -08003282 }
3283
3284 assert(_audioFrame.samples_per_channel_ == fileSamples);
3285
3286 if (_mixFileWithMicrophone) {
3287 // Currently file stream is always mono.
3288 // TODO(xians): Change the code when FilePlayer supports real stereo.
3289 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3290 1, fileSamples);
3291 } else {
3292 // Replace ACM audio with file.
3293 // Currently file stream is always mono.
3294 // TODO(xians): Change the code when FilePlayer supports real stereo.
3295 _audioFrame.UpdateFrame(
3296 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3297 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3298 }
3299 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003300}
3301
kwiberg55b97fe2016-01-28 05:22:45 -08003302int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3303 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003304
kwibergb7f89d62016-02-17 10:04:18 -08003305 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003306 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003307
kwiberg55b97fe2016-01-28 05:22:45 -08003308 {
3309 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003310
kwiberg5a25d952016-08-17 07:31:12 -07003311 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003312 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3313 "Channel::MixAudioWithFile() file mixing failed");
3314 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003315 }
3316
kwiberg55b97fe2016-01-28 05:22:45 -08003317 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07003318 if (output_file_player_->Get10msAudioFromFile(
3319 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003320 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3321 "Channel::MixAudioWithFile() file mixing failed");
3322 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003323 }
kwiberg55b97fe2016-01-28 05:22:45 -08003324 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003325
kwiberg55b97fe2016-01-28 05:22:45 -08003326 if (audioFrame.samples_per_channel_ == fileSamples) {
3327 // Currently file stream is always mono.
3328 // TODO(xians): Change the code when FilePlayer supports real stereo.
3329 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3330 fileSamples);
3331 } else {
3332 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3333 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3334 ") != "
3335 "fileSamples(%" PRIuS ")",
3336 audioFrame.samples_per_channel_, fileSamples);
3337 return -1;
3338 }
3339
3340 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003341}
3342
deadbeef74375882015-08-13 12:09:10 -07003343void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003344 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003345
henrik.lundin96bd5022016-04-06 04:13:56 -07003346 if (!jitter_buffer_playout_timestamp_) {
3347 // This can happen if this channel has not received any RTP packets. In
3348 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003349 return;
3350 }
3351
3352 uint16_t delay_ms = 0;
3353 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003354 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003355 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3356 " delay from the ADM");
3357 _engineStatisticsPtr->SetLastError(
3358 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3359 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3360 return;
3361 }
3362
henrik.lundin96bd5022016-04-06 04:13:56 -07003363 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3364 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003365
3366 // Remove the playout delay.
henrik.lundin96bd5022016-04-06 04:13:56 -07003367 playout_timestamp -= (delay_ms * (GetPlayoutFrequency() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003368
kwiberg55b97fe2016-01-28 05:22:45 -08003369 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003370 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003371 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003372
3373 {
tommi31fc21f2016-01-21 10:37:37 -08003374 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003375 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003376 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003377 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003378 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003379 }
3380 playout_delay_ms_ = delay_ms;
3381 }
3382}
3383
kwiberg55b97fe2016-01-28 05:22:45 -08003384void Channel::RegisterReceiveCodecsToRTPModule() {
3385 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3386 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003387
kwiberg55b97fe2016-01-28 05:22:45 -08003388 CodecInst codec;
3389 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003390
kwiberg55b97fe2016-01-28 05:22:45 -08003391 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3392 // Open up the RTP/RTCP receiver for all supported codecs
3393 if ((audio_coding_->Codec(idx, &codec) == -1) ||
3394 (rtp_receiver_->RegisterReceivePayload(
3395 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3396 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
3397 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3398 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3399 " to register %s (%d/%d/%" PRIuS
3400 "/%d) to RTP/RTCP "
3401 "receiver",
3402 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3403 codec.rate);
3404 } else {
3405 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3406 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3407 "(%d/%d/%" PRIuS
3408 "/%d) has been added to the RTP/RTCP "
3409 "receiver",
3410 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3411 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003412 }
kwiberg55b97fe2016-01-28 05:22:45 -08003413 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003414}
3415
kwiberg55b97fe2016-01-28 05:22:45 -08003416int Channel::SetSendRtpHeaderExtension(bool enable,
3417 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003418 unsigned char id) {
3419 int error = 0;
3420 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3421 if (enable) {
3422 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3423 }
3424 return error;
3425}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003426
henrik.lundinb3e30012016-08-31 14:09:51 -07003427int32_t Channel::GetPlayoutFrequency() const {
wu@webrtc.org94454b72014-06-05 20:34:08 +00003428 int32_t playout_frequency = audio_coding_->PlayoutFrequency();
3429 CodecInst current_recive_codec;
3430 if (audio_coding_->ReceiveCodec(&current_recive_codec) == 0) {
3431 if (STR_CASE_CMP("G722", current_recive_codec.plname) == 0) {
3432 // Even though the actual sampling rate for G.722 audio is
3433 // 16,000 Hz, the RTP clock rate for the G722 payload format is
3434 // 8,000 Hz because that value was erroneously assigned in
3435 // RFC 1890 and must remain unchanged for backward compatibility.
3436 playout_frequency = 8000;
3437 } else if (STR_CASE_CMP("opus", current_recive_codec.plname) == 0) {
3438 // We are resampling Opus internally to 32,000 Hz until all our
3439 // DSP routines can operate at 48,000 Hz, but the RTP clock
3440 // rate for the Opus payload format is standardized to 48,000 Hz,
3441 // because that is the maximum supported decoding sampling rate.
3442 playout_frequency = 48000;
3443 }
3444 }
3445 return playout_frequency;
3446}
3447
Minyue2013aec2015-05-13 14:14:42 +02003448int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003449 RtcpMode method = _rtpRtcpModule->RTCP();
3450 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003451 return 0;
3452 }
3453 std::vector<RTCPReportBlock> report_blocks;
3454 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003455
3456 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003457 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003458 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003459 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003460 Channel* channel = associate_send_channel_.channel();
3461 // Tries to get RTT from an associated channel. This is important for
3462 // receive-only channels.
3463 if (channel) {
3464 // To prevent infinite recursion and deadlock, calling GetRTT of
3465 // associate channel should always use "false" for argument:
3466 // |allow_associate_channel|.
3467 rtt = channel->GetRTT(false);
3468 }
3469 }
3470 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003471 }
3472
3473 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3474 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3475 for (; it != report_blocks.end(); ++it) {
3476 if (it->remoteSSRC == remoteSSRC)
3477 break;
3478 }
3479 if (it == report_blocks.end()) {
3480 // We have not received packets with SSRC matching the report blocks.
3481 // To calculate RTT we try with the SSRC of the first report block.
3482 // This is very important for send-only channels where we don't know
3483 // the SSRC of the other end.
3484 remoteSSRC = report_blocks[0].remoteSSRC;
3485 }
Minyue2013aec2015-05-13 14:14:42 +02003486
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003487 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003488 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003489 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003490 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3491 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003492 return 0;
3493 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003494 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003495}
3496
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003497} // namespace voe
3498} // namespace webrtc