blob: 339a6a52ff8c6d9c1e3ffd4c3f2ed0a3bcce30be [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"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010020#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000021#include "webrtc/base/timeutils.h"
minyue@webrtc.orge509f942013-09-12 17:03:00 +000022#include "webrtc/common.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020023#include "webrtc/config.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000024#include "webrtc/modules/audio_device/include/audio_device.h"
25#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010026#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010027#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010028#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
29#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
30#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000031#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010032#include "webrtc/modules/utility/include/audio_frame_operations.h"
33#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010034#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000035#include "webrtc/voice_engine/include/voe_base.h"
36#include "webrtc/voice_engine/include/voe_external_media.h"
37#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
38#include "webrtc/voice_engine/output_mixer.h"
39#include "webrtc/voice_engine/statistics.h"
40#include "webrtc/voice_engine/transmit_mixer.h"
41#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000042
andrew@webrtc.org50419b02012-11-14 19:07:54 +000043namespace webrtc {
44namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000045
kwibergc8d071e2016-04-06 12:22:38 -070046namespace {
47
48bool RegisterReceiveCodec(std::unique_ptr<AudioCodingModule>* acm,
49 acm2::RentACodec* rac,
50 const CodecInst& ci) {
51 const int result =
52 (*acm)->RegisterReceiveCodec(ci, [&] { return rac->RentIsacDecoder(); });
53 return result == 0;
54}
55
56} // namespace
57
solenberg8842c3e2016-03-11 03:06:41 -080058const int kTelephoneEventAttenuationdB = 10;
59
Stefan Holmerb86d4e42015-12-07 10:26:18 +010060class TransportFeedbackProxy : public TransportFeedbackObserver {
61 public:
62 TransportFeedbackProxy() : feedback_observer_(nullptr) {
63 pacer_thread_.DetachFromThread();
64 network_thread_.DetachFromThread();
65 }
66
67 void SetTransportFeedbackObserver(
68 TransportFeedbackObserver* feedback_observer) {
69 RTC_DCHECK(thread_checker_.CalledOnValidThread());
70 rtc::CritScope lock(&crit_);
71 feedback_observer_ = feedback_observer;
72 }
73
74 // Implements TransportFeedbackObserver.
75 void AddPacket(uint16_t sequence_number,
76 size_t length,
77 bool was_paced) override {
78 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
79 rtc::CritScope lock(&crit_);
80 if (feedback_observer_)
81 feedback_observer_->AddPacket(sequence_number, length, was_paced);
82 }
83 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
84 RTC_DCHECK(network_thread_.CalledOnValidThread());
85 rtc::CritScope lock(&crit_);
86 if (feedback_observer_)
87 feedback_observer_->OnTransportFeedback(feedback);
88 }
89
90 private:
91 rtc::CriticalSection crit_;
92 rtc::ThreadChecker thread_checker_;
93 rtc::ThreadChecker pacer_thread_;
94 rtc::ThreadChecker network_thread_;
95 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
96};
97
98class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
99 public:
100 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
101 pacer_thread_.DetachFromThread();
102 }
103
104 void SetSequenceNumberAllocator(
105 TransportSequenceNumberAllocator* seq_num_allocator) {
106 RTC_DCHECK(thread_checker_.CalledOnValidThread());
107 rtc::CritScope lock(&crit_);
108 seq_num_allocator_ = seq_num_allocator;
109 }
110
111 // Implements TransportSequenceNumberAllocator.
112 uint16_t AllocateSequenceNumber() override {
113 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
114 rtc::CritScope lock(&crit_);
115 if (!seq_num_allocator_)
116 return 0;
117 return seq_num_allocator_->AllocateSequenceNumber();
118 }
119
120 private:
121 rtc::CriticalSection crit_;
122 rtc::ThreadChecker thread_checker_;
123 rtc::ThreadChecker pacer_thread_;
124 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
125};
126
127class RtpPacketSenderProxy : public RtpPacketSender {
128 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800129 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100130
131 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
132 RTC_DCHECK(thread_checker_.CalledOnValidThread());
133 rtc::CritScope lock(&crit_);
134 rtp_packet_sender_ = rtp_packet_sender;
135 }
136
137 // Implements RtpPacketSender.
138 void InsertPacket(Priority priority,
139 uint32_t ssrc,
140 uint16_t sequence_number,
141 int64_t capture_time_ms,
142 size_t bytes,
143 bool retransmission) override {
144 rtc::CritScope lock(&crit_);
145 if (rtp_packet_sender_) {
146 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
147 capture_time_ms, bytes, retransmission);
148 }
149 }
150
151 private:
152 rtc::ThreadChecker thread_checker_;
153 rtc::CriticalSection crit_;
154 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
155};
156
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000157// Extend the default RTCP statistics struct with max_jitter, defined as the
158// maximum jitter value seen in an RTCP report block.
159struct ChannelStatistics : public RtcpStatistics {
160 ChannelStatistics() : rtcp(), max_jitter(0) {}
161
162 RtcpStatistics rtcp;
163 uint32_t max_jitter;
164};
165
166// Statistics callback, called at each generation of a new RTCP report block.
167class StatisticsProxy : public RtcpStatisticsCallback {
168 public:
tommi31fc21f2016-01-21 10:37:37 -0800169 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000170 virtual ~StatisticsProxy() {}
171
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000172 void StatisticsUpdated(const RtcpStatistics& statistics,
173 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000174 if (ssrc != ssrc_)
175 return;
176
tommi31fc21f2016-01-21 10:37:37 -0800177 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000178 stats_.rtcp = statistics;
179 if (statistics.jitter > stats_.max_jitter) {
180 stats_.max_jitter = statistics.jitter;
181 }
182 }
183
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000184 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000185
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000186 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800187 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000188 return stats_;
189 }
190
191 private:
192 // StatisticsUpdated calls are triggered from threads in the RTP module,
193 // while GetStats calls can be triggered from the public voice engine API,
194 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800195 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000196 const uint32_t ssrc_;
197 ChannelStatistics stats_;
198};
199
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000200class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000201 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000202 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
203 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000204
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000205 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
206 // Not used for Voice Engine.
207 }
208
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000209 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
210 int64_t rtt,
211 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000212 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
213 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
214 // report for VoiceEngine?
215 if (report_blocks.empty())
216 return;
217
218 int fraction_lost_aggregate = 0;
219 int total_number_of_packets = 0;
220
221 // If receiving multiple report blocks, calculate the weighted average based
222 // on the number of packets a report refers to.
223 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
224 block_it != report_blocks.end(); ++block_it) {
225 // Find the previous extended high sequence number for this remote SSRC,
226 // to calculate the number of RTP packets this report refers to. Ignore if
227 // we haven't seen this SSRC before.
228 std::map<uint32_t, uint32_t>::iterator seq_num_it =
229 extended_max_sequence_number_.find(block_it->sourceSSRC);
230 int number_of_packets = 0;
231 if (seq_num_it != extended_max_sequence_number_.end()) {
232 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
233 }
234 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
235 total_number_of_packets += number_of_packets;
236
237 extended_max_sequence_number_[block_it->sourceSSRC] =
238 block_it->extendedHighSeqNum;
239 }
240 int weighted_fraction_lost = 0;
241 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800242 weighted_fraction_lost =
243 (fraction_lost_aggregate + total_number_of_packets / 2) /
244 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000245 }
246 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000247 }
248
249 private:
250 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000251 // Maps remote side ssrc to extended highest sequence number received.
252 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000253};
254
kwiberg55b97fe2016-01-28 05:22:45 -0800255int32_t Channel::SendData(FrameType frameType,
256 uint8_t payloadType,
257 uint32_t timeStamp,
258 const uint8_t* payloadData,
259 size_t payloadSize,
260 const RTPFragmentationHeader* fragmentation) {
261 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
262 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
263 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
264 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000265
kwiberg55b97fe2016-01-28 05:22:45 -0800266 if (_includeAudioLevelIndication) {
267 // Store current audio level in the RTP/RTCP module.
268 // The level will be used in combination with voice-activity state
269 // (frameType) to add an RTP header extension
270 _rtpRtcpModule->SetAudioLevel(rms_level_.RMS());
271 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000272
kwiberg55b97fe2016-01-28 05:22:45 -0800273 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
274 // packetization.
275 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
276 if (_rtpRtcpModule->SendOutgoingData(
277 (FrameType&)frameType, payloadType, timeStamp,
278 // Leaving the time when this frame was
279 // received from the capture device as
280 // undefined for voice for now.
281 -1, payloadData, payloadSize, fragmentation) == -1) {
282 _engineStatisticsPtr->SetLastError(
283 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
284 "Channel::SendData() failed to send data to RTP/RTCP module");
285 return -1;
286 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000287
kwiberg55b97fe2016-01-28 05:22:45 -0800288 _lastLocalTimeStamp = timeStamp;
289 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000290
kwiberg55b97fe2016-01-28 05:22:45 -0800291 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000292}
293
kwiberg55b97fe2016-01-28 05:22:45 -0800294int32_t Channel::InFrameType(FrameType frame_type) {
295 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
296 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000297
kwiberg55b97fe2016-01-28 05:22:45 -0800298 rtc::CritScope cs(&_callbackCritSect);
299 _sendFrameType = (frame_type == kAudioFrameSpeech);
300 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000301}
302
kwiberg55b97fe2016-01-28 05:22:45 -0800303int32_t Channel::OnRxVadDetected(int vadDecision) {
304 rtc::CritScope cs(&_callbackCritSect);
305 if (_rxVadObserverPtr) {
306 _rxVadObserverPtr->OnRxVad(_channelId, vadDecision);
307 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000308
kwiberg55b97fe2016-01-28 05:22:45 -0800309 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000310}
311
stefan1d8a5062015-10-02 03:39:33 -0700312bool Channel::SendRtp(const uint8_t* data,
313 size_t len,
314 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800315 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
316 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000317
kwiberg55b97fe2016-01-28 05:22:45 -0800318 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000319
kwiberg55b97fe2016-01-28 05:22:45 -0800320 if (_transportPtr == NULL) {
321 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
322 "Channel::SendPacket() failed to send RTP packet due to"
323 " invalid transport object");
324 return false;
325 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000326
kwiberg55b97fe2016-01-28 05:22:45 -0800327 uint8_t* bufferToSendPtr = (uint8_t*)data;
328 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000329
kwiberg55b97fe2016-01-28 05:22:45 -0800330 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
331 std::string transport_name =
332 _externalTransport ? "external transport" : "WebRtc sockets";
333 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
334 "Channel::SendPacket() RTP transmission using %s failed",
335 transport_name.c_str());
336 return false;
337 }
338 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000339}
340
kwiberg55b97fe2016-01-28 05:22:45 -0800341bool Channel::SendRtcp(const uint8_t* data, size_t len) {
342 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
343 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000344
kwiberg55b97fe2016-01-28 05:22:45 -0800345 rtc::CritScope cs(&_callbackCritSect);
346 if (_transportPtr == NULL) {
347 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
348 "Channel::SendRtcp() failed to send RTCP packet"
349 " due to invalid transport object");
350 return false;
351 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000352
kwiberg55b97fe2016-01-28 05:22:45 -0800353 uint8_t* bufferToSendPtr = (uint8_t*)data;
354 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000355
kwiberg55b97fe2016-01-28 05:22:45 -0800356 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
357 if (n < 0) {
358 std::string transport_name =
359 _externalTransport ? "external transport" : "WebRtc sockets";
360 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
361 "Channel::SendRtcp() transmission using %s failed",
362 transport_name.c_str());
363 return false;
364 }
365 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000366}
367
kwiberg55b97fe2016-01-28 05:22:45 -0800368void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
369 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
370 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000371
kwiberg55b97fe2016-01-28 05:22:45 -0800372 // Update ssrc so that NTP for AV sync can be updated.
373 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000374}
375
Peter Boströmac547a62015-09-17 23:03:57 +0200376void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
377 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
378 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
379 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000380}
381
Peter Boströmac547a62015-09-17 23:03:57 +0200382int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000383 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000384 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000385 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800386 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200387 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800388 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
389 "Channel::OnInitializeDecoder(payloadType=%d, "
390 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
391 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000392
kwiberg55b97fe2016-01-28 05:22:45 -0800393 CodecInst receiveCodec = {0};
394 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000395
kwiberg55b97fe2016-01-28 05:22:45 -0800396 receiveCodec.pltype = payloadType;
397 receiveCodec.plfreq = frequency;
398 receiveCodec.channels = channels;
399 receiveCodec.rate = rate;
400 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000401
kwiberg55b97fe2016-01-28 05:22:45 -0800402 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
403 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000404
kwiberg55b97fe2016-01-28 05:22:45 -0800405 // Register the new codec to the ACM
kwibergc8d071e2016-04-06 12:22:38 -0700406 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, receiveCodec)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800407 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
408 "Channel::OnInitializeDecoder() invalid codec ("
409 "pt=%d, name=%s) received - 1",
410 payloadType, payloadName);
411 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
412 return -1;
413 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000414
kwiberg55b97fe2016-01-28 05:22:45 -0800415 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000416}
417
kwiberg55b97fe2016-01-28 05:22:45 -0800418int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
419 size_t payloadSize,
420 const WebRtcRTPHeader* rtpHeader) {
421 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
422 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
423 ","
424 " payloadType=%u, audioChannel=%" PRIuS ")",
425 payloadSize, rtpHeader->header.payloadType,
426 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000427
kwiberg55b97fe2016-01-28 05:22:45 -0800428 if (!channel_state_.Get().playing) {
429 // Avoid inserting into NetEQ when we are not playing. Count the
430 // packet as discarded.
431 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
432 "received packet is discarded since playing is not"
433 " activated");
434 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000435 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800436 }
437
438 // Push the incoming payload (parsed and ready for decoding) into the ACM
439 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
440 0) {
441 _engineStatisticsPtr->SetLastError(
442 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
443 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
444 return -1;
445 }
446
447 // Update the packet delay.
448 UpdatePacketDelay(rtpHeader->header.timestamp,
449 rtpHeader->header.sequenceNumber);
450
451 int64_t round_trip_time = 0;
452 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
453 NULL);
454
455 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
456 if (!nack_list.empty()) {
457 // Can't use nack_list.data() since it's not supported by all
458 // compilers.
459 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
460 }
461 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000462}
463
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000464bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000465 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000466 RTPHeader header;
467 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
468 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
469 "IncomingPacket invalid RTP header");
470 return false;
471 }
472 header.payload_type_frequency =
473 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
474 if (header.payload_type_frequency < 0)
475 return false;
476 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
477}
478
kwiberg55b97fe2016-01-28 05:22:45 -0800479int32_t Channel::GetAudioFrame(int32_t id, AudioFrame* audioFrame) {
480 if (event_log_) {
481 unsigned int ssrc;
482 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
483 event_log_->LogAudioPlayout(ssrc);
484 }
485 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700486 bool muted;
487 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
488 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800489 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
490 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
491 // In all likelihood, the audio in this frame is garbage. We return an
492 // error so that the audio mixer module doesn't add it to the mix. As
493 // a result, it won't be played out and the actions skipped here are
494 // irrelevant.
495 return -1;
496 }
henrik.lundind4ccb002016-05-17 12:21:55 -0700497 RTC_DCHECK(!muted);
kwiberg55b97fe2016-01-28 05:22:45 -0800498
499 if (_RxVadDetection) {
500 UpdateRxVadDetection(*audioFrame);
501 }
502
503 // Convert module ID to internal VoE channel ID
504 audioFrame->id_ = VoEChannelId(audioFrame->id_);
505 // Store speech type for dead-or-alive detection
506 _outputSpeechType = audioFrame->speech_type_;
507
508 ChannelState::State state = channel_state_.Get();
509
510 if (state.rx_apm_is_enabled) {
511 int err = rx_audioproc_->ProcessStream(audioFrame);
512 if (err) {
513 LOG(LS_ERROR) << "ProcessStream() error: " << err;
514 assert(false);
Ivo Creusenae856f22015-09-17 16:30:16 +0200515 }
kwiberg55b97fe2016-01-28 05:22:45 -0800516 }
517
518 {
519 // Pass the audio buffers to an optional sink callback, before applying
520 // scaling/panning, as that applies to the mix operation.
521 // External recipients of the audio (e.g. via AudioTrack), will do their
522 // own mixing/dynamic processing.
523 rtc::CritScope cs(&_callbackCritSect);
524 if (audio_sink_) {
525 AudioSinkInterface::Data data(
526 &audioFrame->data_[0], audioFrame->samples_per_channel_,
527 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
528 audioFrame->timestamp_);
529 audio_sink_->OnData(data);
530 }
531 }
532
533 float output_gain = 1.0f;
534 float left_pan = 1.0f;
535 float right_pan = 1.0f;
536 {
537 rtc::CritScope cs(&volume_settings_critsect_);
538 output_gain = _outputGain;
539 left_pan = _panLeft;
540 right_pan = _panRight;
541 }
542
543 // Output volume scaling
544 if (output_gain < 0.99f || output_gain > 1.01f) {
545 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
546 }
547
548 // Scale left and/or right channel(s) if stereo and master balance is
549 // active
550
551 if (left_pan != 1.0f || right_pan != 1.0f) {
552 if (audioFrame->num_channels_ == 1) {
553 // Emulate stereo mode since panning is active.
554 // The mono signal is copied to both left and right channels here.
555 AudioFrameOperations::MonoToStereo(audioFrame);
556 }
557 // For true stereo mode (when we are receiving a stereo signal), no
558 // action is needed.
559
560 // Do the panning operation (the audio frame contains stereo at this
561 // stage)
562 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
563 }
564
565 // Mix decoded PCM output with file if file mixing is enabled
566 if (state.output_file_playing) {
567 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
568 }
569
570 // External media
571 if (_outputExternalMedia) {
572 rtc::CritScope cs(&_callbackCritSect);
573 const bool isStereo = (audioFrame->num_channels_ == 2);
574 if (_outputExternalMediaCallbackPtr) {
575 _outputExternalMediaCallbackPtr->Process(
576 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
577 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
578 isStereo);
579 }
580 }
581
582 // Record playout if enabled
583 {
584 rtc::CritScope cs(&_fileCritSect);
585
586 if (_outputFileRecording && _outputFileRecorderPtr) {
587 _outputFileRecorderPtr->RecordAudioToFile(*audioFrame);
588 }
589 }
590
591 // Measure audio level (0-9)
592 _outputAudioLevel.ComputeLevel(*audioFrame);
593
594 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
595 // The first frame with a valid rtp timestamp.
596 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
597 }
598
599 if (capture_start_rtp_time_stamp_ >= 0) {
600 // audioFrame.timestamp_ should be valid from now on.
601
602 // Compute elapsed time.
603 int64_t unwrap_timestamp =
604 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
605 audioFrame->elapsed_time_ms_ =
606 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
607 (GetPlayoutFrequency() / 1000);
608
niklase@google.com470e71d2011-07-07 08:21:25 +0000609 {
kwiberg55b97fe2016-01-28 05:22:45 -0800610 rtc::CritScope lock(&ts_stats_lock_);
611 // Compute ntp time.
612 audioFrame->ntp_time_ms_ =
613 ntp_estimator_.Estimate(audioFrame->timestamp_);
614 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
615 if (audioFrame->ntp_time_ms_ > 0) {
616 // Compute |capture_start_ntp_time_ms_| so that
617 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
618 capture_start_ntp_time_ms_ =
619 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000620 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000621 }
kwiberg55b97fe2016-01-28 05:22:45 -0800622 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000623
kwiberg55b97fe2016-01-28 05:22:45 -0800624 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000625}
626
kwiberg55b97fe2016-01-28 05:22:45 -0800627int32_t Channel::NeededFrequency(int32_t id) const {
628 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
629 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000630
kwiberg55b97fe2016-01-28 05:22:45 -0800631 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000632
kwiberg55b97fe2016-01-28 05:22:45 -0800633 // Determine highest needed receive frequency
634 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000635
kwiberg55b97fe2016-01-28 05:22:45 -0800636 // Return the bigger of playout and receive frequency in the ACM.
637 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
638 highestNeeded = audio_coding_->PlayoutFrequency();
639 } else {
640 highestNeeded = receiveFrequency;
641 }
642
643 // Special case, if we're playing a file on the playout side
644 // we take that frequency into consideration as well
645 // This is not needed on sending side, since the codec will
646 // limit the spectrum anyway.
647 if (channel_state_.Get().output_file_playing) {
648 rtc::CritScope cs(&_fileCritSect);
649 if (_outputFilePlayerPtr) {
650 if (_outputFilePlayerPtr->Frequency() > highestNeeded) {
651 highestNeeded = _outputFilePlayerPtr->Frequency();
652 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000653 }
kwiberg55b97fe2016-01-28 05:22:45 -0800654 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000655
kwiberg55b97fe2016-01-28 05:22:45 -0800656 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000657}
658
ivocb04965c2015-09-09 00:09:43 -0700659int32_t Channel::CreateChannel(Channel*& channel,
660 int32_t channelId,
661 uint32_t instanceId,
662 RtcEventLog* const event_log,
663 const Config& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800664 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
665 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
666 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000667
kwiberg55b97fe2016-01-28 05:22:45 -0800668 channel = new Channel(channelId, instanceId, event_log, config);
669 if (channel == NULL) {
670 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
671 "Channel::CreateChannel() unable to allocate memory for"
672 " channel");
673 return -1;
674 }
675 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000676}
677
kwiberg55b97fe2016-01-28 05:22:45 -0800678void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
679 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
680 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
681 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000682
kwiberg55b97fe2016-01-28 05:22:45 -0800683 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000684}
685
kwiberg55b97fe2016-01-28 05:22:45 -0800686void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
687 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
688 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
689 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000690
kwiberg55b97fe2016-01-28 05:22:45 -0800691 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000692}
693
kwiberg55b97fe2016-01-28 05:22:45 -0800694void Channel::PlayFileEnded(int32_t id) {
695 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
696 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000697
kwiberg55b97fe2016-01-28 05:22:45 -0800698 if (id == _inputFilePlayerId) {
699 channel_state_.SetInputFilePlaying(false);
700 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
701 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000702 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800703 } else if (id == _outputFilePlayerId) {
704 channel_state_.SetOutputFilePlaying(false);
705 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
706 "Channel::PlayFileEnded() => output file player module is"
707 " shutdown");
708 }
709}
710
711void Channel::RecordFileEnded(int32_t id) {
712 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
713 "Channel::RecordFileEnded(id=%d)", id);
714
715 assert(id == _outputFileRecorderId);
716
717 rtc::CritScope cs(&_fileCritSect);
718
719 _outputFileRecording = false;
720 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
721 "Channel::RecordFileEnded() => output file recorder module is"
722 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000723}
724
pbos@webrtc.org92135212013-05-14 08:31:39 +0000725Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000726 uint32_t instanceId,
ivocb04965c2015-09-09 00:09:43 -0700727 RtcEventLog* const event_log,
728 const Config& config)
tommi31fc21f2016-01-21 10:37:37 -0800729 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100730 _channelId(channelId),
731 event_log_(event_log),
732 rtp_header_parser_(RtpHeaderParser::Create()),
733 rtp_payload_registry_(
734 new RTPPayloadRegistry(RTPPayloadStrategy::CreateStrategy(true))),
735 rtp_receive_statistics_(
736 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
737 rtp_receiver_(
738 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100739 this,
740 this,
741 rtp_payload_registry_.get())),
742 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
743 _outputAudioLevel(),
744 _externalTransport(false),
745 _inputFilePlayerPtr(NULL),
746 _outputFilePlayerPtr(NULL),
747 _outputFileRecorderPtr(NULL),
748 // Avoid conflict with other channels by adding 1024 - 1026,
749 // won't use as much as 1024 channels.
750 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
751 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
752 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
753 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100754 _outputExternalMedia(false),
755 _inputExternalMediaCallbackPtr(NULL),
756 _outputExternalMediaCallbackPtr(NULL),
757 _timeStamp(0), // This is just an offset, RTP module will add it's own
758 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100759 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100760 playout_timestamp_rtp_(0),
761 playout_timestamp_rtcp_(0),
762 playout_delay_ms_(0),
763 _numberOfDiscardedPackets(0),
764 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100765 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
766 capture_start_rtp_time_stamp_(-1),
767 capture_start_ntp_time_ms_(-1),
768 _engineStatisticsPtr(NULL),
769 _outputMixerPtr(NULL),
770 _transmitMixerPtr(NULL),
771 _moduleProcessThreadPtr(NULL),
772 _audioDeviceModulePtr(NULL),
773 _voiceEngineObserverPtr(NULL),
774 _callbackCritSectPtr(NULL),
775 _transportPtr(NULL),
776 _rxVadObserverPtr(NULL),
777 _oldVadDecision(-1),
778 _sendFrameType(0),
779 _externalMixing(false),
780 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700781 input_mute_(false),
782 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100783 _panLeft(1.0f),
784 _panRight(1.0f),
785 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100786 _lastLocalTimeStamp(0),
787 _lastPayloadType(0),
788 _includeAudioLevelIndication(false),
789 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100790 _average_jitter_buffer_delay_us(0),
791 _previousTimestamp(0),
792 _recPacketDelayMs(20),
793 _RxVadDetection(false),
794 _rxAgcIsEnabled(false),
795 _rxNsIsEnabled(false),
796 restored_packet_in_use_(false),
797 rtcp_observer_(new VoERtcpObserver(this)),
798 network_predictor_(new NetworkPredictor(Clock::GetRealTimeClock())),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100799 associate_send_channel_(ChannelOwner(nullptr)),
800 pacing_enabled_(config.Get<VoicePacing>().enabled),
stefanbba9dec2016-02-01 04:39:55 -0800801 feedback_observer_proxy_(new TransportFeedbackProxy()),
802 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
803 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()) {
kwiberg55b97fe2016-01-28 05:22:45 -0800804 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
805 "Channel::Channel() - ctor");
806 AudioCodingModule::Config acm_config;
807 acm_config.id = VoEModuleId(instanceId, channelId);
808 if (config.Get<NetEqCapacityConfig>().enabled) {
809 // Clamping the buffer capacity at 20 packets. While going lower will
810 // probably work, it makes little sense.
811 acm_config.neteq_config.max_packets_in_buffer =
812 std::max(20, config.Get<NetEqCapacityConfig>().capacity);
813 }
814 acm_config.neteq_config.enable_fast_accelerate =
815 config.Get<NetEqFastAccelerate>().enabled;
henrik.lundind4ccb002016-05-17 12:21:55 -0700816 acm_config.neteq_config.enable_muted_state = false;
kwiberg55b97fe2016-01-28 05:22:45 -0800817 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200818
kwiberg55b97fe2016-01-28 05:22:45 -0800819 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000820
kwiberg55b97fe2016-01-28 05:22:45 -0800821 RtpRtcp::Configuration configuration;
822 configuration.audio = true;
823 configuration.outgoing_transport = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800824 configuration.receive_statistics = rtp_receive_statistics_.get();
825 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800826 if (pacing_enabled_) {
827 configuration.paced_sender = rtp_packet_sender_proxy_.get();
828 configuration.transport_sequence_number_allocator =
829 seq_num_allocator_proxy_.get();
830 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
831 }
kwiberg55b97fe2016-01-28 05:22:45 -0800832 configuration.event_log = event_log;
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000833
kwiberg55b97fe2016-01-28 05:22:45 -0800834 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100835 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000836
kwiberg55b97fe2016-01-28 05:22:45 -0800837 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
838 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
839 statistics_proxy_.get());
aluebs@webrtc.orgf927fd62014-04-16 11:58:18 +0000840
kwiberg55b97fe2016-01-28 05:22:45 -0800841 Config audioproc_config;
842 audioproc_config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
843 rx_audioproc_.reset(AudioProcessing::Create(audioproc_config));
niklase@google.com470e71d2011-07-07 08:21:25 +0000844}
845
kwiberg55b97fe2016-01-28 05:22:45 -0800846Channel::~Channel() {
847 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
848 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
849 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000850
kwiberg55b97fe2016-01-28 05:22:45 -0800851 if (_outputExternalMedia) {
852 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
853 }
854 if (channel_state_.Get().input_external_media) {
855 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
856 }
857 StopSend();
858 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000859
kwiberg55b97fe2016-01-28 05:22:45 -0800860 {
861 rtc::CritScope cs(&_fileCritSect);
862 if (_inputFilePlayerPtr) {
863 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
864 _inputFilePlayerPtr->StopPlayingFile();
865 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
866 _inputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000867 }
kwiberg55b97fe2016-01-28 05:22:45 -0800868 if (_outputFilePlayerPtr) {
869 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
870 _outputFilePlayerPtr->StopPlayingFile();
871 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
872 _outputFilePlayerPtr = NULL;
873 }
874 if (_outputFileRecorderPtr) {
875 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
876 _outputFileRecorderPtr->StopRecording();
877 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
878 _outputFileRecorderPtr = NULL;
879 }
880 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000881
kwiberg55b97fe2016-01-28 05:22:45 -0800882 // The order to safely shutdown modules in a channel is:
883 // 1. De-register callbacks in modules
884 // 2. De-register modules in process thread
885 // 3. Destroy modules
886 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
887 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
888 "~Channel() failed to de-register transport callback"
889 " (Audio coding module)");
890 }
891 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
892 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
893 "~Channel() failed to de-register VAD callback"
894 " (Audio coding module)");
895 }
896 // De-register modules in process thread
897 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +0000898
kwiberg55b97fe2016-01-28 05:22:45 -0800899 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +0000900}
901
kwiberg55b97fe2016-01-28 05:22:45 -0800902int32_t Channel::Init() {
903 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
904 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000905
kwiberg55b97fe2016-01-28 05:22:45 -0800906 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000907
kwiberg55b97fe2016-01-28 05:22:45 -0800908 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000909
kwiberg55b97fe2016-01-28 05:22:45 -0800910 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
911 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
912 "Channel::Init() must call SetEngineInformation() first");
913 return -1;
914 }
915
916 // --- Add modules to process thread (for periodic schedulation)
917
918 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
919
920 // --- ACM initialization
921
922 if (audio_coding_->InitializeReceiver() == -1) {
923 _engineStatisticsPtr->SetLastError(
924 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
925 "Channel::Init() unable to initialize the ACM - 1");
926 return -1;
927 }
928
929 // --- RTP/RTCP module initialization
930
931 // Ensure that RTCP is enabled by default for the created channel.
932 // Note that, the module will keep generating RTCP until it is explicitly
933 // disabled by the user.
934 // After StopListen (when no sockets exists), RTCP packets will no longer
935 // be transmitted since the Transport object will then be invalid.
936 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
937 // RTCP is enabled by default.
938 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
939 // --- Register all permanent callbacks
940 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
941 (audio_coding_->RegisterVADCallback(this) == -1);
942
943 if (fail) {
944 _engineStatisticsPtr->SetLastError(
945 VE_CANNOT_INIT_CHANNEL, kTraceError,
946 "Channel::Init() callbacks not registered");
947 return -1;
948 }
949
950 // --- Register all supported codecs to the receiving side of the
951 // RTP/RTCP module
952
953 CodecInst codec;
954 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
955
956 for (int idx = 0; idx < nSupportedCodecs; idx++) {
957 // Open up the RTP/RTCP receiver for all supported codecs
958 if ((audio_coding_->Codec(idx, &codec) == -1) ||
959 (rtp_receiver_->RegisterReceivePayload(
960 codec.plname, codec.pltype, codec.plfreq, codec.channels,
961 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
962 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
963 "Channel::Init() unable to register %s "
964 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
965 codec.plname, codec.pltype, codec.plfreq, codec.channels,
966 codec.rate);
967 } else {
968 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
969 "Channel::Init() %s (%d/%d/%" PRIuS
970 "/%d) has been "
971 "added to the RTP/RTCP receiver",
972 codec.plname, codec.pltype, codec.plfreq, codec.channels,
973 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000974 }
975
kwiberg55b97fe2016-01-28 05:22:45 -0800976 // Ensure that PCMU is used as default codec on the sending side
977 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
978 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +0000979 }
980
kwiberg55b97fe2016-01-28 05:22:45 -0800981 // Register default PT for outband 'telephone-event'
982 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -0700983 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
984 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800985 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
986 "Channel::Init() failed to register outband "
987 "'telephone-event' (%d/%d) correctly",
988 codec.pltype, codec.plfreq);
989 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000990 }
991
kwiberg55b97fe2016-01-28 05:22:45 -0800992 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -0700993 if (!codec_manager_.RegisterEncoder(codec) ||
994 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
995 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec) ||
996 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800997 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
998 "Channel::Init() failed to register CN (%d/%d) "
999 "correctly - 1",
1000 codec.pltype, codec.plfreq);
1001 }
1002 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001003#ifdef WEBRTC_CODEC_RED
kwiberg55b97fe2016-01-28 05:22:45 -08001004 // Register RED to the receiving side of the ACM.
1005 // We will not receive an OnInitializeDecoder() callback for RED.
1006 if (!STR_CASE_CMP(codec.plname, "RED")) {
kwibergc8d071e2016-04-06 12:22:38 -07001007 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001008 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1009 "Channel::Init() failed to register RED (%d/%d) "
1010 "correctly",
1011 codec.pltype, codec.plfreq);
1012 }
1013 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001014#endif
kwiberg55b97fe2016-01-28 05:22:45 -08001015 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001016
kwiberg55b97fe2016-01-28 05:22:45 -08001017 if (rx_audioproc_->noise_suppression()->set_level(kDefaultNsMode) != 0) {
1018 LOG(LS_ERROR) << "noise_suppression()->set_level(kDefaultNsMode) failed.";
1019 return -1;
1020 }
1021 if (rx_audioproc_->gain_control()->set_mode(kDefaultRxAgcMode) != 0) {
1022 LOG(LS_ERROR) << "gain_control()->set_mode(kDefaultRxAgcMode) failed.";
1023 return -1;
1024 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001025
kwiberg55b97fe2016-01-28 05:22:45 -08001026 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001027}
1028
kwiberg55b97fe2016-01-28 05:22:45 -08001029int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1030 OutputMixer& outputMixer,
1031 voe::TransmitMixer& transmitMixer,
1032 ProcessThread& moduleProcessThread,
1033 AudioDeviceModule& audioDeviceModule,
1034 VoiceEngineObserver* voiceEngineObserver,
1035 rtc::CriticalSection* callbackCritSect) {
1036 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1037 "Channel::SetEngineInformation()");
1038 _engineStatisticsPtr = &engineStatistics;
1039 _outputMixerPtr = &outputMixer;
1040 _transmitMixerPtr = &transmitMixer,
1041 _moduleProcessThreadPtr = &moduleProcessThread;
1042 _audioDeviceModulePtr = &audioDeviceModule;
1043 _voiceEngineObserverPtr = voiceEngineObserver;
1044 _callbackCritSectPtr = callbackCritSect;
1045 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001046}
1047
kwiberg55b97fe2016-01-28 05:22:45 -08001048int32_t Channel::UpdateLocalTimeStamp() {
1049 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1050 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001051}
1052
kwibergb7f89d62016-02-17 10:04:18 -08001053void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001054 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001055 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001056}
1057
kwiberg55b97fe2016-01-28 05:22:45 -08001058int32_t Channel::StartPlayout() {
1059 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1060 "Channel::StartPlayout()");
1061 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001062 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001063 }
1064
1065 if (!_externalMixing) {
1066 // Add participant as candidates for mixing.
1067 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1068 _engineStatisticsPtr->SetLastError(
1069 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1070 "StartPlayout() failed to add participant to mixer");
1071 return -1;
1072 }
1073 }
1074
1075 channel_state_.SetPlaying(true);
1076 if (RegisterFilePlayingToMixer() != 0)
1077 return -1;
1078
1079 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001080}
1081
kwiberg55b97fe2016-01-28 05:22:45 -08001082int32_t Channel::StopPlayout() {
1083 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1084 "Channel::StopPlayout()");
1085 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001086 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001087 }
1088
1089 if (!_externalMixing) {
1090 // Remove participant as candidates for mixing
1091 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1092 _engineStatisticsPtr->SetLastError(
1093 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1094 "StopPlayout() failed to remove participant from mixer");
1095 return -1;
1096 }
1097 }
1098
1099 channel_state_.SetPlaying(false);
1100 _outputAudioLevel.Clear();
1101
1102 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001103}
1104
kwiberg55b97fe2016-01-28 05:22:45 -08001105int32_t Channel::StartSend() {
1106 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1107 "Channel::StartSend()");
1108 // Resume the previous sequence number which was reset by StopSend().
1109 // This needs to be done before |sending| is set to true.
1110 if (send_sequence_number_)
1111 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001112
kwiberg55b97fe2016-01-28 05:22:45 -08001113 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001114 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001115 }
1116 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001117
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001118 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001119 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1120 _engineStatisticsPtr->SetLastError(
1121 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1122 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001123 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001124 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001125 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001126 return -1;
1127 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001128
kwiberg55b97fe2016-01-28 05:22:45 -08001129 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001130}
1131
kwiberg55b97fe2016-01-28 05:22:45 -08001132int32_t Channel::StopSend() {
1133 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1134 "Channel::StopSend()");
1135 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001136 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001137 }
1138 channel_state_.SetSending(false);
1139
1140 // Store the sequence number to be able to pick up the same sequence for
1141 // the next StartSend(). This is needed for restarting device, otherwise
1142 // it might cause libSRTP to complain about packets being replayed.
1143 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1144 // CL is landed. See issue
1145 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1146 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1147
1148 // Reset sending SSRC and sequence number and triggers direct transmission
1149 // of RTCP BYE
1150 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1151 _engineStatisticsPtr->SetLastError(
1152 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1153 "StartSend() RTP/RTCP failed to stop sending");
1154 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001155 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001156
1157 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001158}
1159
kwiberg55b97fe2016-01-28 05:22:45 -08001160int32_t Channel::StartReceiving() {
1161 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1162 "Channel::StartReceiving()");
1163 if (channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001164 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001165 }
1166 channel_state_.SetReceiving(true);
1167 _numberOfDiscardedPackets = 0;
1168 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001169}
1170
kwiberg55b97fe2016-01-28 05:22:45 -08001171int32_t Channel::StopReceiving() {
1172 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1173 "Channel::StopReceiving()");
1174 if (!channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001175 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001176 }
1177
1178 channel_state_.SetReceiving(false);
1179 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001180}
1181
kwiberg55b97fe2016-01-28 05:22:45 -08001182int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1183 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1184 "Channel::RegisterVoiceEngineObserver()");
1185 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001186
kwiberg55b97fe2016-01-28 05:22:45 -08001187 if (_voiceEngineObserverPtr) {
1188 _engineStatisticsPtr->SetLastError(
1189 VE_INVALID_OPERATION, kTraceError,
1190 "RegisterVoiceEngineObserver() observer already enabled");
1191 return -1;
1192 }
1193 _voiceEngineObserverPtr = &observer;
1194 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001195}
1196
kwiberg55b97fe2016-01-28 05:22:45 -08001197int32_t Channel::DeRegisterVoiceEngineObserver() {
1198 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1199 "Channel::DeRegisterVoiceEngineObserver()");
1200 rtc::CritScope cs(&_callbackCritSect);
1201
1202 if (!_voiceEngineObserverPtr) {
1203 _engineStatisticsPtr->SetLastError(
1204 VE_INVALID_OPERATION, kTraceWarning,
1205 "DeRegisterVoiceEngineObserver() observer already disabled");
1206 return 0;
1207 }
1208 _voiceEngineObserverPtr = NULL;
1209 return 0;
1210}
1211
1212int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001213 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001214 if (send_codec) {
1215 codec = *send_codec;
1216 return 0;
1217 }
1218 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001219}
1220
kwiberg55b97fe2016-01-28 05:22:45 -08001221int32_t Channel::GetRecCodec(CodecInst& codec) {
1222 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001223}
1224
kwiberg55b97fe2016-01-28 05:22:45 -08001225int32_t Channel::SetSendCodec(const CodecInst& codec) {
1226 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1227 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001228
kwibergc8d071e2016-04-06 12:22:38 -07001229 if (!codec_manager_.RegisterEncoder(codec) ||
1230 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001231 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1232 "SetSendCodec() failed to register codec to ACM");
1233 return -1;
1234 }
1235
1236 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1237 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1238 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1239 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1240 "SetSendCodec() failed to register codec to"
1241 " RTP/RTCP module");
1242 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001243 }
kwiberg55b97fe2016-01-28 05:22:45 -08001244 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001245
kwiberg55b97fe2016-01-28 05:22:45 -08001246 if (_rtpRtcpModule->SetAudioPacketSize(codec.pacsize) != 0) {
1247 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1248 "SetSendCodec() failed to set audio packet size");
1249 return -1;
1250 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001251
kwiberg55b97fe2016-01-28 05:22:45 -08001252 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001253}
1254
Ivo Creusenadf89b72015-04-29 16:03:33 +02001255void Channel::SetBitRate(int bitrate_bps) {
1256 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1257 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
1258 audio_coding_->SetBitRate(bitrate_bps);
1259}
1260
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001261void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue@webrtc.org74aaf292014-07-16 21:28:26 +00001262 network_predictor_->UpdatePacketLossRate(fraction_lost);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001263 uint8_t average_fraction_loss = network_predictor_->GetLossRate();
1264
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001265 // Normalizes rate to 0 - 100.
kwiberg55b97fe2016-01-28 05:22:45 -08001266 if (audio_coding_->SetPacketLossRate(100 * average_fraction_loss / 255) !=
1267 0) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001268 assert(false); // This should not happen.
1269 }
1270}
1271
kwiberg55b97fe2016-01-28 05:22:45 -08001272int32_t Channel::SetVADStatus(bool enableVAD,
1273 ACMVADMode mode,
1274 bool disableDTX) {
1275 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1276 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001277 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1278 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1279 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001280 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1281 kTraceError,
1282 "SetVADStatus() failed to set VAD");
1283 return -1;
1284 }
1285 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001286}
1287
kwiberg55b97fe2016-01-28 05:22:45 -08001288int32_t Channel::GetVADStatus(bool& enabledVAD,
1289 ACMVADMode& mode,
1290 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001291 const auto* params = codec_manager_.GetStackParams();
1292 enabledVAD = params->use_cng;
1293 mode = params->vad_mode;
1294 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001295 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001296}
1297
kwiberg55b97fe2016-01-28 05:22:45 -08001298int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1299 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1300 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001301
kwiberg55b97fe2016-01-28 05:22:45 -08001302 if (channel_state_.Get().playing) {
1303 _engineStatisticsPtr->SetLastError(
1304 VE_ALREADY_PLAYING, kTraceError,
1305 "SetRecPayloadType() unable to set PT while playing");
1306 return -1;
1307 }
1308 if (channel_state_.Get().receiving) {
1309 _engineStatisticsPtr->SetLastError(
1310 VE_ALREADY_LISTENING, kTraceError,
1311 "SetRecPayloadType() unable to set PT while listening");
1312 return -1;
1313 }
1314
1315 if (codec.pltype == -1) {
1316 // De-register the selected codec (RTP/RTCP module and ACM)
1317
1318 int8_t pltype(-1);
1319 CodecInst rxCodec = codec;
1320
1321 // Get payload type for the given codec
1322 rtp_payload_registry_->ReceivePayloadType(
1323 rxCodec.plname, rxCodec.plfreq, rxCodec.channels,
1324 (rxCodec.rate < 0) ? 0 : rxCodec.rate, &pltype);
1325 rxCodec.pltype = pltype;
1326
1327 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1328 _engineStatisticsPtr->SetLastError(
1329 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1330 "SetRecPayloadType() RTP/RTCP-module deregistration "
1331 "failed");
1332 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001333 }
kwiberg55b97fe2016-01-28 05:22:45 -08001334 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1335 _engineStatisticsPtr->SetLastError(
1336 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1337 "SetRecPayloadType() ACM deregistration failed - 1");
1338 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001339 }
kwiberg55b97fe2016-01-28 05:22:45 -08001340 return 0;
1341 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001342
kwiberg55b97fe2016-01-28 05:22:45 -08001343 if (rtp_receiver_->RegisterReceivePayload(
1344 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1345 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1346 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001347 // TODO(kwiberg): Retrying is probably not necessary, since
1348 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001349 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001350 if (rtp_receiver_->RegisterReceivePayload(
kwiberg55b97fe2016-01-28 05:22:45 -08001351 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1352 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1353 _engineStatisticsPtr->SetLastError(
1354 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1355 "SetRecPayloadType() RTP/RTCP-module registration failed");
1356 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001357 }
kwiberg55b97fe2016-01-28 05:22:45 -08001358 }
kwibergc8d071e2016-04-06 12:22:38 -07001359 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001360 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergc8d071e2016-04-06 12:22:38 -07001361 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001362 _engineStatisticsPtr->SetLastError(
1363 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1364 "SetRecPayloadType() ACM registration failed - 1");
1365 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001366 }
kwiberg55b97fe2016-01-28 05:22:45 -08001367 }
1368 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001369}
1370
kwiberg55b97fe2016-01-28 05:22:45 -08001371int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1372 int8_t payloadType(-1);
1373 if (rtp_payload_registry_->ReceivePayloadType(
1374 codec.plname, codec.plfreq, codec.channels,
1375 (codec.rate < 0) ? 0 : codec.rate, &payloadType) != 0) {
1376 _engineStatisticsPtr->SetLastError(
1377 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1378 "GetRecPayloadType() failed to retrieve RX payload type");
1379 return -1;
1380 }
1381 codec.pltype = payloadType;
1382 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001383}
1384
kwiberg55b97fe2016-01-28 05:22:45 -08001385int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1386 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1387 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001388
kwiberg55b97fe2016-01-28 05:22:45 -08001389 CodecInst codec;
1390 int32_t samplingFreqHz(-1);
1391 const size_t kMono = 1;
1392 if (frequency == kFreq32000Hz)
1393 samplingFreqHz = 32000;
1394 else if (frequency == kFreq16000Hz)
1395 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001396
kwiberg55b97fe2016-01-28 05:22:45 -08001397 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1398 _engineStatisticsPtr->SetLastError(
1399 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1400 "SetSendCNPayloadType() failed to retrieve default CN codec "
1401 "settings");
1402 return -1;
1403 }
1404
1405 // Modify the payload type (must be set to dynamic range)
1406 codec.pltype = type;
1407
kwibergc8d071e2016-04-06 12:22:38 -07001408 if (!codec_manager_.RegisterEncoder(codec) ||
1409 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001410 _engineStatisticsPtr->SetLastError(
1411 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1412 "SetSendCNPayloadType() failed to register CN to ACM");
1413 return -1;
1414 }
1415
1416 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1417 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1418 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1419 _engineStatisticsPtr->SetLastError(
1420 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1421 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1422 "module");
1423 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001424 }
kwiberg55b97fe2016-01-28 05:22:45 -08001425 }
1426 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001427}
1428
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001429int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001430 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001431 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001432
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001433 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001434 _engineStatisticsPtr->SetLastError(
1435 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001436 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001437 return -1;
1438 }
1439 return 0;
1440}
1441
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001442int Channel::SetOpusDtx(bool enable_dtx) {
1443 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1444 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001445 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001446 : audio_coding_->DisableOpusDtx();
1447 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001448 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1449 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001450 return -1;
1451 }
1452 return 0;
1453}
1454
mflodman3d7db262016-04-29 00:57:13 -07001455int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001456 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001457 "Channel::RegisterExternalTransport()");
1458
kwiberg55b97fe2016-01-28 05:22:45 -08001459 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001460 if (_externalTransport) {
1461 _engineStatisticsPtr->SetLastError(
1462 VE_INVALID_OPERATION, kTraceError,
1463 "RegisterExternalTransport() external transport already enabled");
1464 return -1;
1465 }
1466 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001467 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001468 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001469}
1470
kwiberg55b97fe2016-01-28 05:22:45 -08001471int32_t Channel::DeRegisterExternalTransport() {
1472 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1473 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001474
kwiberg55b97fe2016-01-28 05:22:45 -08001475 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001476 if (_transportPtr) {
1477 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1478 "DeRegisterExternalTransport() all transport is disabled");
1479 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001480 _engineStatisticsPtr->SetLastError(
1481 VE_INVALID_OPERATION, kTraceWarning,
1482 "DeRegisterExternalTransport() external transport already "
1483 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001484 }
1485 _externalTransport = false;
1486 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001487 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001488}
1489
mflodman3d7db262016-04-29 00:57:13 -07001490int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001491 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001492 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001493 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001494 "Channel::ReceivedRTPPacket()");
1495
1496 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001497 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001498
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001499 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001500 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1501 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1502 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001503 return -1;
1504 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001505 header.payload_type_frequency =
1506 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001507 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001508 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001509 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001510 rtp_receive_statistics_->IncomingPacket(
1511 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001512 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001513
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001514 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001515}
1516
1517bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001518 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001519 const RTPHeader& header,
1520 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001521 if (rtp_payload_registry_->IsRtx(header)) {
1522 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001523 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001524 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001525 assert(packet_length >= header.headerLength);
1526 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001527 PayloadUnion payload_specific;
1528 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001529 &payload_specific)) {
1530 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001531 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001532 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1533 payload_specific, in_order);
1534}
1535
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001536bool Channel::HandleRtxPacket(const uint8_t* packet,
1537 size_t packet_length,
1538 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001539 if (!rtp_payload_registry_->IsRtx(header))
1540 return false;
1541
1542 // Remove the RTX header and parse the original RTP header.
1543 if (packet_length < header.headerLength)
1544 return false;
1545 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1546 return false;
1547 if (restored_packet_in_use_) {
1548 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1549 "Multiple RTX headers detected, dropping packet");
1550 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001551 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001552 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001553 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1554 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001555 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1556 "Incoming RTX packet: invalid RTP header");
1557 return false;
1558 }
1559 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001560 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001561 restored_packet_in_use_ = false;
1562 return ret;
1563}
1564
1565bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1566 StreamStatistician* statistician =
1567 rtp_receive_statistics_->GetStatistician(header.ssrc);
1568 if (!statistician)
1569 return false;
1570 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001571}
1572
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001573bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1574 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001575 // Retransmissions are handled separately if RTX is enabled.
1576 if (rtp_payload_registry_->RtxEnabled())
1577 return false;
1578 StreamStatistician* statistician =
1579 rtp_receive_statistics_->GetStatistician(header.ssrc);
1580 if (!statistician)
1581 return false;
1582 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001583 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001584 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001585 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001586}
1587
mflodman3d7db262016-04-29 00:57:13 -07001588int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001589 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001590 "Channel::ReceivedRTCPPacket()");
1591 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001592 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001593
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001594 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001595 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001596 _engineStatisticsPtr->SetLastError(
1597 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1598 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1599 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001600
Minyue2013aec2015-05-13 14:14:42 +02001601 int64_t rtt = GetRTT(true);
1602 if (rtt == 0) {
1603 // Waiting for valid RTT.
1604 return 0;
1605 }
1606 uint32_t ntp_secs = 0;
1607 uint32_t ntp_frac = 0;
1608 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001609 if (0 !=
1610 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1611 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001612 // Waiting for RTCP.
1613 return 0;
1614 }
1615
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001616 {
tommi31fc21f2016-01-21 10:37:37 -08001617 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001618 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001619 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001620 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001621}
1622
niklase@google.com470e71d2011-07-07 08:21:25 +00001623int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001624 bool loop,
1625 FileFormats format,
1626 int startPosition,
1627 float volumeScaling,
1628 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001629 const CodecInst* codecInst) {
1630 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1631 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1632 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1633 "stopPosition=%d)",
1634 fileName, loop, format, volumeScaling, startPosition,
1635 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001636
kwiberg55b97fe2016-01-28 05:22:45 -08001637 if (channel_state_.Get().output_file_playing) {
1638 _engineStatisticsPtr->SetLastError(
1639 VE_ALREADY_PLAYING, kTraceError,
1640 "StartPlayingFileLocally() is already playing");
1641 return -1;
1642 }
1643
1644 {
1645 rtc::CritScope cs(&_fileCritSect);
1646
1647 if (_outputFilePlayerPtr) {
1648 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1649 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1650 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001651 }
1652
kwiberg55b97fe2016-01-28 05:22:45 -08001653 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1654 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001655
kwiberg55b97fe2016-01-28 05:22:45 -08001656 if (_outputFilePlayerPtr == NULL) {
1657 _engineStatisticsPtr->SetLastError(
1658 VE_INVALID_ARGUMENT, kTraceError,
1659 "StartPlayingFileLocally() filePlayer format is not correct");
1660 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001661 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001662
kwiberg55b97fe2016-01-28 05:22:45 -08001663 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001664
kwiberg55b97fe2016-01-28 05:22:45 -08001665 if (_outputFilePlayerPtr->StartPlayingFile(
1666 fileName, loop, startPosition, volumeScaling, notificationTime,
1667 stopPosition, (const CodecInst*)codecInst) != 0) {
1668 _engineStatisticsPtr->SetLastError(
1669 VE_BAD_FILE, kTraceError,
1670 "StartPlayingFile() failed to start file playout");
1671 _outputFilePlayerPtr->StopPlayingFile();
1672 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1673 _outputFilePlayerPtr = NULL;
1674 return -1;
1675 }
1676 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1677 channel_state_.SetOutputFilePlaying(true);
1678 }
1679
1680 if (RegisterFilePlayingToMixer() != 0)
1681 return -1;
1682
1683 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001684}
1685
1686int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001687 FileFormats format,
1688 int startPosition,
1689 float volumeScaling,
1690 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001691 const CodecInst* codecInst) {
1692 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1693 "Channel::StartPlayingFileLocally(format=%d,"
1694 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1695 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001696
kwiberg55b97fe2016-01-28 05:22:45 -08001697 if (stream == NULL) {
1698 _engineStatisticsPtr->SetLastError(
1699 VE_BAD_FILE, kTraceError,
1700 "StartPlayingFileLocally() NULL as input stream");
1701 return -1;
1702 }
1703
1704 if (channel_state_.Get().output_file_playing) {
1705 _engineStatisticsPtr->SetLastError(
1706 VE_ALREADY_PLAYING, kTraceError,
1707 "StartPlayingFileLocally() is already playing");
1708 return -1;
1709 }
1710
1711 {
1712 rtc::CritScope cs(&_fileCritSect);
1713
1714 // Destroy the old instance
1715 if (_outputFilePlayerPtr) {
1716 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1717 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1718 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001719 }
1720
kwiberg55b97fe2016-01-28 05:22:45 -08001721 // Create the instance
1722 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1723 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001724
kwiberg55b97fe2016-01-28 05:22:45 -08001725 if (_outputFilePlayerPtr == NULL) {
1726 _engineStatisticsPtr->SetLastError(
1727 VE_INVALID_ARGUMENT, kTraceError,
1728 "StartPlayingFileLocally() filePlayer format isnot correct");
1729 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001730 }
1731
kwiberg55b97fe2016-01-28 05:22:45 -08001732 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001733
kwiberg55b97fe2016-01-28 05:22:45 -08001734 if (_outputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1735 volumeScaling, notificationTime,
1736 stopPosition, codecInst) != 0) {
1737 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1738 "StartPlayingFile() failed to "
1739 "start file playout");
1740 _outputFilePlayerPtr->StopPlayingFile();
1741 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1742 _outputFilePlayerPtr = NULL;
1743 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001744 }
kwiberg55b97fe2016-01-28 05:22:45 -08001745 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1746 channel_state_.SetOutputFilePlaying(true);
1747 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001748
kwiberg55b97fe2016-01-28 05:22:45 -08001749 if (RegisterFilePlayingToMixer() != 0)
1750 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001751
kwiberg55b97fe2016-01-28 05:22:45 -08001752 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001753}
1754
kwiberg55b97fe2016-01-28 05:22:45 -08001755int Channel::StopPlayingFileLocally() {
1756 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1757 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001758
kwiberg55b97fe2016-01-28 05:22:45 -08001759 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001760 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001761 }
1762
1763 {
1764 rtc::CritScope cs(&_fileCritSect);
1765
1766 if (_outputFilePlayerPtr->StopPlayingFile() != 0) {
1767 _engineStatisticsPtr->SetLastError(
1768 VE_STOP_RECORDING_FAILED, kTraceError,
1769 "StopPlayingFile() could not stop playing");
1770 return -1;
1771 }
1772 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1773 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1774 _outputFilePlayerPtr = NULL;
1775 channel_state_.SetOutputFilePlaying(false);
1776 }
1777 // _fileCritSect cannot be taken while calling
1778 // SetAnonymousMixibilityStatus. Refer to comments in
1779 // StartPlayingFileLocally(const char* ...) for more details.
1780 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1781 _engineStatisticsPtr->SetLastError(
1782 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1783 "StopPlayingFile() failed to stop participant from playing as"
1784 "file in the mixer");
1785 return -1;
1786 }
1787
1788 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001789}
1790
kwiberg55b97fe2016-01-28 05:22:45 -08001791int Channel::IsPlayingFileLocally() const {
1792 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001793}
1794
kwiberg55b97fe2016-01-28 05:22:45 -08001795int Channel::RegisterFilePlayingToMixer() {
1796 // Return success for not registering for file playing to mixer if:
1797 // 1. playing file before playout is started on that channel.
1798 // 2. starting playout without file playing on that channel.
1799 if (!channel_state_.Get().playing ||
1800 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001801 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001802 }
1803
1804 // |_fileCritSect| cannot be taken while calling
1805 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1806 // frames can be pulled by the mixer. Since the frames are generated from
1807 // the file, _fileCritSect will be taken. This would result in a deadlock.
1808 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1809 channel_state_.SetOutputFilePlaying(false);
1810 rtc::CritScope cs(&_fileCritSect);
1811 _engineStatisticsPtr->SetLastError(
1812 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1813 "StartPlayingFile() failed to add participant as file to mixer");
1814 _outputFilePlayerPtr->StopPlayingFile();
1815 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1816 _outputFilePlayerPtr = NULL;
1817 return -1;
1818 }
1819
1820 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001821}
1822
niklase@google.com470e71d2011-07-07 08:21:25 +00001823int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001824 bool loop,
1825 FileFormats format,
1826 int startPosition,
1827 float volumeScaling,
1828 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001829 const CodecInst* codecInst) {
1830 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1831 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1832 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1833 "stopPosition=%d)",
1834 fileName, loop, format, volumeScaling, startPosition,
1835 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001836
kwiberg55b97fe2016-01-28 05:22:45 -08001837 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001838
kwiberg55b97fe2016-01-28 05:22:45 -08001839 if (channel_state_.Get().input_file_playing) {
1840 _engineStatisticsPtr->SetLastError(
1841 VE_ALREADY_PLAYING, kTraceWarning,
1842 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001843 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001844 }
1845
1846 // Destroy the old instance
1847 if (_inputFilePlayerPtr) {
1848 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1849 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1850 _inputFilePlayerPtr = NULL;
1851 }
1852
1853 // Create the instance
1854 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1855 (const FileFormats)format);
1856
1857 if (_inputFilePlayerPtr == NULL) {
1858 _engineStatisticsPtr->SetLastError(
1859 VE_INVALID_ARGUMENT, kTraceError,
1860 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1861 return -1;
1862 }
1863
1864 const uint32_t notificationTime(0);
1865
1866 if (_inputFilePlayerPtr->StartPlayingFile(
1867 fileName, loop, startPosition, volumeScaling, notificationTime,
1868 stopPosition, (const CodecInst*)codecInst) != 0) {
1869 _engineStatisticsPtr->SetLastError(
1870 VE_BAD_FILE, kTraceError,
1871 "StartPlayingFile() failed to start file playout");
1872 _inputFilePlayerPtr->StopPlayingFile();
1873 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1874 _inputFilePlayerPtr = NULL;
1875 return -1;
1876 }
1877 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1878 channel_state_.SetInputFilePlaying(true);
1879
1880 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001881}
1882
1883int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001884 FileFormats format,
1885 int startPosition,
1886 float volumeScaling,
1887 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001888 const CodecInst* codecInst) {
1889 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1890 "Channel::StartPlayingFileAsMicrophone(format=%d, "
1891 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1892 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001893
kwiberg55b97fe2016-01-28 05:22:45 -08001894 if (stream == NULL) {
1895 _engineStatisticsPtr->SetLastError(
1896 VE_BAD_FILE, kTraceError,
1897 "StartPlayingFileAsMicrophone NULL as input stream");
1898 return -1;
1899 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001900
kwiberg55b97fe2016-01-28 05:22:45 -08001901 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001902
kwiberg55b97fe2016-01-28 05:22:45 -08001903 if (channel_state_.Get().input_file_playing) {
1904 _engineStatisticsPtr->SetLastError(
1905 VE_ALREADY_PLAYING, kTraceWarning,
1906 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001907 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001908 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001909
kwiberg55b97fe2016-01-28 05:22:45 -08001910 // Destroy the old instance
1911 if (_inputFilePlayerPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001912 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1913 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1914 _inputFilePlayerPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001915 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001916
kwiberg55b97fe2016-01-28 05:22:45 -08001917 // Create the instance
1918 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1919 (const FileFormats)format);
1920
1921 if (_inputFilePlayerPtr == NULL) {
1922 _engineStatisticsPtr->SetLastError(
1923 VE_INVALID_ARGUMENT, kTraceError,
1924 "StartPlayingInputFile() filePlayer format isnot correct");
1925 return -1;
1926 }
1927
1928 const uint32_t notificationTime(0);
1929
1930 if (_inputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1931 volumeScaling, notificationTime,
1932 stopPosition, codecInst) != 0) {
1933 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1934 "StartPlayingFile() failed to start "
1935 "file playout");
1936 _inputFilePlayerPtr->StopPlayingFile();
1937 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1938 _inputFilePlayerPtr = NULL;
1939 return -1;
1940 }
1941
1942 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1943 channel_state_.SetInputFilePlaying(true);
1944
1945 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001946}
1947
kwiberg55b97fe2016-01-28 05:22:45 -08001948int Channel::StopPlayingFileAsMicrophone() {
1949 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1950 "Channel::StopPlayingFileAsMicrophone()");
1951
1952 rtc::CritScope cs(&_fileCritSect);
1953
1954 if (!channel_state_.Get().input_file_playing) {
1955 return 0;
1956 }
1957
1958 if (_inputFilePlayerPtr->StopPlayingFile() != 0) {
1959 _engineStatisticsPtr->SetLastError(
1960 VE_STOP_RECORDING_FAILED, kTraceError,
1961 "StopPlayingFile() could not stop playing");
1962 return -1;
1963 }
1964 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1965 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1966 _inputFilePlayerPtr = NULL;
1967 channel_state_.SetInputFilePlaying(false);
1968
1969 return 0;
1970}
1971
1972int Channel::IsPlayingFileAsMicrophone() const {
1973 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001974}
1975
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00001976int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08001977 const CodecInst* codecInst) {
1978 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1979 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00001980
kwiberg55b97fe2016-01-28 05:22:45 -08001981 if (_outputFileRecording) {
1982 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
1983 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00001984 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001985 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001986
kwiberg55b97fe2016-01-28 05:22:45 -08001987 FileFormats format;
1988 const uint32_t notificationTime(0); // Not supported in VoE
1989 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00001990
kwiberg55b97fe2016-01-28 05:22:45 -08001991 if ((codecInst != NULL) &&
1992 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
1993 _engineStatisticsPtr->SetLastError(
1994 VE_BAD_ARGUMENT, kTraceError,
1995 "StartRecordingPlayout() invalid compression");
1996 return (-1);
1997 }
1998 if (codecInst == NULL) {
1999 format = kFileFormatPcm16kHzFile;
2000 codecInst = &dummyCodec;
2001 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2002 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2003 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2004 format = kFileFormatWavFile;
2005 } else {
2006 format = kFileFormatCompressedFile;
2007 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002008
kwiberg55b97fe2016-01-28 05:22:45 -08002009 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002010
kwiberg55b97fe2016-01-28 05:22:45 -08002011 // Destroy the old instance
2012 if (_outputFileRecorderPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002013 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2014 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2015 _outputFileRecorderPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08002016 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002017
kwiberg55b97fe2016-01-28 05:22:45 -08002018 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2019 _outputFileRecorderId, (const FileFormats)format);
2020 if (_outputFileRecorderPtr == NULL) {
2021 _engineStatisticsPtr->SetLastError(
2022 VE_INVALID_ARGUMENT, kTraceError,
2023 "StartRecordingPlayout() fileRecorder format isnot correct");
2024 return -1;
2025 }
2026
2027 if (_outputFileRecorderPtr->StartRecordingAudioFile(
2028 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2029 _engineStatisticsPtr->SetLastError(
2030 VE_BAD_FILE, kTraceError,
2031 "StartRecordingAudioFile() failed to start file recording");
2032 _outputFileRecorderPtr->StopRecording();
2033 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2034 _outputFileRecorderPtr = NULL;
2035 return -1;
2036 }
2037 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2038 _outputFileRecording = true;
2039
2040 return 0;
2041}
2042
2043int Channel::StartRecordingPlayout(OutStream* stream,
2044 const CodecInst* codecInst) {
2045 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2046 "Channel::StartRecordingPlayout()");
2047
2048 if (_outputFileRecording) {
2049 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2050 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002051 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002052 }
2053
2054 FileFormats format;
2055 const uint32_t notificationTime(0); // Not supported in VoE
2056 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2057
2058 if (codecInst != NULL && codecInst->channels != 1) {
2059 _engineStatisticsPtr->SetLastError(
2060 VE_BAD_ARGUMENT, kTraceError,
2061 "StartRecordingPlayout() invalid compression");
2062 return (-1);
2063 }
2064 if (codecInst == NULL) {
2065 format = kFileFormatPcm16kHzFile;
2066 codecInst = &dummyCodec;
2067 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2068 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2069 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2070 format = kFileFormatWavFile;
2071 } else {
2072 format = kFileFormatCompressedFile;
2073 }
2074
2075 rtc::CritScope cs(&_fileCritSect);
2076
2077 // Destroy the old instance
2078 if (_outputFileRecorderPtr) {
2079 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2080 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2081 _outputFileRecorderPtr = NULL;
2082 }
2083
2084 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2085 _outputFileRecorderId, (const FileFormats)format);
2086 if (_outputFileRecorderPtr == NULL) {
2087 _engineStatisticsPtr->SetLastError(
2088 VE_INVALID_ARGUMENT, kTraceError,
2089 "StartRecordingPlayout() fileRecorder format isnot correct");
2090 return -1;
2091 }
2092
2093 if (_outputFileRecorderPtr->StartRecordingAudioFile(*stream, *codecInst,
2094 notificationTime) != 0) {
2095 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2096 "StartRecordingPlayout() failed to "
2097 "start file recording");
2098 _outputFileRecorderPtr->StopRecording();
2099 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2100 _outputFileRecorderPtr = NULL;
2101 return -1;
2102 }
2103
2104 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2105 _outputFileRecording = true;
2106
2107 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002108}
2109
kwiberg55b97fe2016-01-28 05:22:45 -08002110int Channel::StopRecordingPlayout() {
2111 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2112 "Channel::StopRecordingPlayout()");
2113
2114 if (!_outputFileRecording) {
2115 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2116 "StopRecordingPlayout() isnot recording");
2117 return -1;
2118 }
2119
2120 rtc::CritScope cs(&_fileCritSect);
2121
2122 if (_outputFileRecorderPtr->StopRecording() != 0) {
2123 _engineStatisticsPtr->SetLastError(
2124 VE_STOP_RECORDING_FAILED, kTraceError,
2125 "StopRecording() could not stop recording");
2126 return (-1);
2127 }
2128 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2129 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2130 _outputFileRecorderPtr = NULL;
2131 _outputFileRecording = false;
2132
2133 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002134}
2135
kwiberg55b97fe2016-01-28 05:22:45 -08002136void Channel::SetMixWithMicStatus(bool mix) {
2137 rtc::CritScope cs(&_fileCritSect);
2138 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002139}
2140
kwiberg55b97fe2016-01-28 05:22:45 -08002141int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2142 int8_t currentLevel = _outputAudioLevel.Level();
2143 level = static_cast<int32_t>(currentLevel);
2144 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002145}
2146
kwiberg55b97fe2016-01-28 05:22:45 -08002147int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2148 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2149 level = static_cast<int32_t>(currentLevel);
2150 return 0;
2151}
2152
solenberg1c2af8e2016-03-24 10:36:00 -07002153int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002154 rtc::CritScope cs(&volume_settings_critsect_);
2155 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002156 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002157 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002158 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002159}
2160
solenberg1c2af8e2016-03-24 10:36:00 -07002161bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002162 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002163 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002164}
2165
kwiberg55b97fe2016-01-28 05:22:45 -08002166int Channel::SetOutputVolumePan(float left, float right) {
2167 rtc::CritScope cs(&volume_settings_critsect_);
2168 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002169 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002170 _panLeft = left;
2171 _panRight = right;
2172 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002173}
2174
kwiberg55b97fe2016-01-28 05:22:45 -08002175int Channel::GetOutputVolumePan(float& left, float& right) const {
2176 rtc::CritScope cs(&volume_settings_critsect_);
2177 left = _panLeft;
2178 right = _panRight;
2179 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002180}
2181
kwiberg55b97fe2016-01-28 05:22:45 -08002182int Channel::SetChannelOutputVolumeScaling(float scaling) {
2183 rtc::CritScope cs(&volume_settings_critsect_);
2184 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002185 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002186 _outputGain = scaling;
2187 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002188}
2189
kwiberg55b97fe2016-01-28 05:22:45 -08002190int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2191 rtc::CritScope cs(&volume_settings_critsect_);
2192 scaling = _outputGain;
2193 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002194}
2195
solenberg8842c3e2016-03-11 03:06:41 -08002196int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002197 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002198 "Channel::SendTelephoneEventOutband(...)");
2199 RTC_DCHECK_LE(0, event);
2200 RTC_DCHECK_GE(255, event);
2201 RTC_DCHECK_LE(0, duration_ms);
2202 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002203 if (!Sending()) {
2204 return -1;
2205 }
solenberg8842c3e2016-03-11 03:06:41 -08002206 if (_rtpRtcpModule->SendTelephoneEventOutband(
2207 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002208 _engineStatisticsPtr->SetLastError(
2209 VE_SEND_DTMF_FAILED, kTraceWarning,
2210 "SendTelephoneEventOutband() failed to send event");
2211 return -1;
2212 }
2213 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002214}
2215
solenberg31642aa2016-03-14 08:00:37 -07002216int Channel::SetSendTelephoneEventPayloadType(int payload_type) {
kwiberg55b97fe2016-01-28 05:22:45 -08002217 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002218 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002219 RTC_DCHECK_LE(0, payload_type);
2220 RTC_DCHECK_GE(127, payload_type);
2221 CodecInst codec = {0};
kwiberg55b97fe2016-01-28 05:22:45 -08002222 codec.plfreq = 8000;
solenberg31642aa2016-03-14 08:00:37 -07002223 codec.pltype = payload_type;
kwiberg55b97fe2016-01-28 05:22:45 -08002224 memcpy(codec.plname, "telephone-event", 16);
2225 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2226 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2227 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2228 _engineStatisticsPtr->SetLastError(
2229 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2230 "SetSendTelephoneEventPayloadType() failed to register send"
2231 "payload type");
2232 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002233 }
kwiberg55b97fe2016-01-28 05:22:45 -08002234 }
kwiberg55b97fe2016-01-28 05:22:45 -08002235 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002236}
2237
kwiberg55b97fe2016-01-28 05:22:45 -08002238int Channel::UpdateRxVadDetection(AudioFrame& audioFrame) {
2239 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2240 "Channel::UpdateRxVadDetection()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002241
kwiberg55b97fe2016-01-28 05:22:45 -08002242 int vadDecision = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002243
kwiberg55b97fe2016-01-28 05:22:45 -08002244 vadDecision = (audioFrame.vad_activity_ == AudioFrame::kVadActive) ? 1 : 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002245
kwiberg55b97fe2016-01-28 05:22:45 -08002246 if ((vadDecision != _oldVadDecision) && _rxVadObserverPtr) {
2247 OnRxVadDetected(vadDecision);
2248 _oldVadDecision = vadDecision;
2249 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002250
kwiberg55b97fe2016-01-28 05:22:45 -08002251 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2252 "Channel::UpdateRxVadDetection() => vadDecision=%d",
2253 vadDecision);
2254 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002255}
2256
kwiberg55b97fe2016-01-28 05:22:45 -08002257int Channel::RegisterRxVadObserver(VoERxVadCallback& observer) {
2258 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2259 "Channel::RegisterRxVadObserver()");
2260 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002261
kwiberg55b97fe2016-01-28 05:22:45 -08002262 if (_rxVadObserverPtr) {
2263 _engineStatisticsPtr->SetLastError(
2264 VE_INVALID_OPERATION, kTraceError,
2265 "RegisterRxVadObserver() observer already enabled");
2266 return -1;
2267 }
2268 _rxVadObserverPtr = &observer;
2269 _RxVadDetection = true;
2270 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002271}
2272
kwiberg55b97fe2016-01-28 05:22:45 -08002273int Channel::DeRegisterRxVadObserver() {
2274 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2275 "Channel::DeRegisterRxVadObserver()");
2276 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002277
kwiberg55b97fe2016-01-28 05:22:45 -08002278 if (!_rxVadObserverPtr) {
2279 _engineStatisticsPtr->SetLastError(
2280 VE_INVALID_OPERATION, kTraceWarning,
2281 "DeRegisterRxVadObserver() observer already disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00002282 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002283 }
2284 _rxVadObserverPtr = NULL;
2285 _RxVadDetection = false;
2286 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002287}
2288
kwiberg55b97fe2016-01-28 05:22:45 -08002289int Channel::VoiceActivityIndicator(int& activity) {
2290 activity = _sendFrameType;
2291 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002292}
2293
2294#ifdef WEBRTC_VOICE_ENGINE_AGC
2295
kwiberg55b97fe2016-01-28 05:22:45 -08002296int Channel::SetRxAgcStatus(bool enable, AgcModes mode) {
2297 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2298 "Channel::SetRxAgcStatus(enable=%d, mode=%d)", (int)enable,
2299 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002300
kwiberg55b97fe2016-01-28 05:22:45 -08002301 GainControl::Mode agcMode = kDefaultRxAgcMode;
2302 switch (mode) {
2303 case kAgcDefault:
2304 break;
2305 case kAgcUnchanged:
2306 agcMode = rx_audioproc_->gain_control()->mode();
2307 break;
2308 case kAgcFixedDigital:
2309 agcMode = GainControl::kFixedDigital;
2310 break;
2311 case kAgcAdaptiveDigital:
2312 agcMode = GainControl::kAdaptiveDigital;
2313 break;
2314 default:
2315 _engineStatisticsPtr->SetLastError(VE_INVALID_ARGUMENT, kTraceError,
2316 "SetRxAgcStatus() invalid Agc mode");
2317 return -1;
2318 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002319
kwiberg55b97fe2016-01-28 05:22:45 -08002320 if (rx_audioproc_->gain_control()->set_mode(agcMode) != 0) {
2321 _engineStatisticsPtr->SetLastError(
2322 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc mode");
2323 return -1;
2324 }
2325 if (rx_audioproc_->gain_control()->Enable(enable) != 0) {
2326 _engineStatisticsPtr->SetLastError(
2327 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc state");
2328 return -1;
2329 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002330
kwiberg55b97fe2016-01-28 05:22:45 -08002331 _rxAgcIsEnabled = enable;
2332 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002333
kwiberg55b97fe2016-01-28 05:22:45 -08002334 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002335}
2336
kwiberg55b97fe2016-01-28 05:22:45 -08002337int Channel::GetRxAgcStatus(bool& enabled, AgcModes& mode) {
2338 bool enable = rx_audioproc_->gain_control()->is_enabled();
2339 GainControl::Mode agcMode = rx_audioproc_->gain_control()->mode();
niklase@google.com470e71d2011-07-07 08:21:25 +00002340
kwiberg55b97fe2016-01-28 05:22:45 -08002341 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002342
kwiberg55b97fe2016-01-28 05:22:45 -08002343 switch (agcMode) {
2344 case GainControl::kFixedDigital:
2345 mode = kAgcFixedDigital;
2346 break;
2347 case GainControl::kAdaptiveDigital:
2348 mode = kAgcAdaptiveDigital;
2349 break;
2350 default:
2351 _engineStatisticsPtr->SetLastError(VE_APM_ERROR, kTraceError,
2352 "GetRxAgcStatus() invalid Agc mode");
2353 return -1;
2354 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002355
kwiberg55b97fe2016-01-28 05:22:45 -08002356 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002357}
2358
kwiberg55b97fe2016-01-28 05:22:45 -08002359int Channel::SetRxAgcConfig(AgcConfig config) {
2360 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2361 "Channel::SetRxAgcConfig()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002362
kwiberg55b97fe2016-01-28 05:22:45 -08002363 if (rx_audioproc_->gain_control()->set_target_level_dbfs(
2364 config.targetLeveldBOv) != 0) {
2365 _engineStatisticsPtr->SetLastError(
2366 VE_APM_ERROR, kTraceError,
2367 "SetRxAgcConfig() failed to set target peak |level|"
2368 "(or envelope) of the Agc");
2369 return -1;
2370 }
2371 if (rx_audioproc_->gain_control()->set_compression_gain_db(
2372 config.digitalCompressionGaindB) != 0) {
2373 _engineStatisticsPtr->SetLastError(
2374 VE_APM_ERROR, kTraceError,
2375 "SetRxAgcConfig() failed to set the range in |gain| the"
2376 " digital compression stage may apply");
2377 return -1;
2378 }
2379 if (rx_audioproc_->gain_control()->enable_limiter(config.limiterEnable) !=
2380 0) {
2381 _engineStatisticsPtr->SetLastError(
2382 VE_APM_ERROR, kTraceError,
2383 "SetRxAgcConfig() failed to set hard limiter to the signal");
2384 return -1;
2385 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002386
kwiberg55b97fe2016-01-28 05:22:45 -08002387 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002388}
2389
kwiberg55b97fe2016-01-28 05:22:45 -08002390int Channel::GetRxAgcConfig(AgcConfig& config) {
2391 config.targetLeveldBOv = rx_audioproc_->gain_control()->target_level_dbfs();
2392 config.digitalCompressionGaindB =
2393 rx_audioproc_->gain_control()->compression_gain_db();
2394 config.limiterEnable = rx_audioproc_->gain_control()->is_limiter_enabled();
niklase@google.com470e71d2011-07-07 08:21:25 +00002395
kwiberg55b97fe2016-01-28 05:22:45 -08002396 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002397}
2398
kwiberg55b97fe2016-01-28 05:22:45 -08002399#endif // #ifdef WEBRTC_VOICE_ENGINE_AGC
niklase@google.com470e71d2011-07-07 08:21:25 +00002400
2401#ifdef WEBRTC_VOICE_ENGINE_NR
2402
kwiberg55b97fe2016-01-28 05:22:45 -08002403int Channel::SetRxNsStatus(bool enable, NsModes mode) {
2404 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2405 "Channel::SetRxNsStatus(enable=%d, mode=%d)", (int)enable,
2406 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002407
kwiberg55b97fe2016-01-28 05:22:45 -08002408 NoiseSuppression::Level nsLevel = kDefaultNsMode;
2409 switch (mode) {
2410 case kNsDefault:
2411 break;
2412 case kNsUnchanged:
2413 nsLevel = rx_audioproc_->noise_suppression()->level();
2414 break;
2415 case kNsConference:
2416 nsLevel = NoiseSuppression::kHigh;
2417 break;
2418 case kNsLowSuppression:
2419 nsLevel = NoiseSuppression::kLow;
2420 break;
2421 case kNsModerateSuppression:
2422 nsLevel = NoiseSuppression::kModerate;
2423 break;
2424 case kNsHighSuppression:
2425 nsLevel = NoiseSuppression::kHigh;
2426 break;
2427 case kNsVeryHighSuppression:
2428 nsLevel = NoiseSuppression::kVeryHigh;
2429 break;
2430 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002431
kwiberg55b97fe2016-01-28 05:22:45 -08002432 if (rx_audioproc_->noise_suppression()->set_level(nsLevel) != 0) {
2433 _engineStatisticsPtr->SetLastError(
2434 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS level");
2435 return -1;
2436 }
2437 if (rx_audioproc_->noise_suppression()->Enable(enable) != 0) {
2438 _engineStatisticsPtr->SetLastError(
2439 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS state");
2440 return -1;
2441 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002442
kwiberg55b97fe2016-01-28 05:22:45 -08002443 _rxNsIsEnabled = enable;
2444 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002445
kwiberg55b97fe2016-01-28 05:22:45 -08002446 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002447}
2448
kwiberg55b97fe2016-01-28 05:22:45 -08002449int Channel::GetRxNsStatus(bool& enabled, NsModes& mode) {
2450 bool enable = rx_audioproc_->noise_suppression()->is_enabled();
2451 NoiseSuppression::Level ncLevel = rx_audioproc_->noise_suppression()->level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002452
kwiberg55b97fe2016-01-28 05:22:45 -08002453 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002454
kwiberg55b97fe2016-01-28 05:22:45 -08002455 switch (ncLevel) {
2456 case NoiseSuppression::kLow:
2457 mode = kNsLowSuppression;
2458 break;
2459 case NoiseSuppression::kModerate:
2460 mode = kNsModerateSuppression;
2461 break;
2462 case NoiseSuppression::kHigh:
2463 mode = kNsHighSuppression;
2464 break;
2465 case NoiseSuppression::kVeryHigh:
2466 mode = kNsVeryHighSuppression;
2467 break;
2468 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002469
kwiberg55b97fe2016-01-28 05:22:45 -08002470 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002471}
2472
kwiberg55b97fe2016-01-28 05:22:45 -08002473#endif // #ifdef WEBRTC_VOICE_ENGINE_NR
niklase@google.com470e71d2011-07-07 08:21:25 +00002474
kwiberg55b97fe2016-01-28 05:22:45 -08002475int Channel::SetLocalSSRC(unsigned int ssrc) {
2476 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2477 "Channel::SetLocalSSRC()");
2478 if (channel_state_.Get().sending) {
2479 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2480 "SetLocalSSRC() already sending");
2481 return -1;
2482 }
2483 _rtpRtcpModule->SetSSRC(ssrc);
2484 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002485}
2486
kwiberg55b97fe2016-01-28 05:22:45 -08002487int Channel::GetLocalSSRC(unsigned int& ssrc) {
2488 ssrc = _rtpRtcpModule->SSRC();
2489 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002490}
2491
kwiberg55b97fe2016-01-28 05:22:45 -08002492int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2493 ssrc = rtp_receiver_->SSRC();
2494 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002495}
2496
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002497int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002498 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002499 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002500}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002501
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002502int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2503 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002504 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2505 if (enable &&
2506 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2507 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002508 return -1;
2509 }
2510 return 0;
2511}
2512
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002513int Channel::SetSendAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2514 return SetSendRtpHeaderExtension(enable, kRtpExtensionAbsoluteSendTime, id);
2515}
2516
2517int Channel::SetReceiveAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2518 rtp_header_parser_->DeregisterRtpHeaderExtension(
2519 kRtpExtensionAbsoluteSendTime);
kwiberg55b97fe2016-01-28 05:22:45 -08002520 if (enable &&
2521 !rtp_header_parser_->RegisterRtpHeaderExtension(
2522 kRtpExtensionAbsoluteSendTime, id)) {
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00002523 return -1;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002524 }
2525 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002526}
2527
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002528void Channel::EnableSendTransportSequenceNumber(int id) {
2529 int ret =
2530 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2531 RTC_DCHECK_EQ(0, ret);
2532}
2533
stefan3313ec92016-01-21 06:32:43 -08002534void Channel::EnableReceiveTransportSequenceNumber(int id) {
2535 rtp_header_parser_->DeregisterRtpHeaderExtension(
2536 kRtpExtensionTransportSequenceNumber);
2537 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2538 kRtpExtensionTransportSequenceNumber, id);
2539 RTC_DCHECK(ret);
2540}
2541
stefanbba9dec2016-02-01 04:39:55 -08002542void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002543 RtpPacketSender* rtp_packet_sender,
2544 TransportFeedbackObserver* transport_feedback_observer,
2545 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002546 RTC_DCHECK(rtp_packet_sender);
2547 RTC_DCHECK(transport_feedback_observer);
2548 RTC_DCHECK(packet_router && !packet_router_);
2549 feedback_observer_proxy_->SetTransportFeedbackObserver(
2550 transport_feedback_observer);
2551 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2552 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2553 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002554 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002555 packet_router_ = packet_router;
2556}
2557
stefanbba9dec2016-02-01 04:39:55 -08002558void Channel::RegisterReceiverCongestionControlObjects(
2559 PacketRouter* packet_router) {
2560 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002561 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002562 packet_router_ = packet_router;
2563}
2564
2565void Channel::ResetCongestionControlObjects() {
2566 RTC_DCHECK(packet_router_);
2567 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2568 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2569 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002570 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002571 packet_router_ = nullptr;
2572 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2573}
2574
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002575void Channel::SetRTCPStatus(bool enable) {
2576 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2577 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002578 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002579}
2580
kwiberg55b97fe2016-01-28 05:22:45 -08002581int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002582 RtcpMode method = _rtpRtcpModule->RTCP();
2583 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002584 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002585}
2586
kwiberg55b97fe2016-01-28 05:22:45 -08002587int Channel::SetRTCP_CNAME(const char cName[256]) {
2588 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2589 "Channel::SetRTCP_CNAME()");
2590 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2591 _engineStatisticsPtr->SetLastError(
2592 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2593 "SetRTCP_CNAME() failed to set RTCP CNAME");
2594 return -1;
2595 }
2596 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002597}
2598
kwiberg55b97fe2016-01-28 05:22:45 -08002599int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2600 if (cName == NULL) {
2601 _engineStatisticsPtr->SetLastError(
2602 VE_INVALID_ARGUMENT, kTraceError,
2603 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2604 return -1;
2605 }
2606 char cname[RTCP_CNAME_SIZE];
2607 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2608 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2609 _engineStatisticsPtr->SetLastError(
2610 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2611 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2612 return -1;
2613 }
2614 strcpy(cName, cname);
2615 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002616}
2617
kwiberg55b97fe2016-01-28 05:22:45 -08002618int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2619 unsigned int& NTPLow,
2620 unsigned int& timestamp,
2621 unsigned int& playoutTimestamp,
2622 unsigned int* jitter,
2623 unsigned short* fractionLost) {
2624 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002625
kwiberg55b97fe2016-01-28 05:22:45 -08002626 RTCPSenderInfo senderInfo;
2627 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2628 _engineStatisticsPtr->SetLastError(
2629 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2630 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2631 "side");
2632 return -1;
2633 }
2634
2635 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2636 // and octet count)
2637 NTPHigh = senderInfo.NTPseconds;
2638 NTPLow = senderInfo.NTPfraction;
2639 timestamp = senderInfo.RTPtimeStamp;
2640
2641 // --- Locally derived information
2642
2643 // This value is updated on each incoming RTCP packet (0 when no packet
2644 // has been received)
2645 playoutTimestamp = playout_timestamp_rtcp_;
2646
2647 if (NULL != jitter || NULL != fractionLost) {
2648 // Get all RTCP receiver report blocks that have been received on this
2649 // channel. If we receive RTP packets from a remote source we know the
2650 // remote SSRC and use the report block from him.
2651 // Otherwise use the first report block.
2652 std::vector<RTCPReportBlock> remote_stats;
2653 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2654 remote_stats.empty()) {
2655 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2656 "GetRemoteRTCPData() failed to measure statistics due"
2657 " to lack of received RTP and/or RTCP packets");
2658 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002659 }
2660
kwiberg55b97fe2016-01-28 05:22:45 -08002661 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2662 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2663 for (; it != remote_stats.end(); ++it) {
2664 if (it->remoteSSRC == remoteSSRC)
2665 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002666 }
kwiberg55b97fe2016-01-28 05:22:45 -08002667
2668 if (it == remote_stats.end()) {
2669 // If we have not received any RTCP packets from this SSRC it probably
2670 // means that we have not received any RTP packets.
2671 // Use the first received report block instead.
2672 it = remote_stats.begin();
2673 remoteSSRC = it->remoteSSRC;
2674 }
2675
2676 if (jitter) {
2677 *jitter = it->jitter;
2678 }
2679
2680 if (fractionLost) {
2681 *fractionLost = it->fractionLost;
2682 }
2683 }
2684 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002685}
2686
kwiberg55b97fe2016-01-28 05:22:45 -08002687int Channel::SendApplicationDefinedRTCPPacket(
2688 unsigned char subType,
2689 unsigned int name,
2690 const char* data,
2691 unsigned short dataLengthInBytes) {
2692 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2693 "Channel::SendApplicationDefinedRTCPPacket()");
2694 if (!channel_state_.Get().sending) {
2695 _engineStatisticsPtr->SetLastError(
2696 VE_NOT_SENDING, kTraceError,
2697 "SendApplicationDefinedRTCPPacket() not sending");
2698 return -1;
2699 }
2700 if (NULL == data) {
2701 _engineStatisticsPtr->SetLastError(
2702 VE_INVALID_ARGUMENT, kTraceError,
2703 "SendApplicationDefinedRTCPPacket() invalid data value");
2704 return -1;
2705 }
2706 if (dataLengthInBytes % 4 != 0) {
2707 _engineStatisticsPtr->SetLastError(
2708 VE_INVALID_ARGUMENT, kTraceError,
2709 "SendApplicationDefinedRTCPPacket() invalid length value");
2710 return -1;
2711 }
2712 RtcpMode status = _rtpRtcpModule->RTCP();
2713 if (status == RtcpMode::kOff) {
2714 _engineStatisticsPtr->SetLastError(
2715 VE_RTCP_ERROR, kTraceError,
2716 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2717 return -1;
2718 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002719
kwiberg55b97fe2016-01-28 05:22:45 -08002720 // Create and schedule the RTCP APP packet for transmission
2721 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2722 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2723 _engineStatisticsPtr->SetLastError(
2724 VE_SEND_ERROR, kTraceError,
2725 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2726 return -1;
2727 }
2728 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002729}
2730
kwiberg55b97fe2016-01-28 05:22:45 -08002731int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2732 unsigned int& maxJitterMs,
2733 unsigned int& discardedPackets) {
2734 // The jitter statistics is updated for each received RTP packet and is
2735 // based on received packets.
2736 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2737 // If RTCP is off, there is no timed thread in the RTCP module regularly
2738 // generating new stats, trigger the update manually here instead.
2739 StreamStatistician* statistician =
2740 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2741 if (statistician) {
2742 // Don't use returned statistics, use data from proxy instead so that
2743 // max jitter can be fetched atomically.
2744 RtcpStatistics s;
2745 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002746 }
kwiberg55b97fe2016-01-28 05:22:45 -08002747 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002748
kwiberg55b97fe2016-01-28 05:22:45 -08002749 ChannelStatistics stats = statistics_proxy_->GetStats();
2750 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2751 if (playoutFrequency > 0) {
2752 // Scale RTP statistics given the current playout frequency
2753 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2754 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2755 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002756
kwiberg55b97fe2016-01-28 05:22:45 -08002757 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002758
kwiberg55b97fe2016-01-28 05:22:45 -08002759 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002760}
2761
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002762int Channel::GetRemoteRTCPReportBlocks(
2763 std::vector<ReportBlock>* report_blocks) {
2764 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002765 _engineStatisticsPtr->SetLastError(
2766 VE_INVALID_ARGUMENT, kTraceError,
2767 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002768 return -1;
2769 }
2770
2771 // Get the report blocks from the latest received RTCP Sender or Receiver
2772 // Report. Each element in the vector contains the sender's SSRC and a
2773 // report block according to RFC 3550.
2774 std::vector<RTCPReportBlock> rtcp_report_blocks;
2775 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002776 return -1;
2777 }
2778
2779 if (rtcp_report_blocks.empty())
2780 return 0;
2781
2782 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2783 for (; it != rtcp_report_blocks.end(); ++it) {
2784 ReportBlock report_block;
2785 report_block.sender_SSRC = it->remoteSSRC;
2786 report_block.source_SSRC = it->sourceSSRC;
2787 report_block.fraction_lost = it->fractionLost;
2788 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2789 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2790 report_block.interarrival_jitter = it->jitter;
2791 report_block.last_SR_timestamp = it->lastSR;
2792 report_block.delay_since_last_SR = it->delaySinceLastSR;
2793 report_blocks->push_back(report_block);
2794 }
2795 return 0;
2796}
2797
kwiberg55b97fe2016-01-28 05:22:45 -08002798int Channel::GetRTPStatistics(CallStatistics& stats) {
2799 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002800
kwiberg55b97fe2016-01-28 05:22:45 -08002801 // The jitter statistics is updated for each received RTP packet and is
2802 // based on received packets.
2803 RtcpStatistics statistics;
2804 StreamStatistician* statistician =
2805 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002806 if (statistician) {
2807 statistician->GetStatistics(&statistics,
2808 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002809 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002810
kwiberg55b97fe2016-01-28 05:22:45 -08002811 stats.fractionLost = statistics.fraction_lost;
2812 stats.cumulativeLost = statistics.cumulative_lost;
2813 stats.extendedMax = statistics.extended_max_sequence_number;
2814 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002815
kwiberg55b97fe2016-01-28 05:22:45 -08002816 // --- RTT
2817 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002818
kwiberg55b97fe2016-01-28 05:22:45 -08002819 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002820
kwiberg55b97fe2016-01-28 05:22:45 -08002821 size_t bytesSent(0);
2822 uint32_t packetsSent(0);
2823 size_t bytesReceived(0);
2824 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002825
kwiberg55b97fe2016-01-28 05:22:45 -08002826 if (statistician) {
2827 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2828 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002829
kwiberg55b97fe2016-01-28 05:22:45 -08002830 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2831 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2832 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2833 " output will not be complete");
2834 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002835
kwiberg55b97fe2016-01-28 05:22:45 -08002836 stats.bytesSent = bytesSent;
2837 stats.packetsSent = packetsSent;
2838 stats.bytesReceived = bytesReceived;
2839 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002840
kwiberg55b97fe2016-01-28 05:22:45 -08002841 // --- Timestamps
2842 {
2843 rtc::CritScope lock(&ts_stats_lock_);
2844 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2845 }
2846 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002847}
2848
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002849int Channel::SetREDStatus(bool enable, int redPayloadtype) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002850 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002851 "Channel::SetREDStatus()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002852
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002853 if (enable) {
2854 if (redPayloadtype < 0 || redPayloadtype > 127) {
2855 _engineStatisticsPtr->SetLastError(
2856 VE_PLTYPE_ERROR, kTraceError,
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002857 "SetREDStatus() invalid RED payload type");
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002858 return -1;
2859 }
2860
2861 if (SetRedPayloadType(redPayloadtype) < 0) {
2862 _engineStatisticsPtr->SetLastError(
2863 VE_CODEC_ERROR, kTraceError,
2864 "SetSecondarySendCodec() Failed to register RED ACM");
2865 return -1;
2866 }
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002867 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002868
kwibergc8d071e2016-04-06 12:22:38 -07002869 if (!codec_manager_.SetCopyRed(enable) ||
2870 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002871 _engineStatisticsPtr->SetLastError(
2872 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgaa5ea1c2014-05-23 15:16:51 +00002873 "SetREDStatus() failed to set RED state in the ACM");
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002874 return -1;
2875 }
2876 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002877}
2878
kwiberg55b97fe2016-01-28 05:22:45 -08002879int Channel::GetREDStatus(bool& enabled, int& redPayloadtype) {
kwibergc8d071e2016-04-06 12:22:38 -07002880 enabled = codec_manager_.GetStackParams()->use_red;
kwiberg55b97fe2016-01-28 05:22:45 -08002881 if (enabled) {
2882 int8_t payloadType = 0;
2883 if (_rtpRtcpModule->SendREDPayloadType(&payloadType) != 0) {
2884 _engineStatisticsPtr->SetLastError(
2885 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2886 "GetREDStatus() failed to retrieve RED PT from RTP/RTCP "
2887 "module");
2888 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002889 }
kwiberg55b97fe2016-01-28 05:22:45 -08002890 redPayloadtype = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +00002891 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002892 }
2893 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002894}
2895
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002896int Channel::SetCodecFECStatus(bool enable) {
2897 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2898 "Channel::SetCodecFECStatus()");
2899
kwibergc8d071e2016-04-06 12:22:38 -07002900 if (!codec_manager_.SetCodecFEC(enable) ||
2901 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002902 _engineStatisticsPtr->SetLastError(
2903 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2904 "SetCodecFECStatus() failed to set FEC state");
2905 return -1;
2906 }
2907 return 0;
2908}
2909
2910bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002911 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002912}
2913
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002914void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2915 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002916 // If pacing is enabled we always store packets.
2917 if (!pacing_enabled_)
2918 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002919 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002920 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002921 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002922 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002923 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002924}
2925
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002926// Called when we are missing one or more packets.
2927int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002928 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2929}
2930
kwiberg55b97fe2016-01-28 05:22:45 -08002931uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2932 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2933 "Channel::Demultiplex()");
2934 _audioFrame.CopyFrom(audioFrame);
2935 _audioFrame.id_ = _channelId;
2936 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002937}
2938
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002939void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002940 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002941 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002942 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002943 CodecInst codec;
2944 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002945
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002946 // Never upsample or upmix the capture signal here. This should be done at the
2947 // end of the send chain.
2948 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2949 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2950 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2951 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002952}
2953
kwiberg55b97fe2016-01-28 05:22:45 -08002954uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2955 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2956 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002957
kwiberg55b97fe2016-01-28 05:22:45 -08002958 if (_audioFrame.samples_per_channel_ == 0) {
2959 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2960 "Channel::PrepareEncodeAndSend() invalid audio frame");
2961 return 0xFFFFFFFF;
2962 }
2963
2964 if (channel_state_.Get().input_file_playing) {
2965 MixOrReplaceAudioWithFile(mixingFrequency);
2966 }
2967
solenberg1c2af8e2016-03-24 10:36:00 -07002968 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2969 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002970
2971 if (channel_state_.Get().input_external_media) {
2972 rtc::CritScope cs(&_callbackCritSect);
2973 const bool isStereo = (_audioFrame.num_channels_ == 2);
2974 if (_inputExternalMediaCallbackPtr) {
2975 _inputExternalMediaCallbackPtr->Process(
2976 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2977 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2978 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002979 }
kwiberg55b97fe2016-01-28 05:22:45 -08002980 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002981
kwiberg55b97fe2016-01-28 05:22:45 -08002982 if (_includeAudioLevelIndication) {
2983 size_t length =
2984 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
solenberg1c2af8e2016-03-24 10:36:00 -07002985 if (is_muted && previous_frame_muted_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002986 rms_level_.ProcessMuted(length);
2987 } else {
2988 rms_level_.Process(_audioFrame.data_, length);
niklase@google.com470e71d2011-07-07 08:21:25 +00002989 }
kwiberg55b97fe2016-01-28 05:22:45 -08002990 }
solenberg1c2af8e2016-03-24 10:36:00 -07002991 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002992
kwiberg55b97fe2016-01-28 05:22:45 -08002993 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002994}
2995
kwiberg55b97fe2016-01-28 05:22:45 -08002996uint32_t Channel::EncodeAndSend() {
2997 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2998 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002999
kwiberg55b97fe2016-01-28 05:22:45 -08003000 assert(_audioFrame.num_channels_ <= 2);
3001 if (_audioFrame.samples_per_channel_ == 0) {
3002 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3003 "Channel::EncodeAndSend() invalid audio frame");
3004 return 0xFFFFFFFF;
3005 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003006
kwiberg55b97fe2016-01-28 05:22:45 -08003007 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00003008
kwiberg55b97fe2016-01-28 05:22:45 -08003009 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00003010
kwiberg55b97fe2016-01-28 05:22:45 -08003011 // The ACM resamples internally.
3012 _audioFrame.timestamp_ = _timeStamp;
3013 // This call will trigger AudioPacketizationCallback::SendData if encoding
3014 // is done and payload is ready for packetization and transmission.
3015 // Otherwise, it will return without invoking the callback.
3016 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
3017 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
3018 "Channel::EncodeAndSend() ACM encoding failed");
3019 return 0xFFFFFFFF;
3020 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003021
kwiberg55b97fe2016-01-28 05:22:45 -08003022 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
3023 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003024}
3025
Minyue2013aec2015-05-13 14:14:42 +02003026void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08003027 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003028 Channel* channel = associate_send_channel_.channel();
3029 if (channel && channel->ChannelId() == channel_id) {
3030 // If this channel is associated with a send channel of the specified
3031 // Channel ID, disassociate with it.
3032 ChannelOwner ref(NULL);
3033 associate_send_channel_ = ref;
3034 }
3035}
3036
kwiberg55b97fe2016-01-28 05:22:45 -08003037int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
3038 VoEMediaProcess& processObject) {
3039 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3040 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003041
kwiberg55b97fe2016-01-28 05:22:45 -08003042 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003043
kwiberg55b97fe2016-01-28 05:22:45 -08003044 if (kPlaybackPerChannel == type) {
3045 if (_outputExternalMediaCallbackPtr) {
3046 _engineStatisticsPtr->SetLastError(
3047 VE_INVALID_OPERATION, kTraceError,
3048 "Channel::RegisterExternalMediaProcessing() "
3049 "output external media already enabled");
3050 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003051 }
kwiberg55b97fe2016-01-28 05:22:45 -08003052 _outputExternalMediaCallbackPtr = &processObject;
3053 _outputExternalMedia = true;
3054 } else if (kRecordingPerChannel == type) {
3055 if (_inputExternalMediaCallbackPtr) {
3056 _engineStatisticsPtr->SetLastError(
3057 VE_INVALID_OPERATION, kTraceError,
3058 "Channel::RegisterExternalMediaProcessing() "
3059 "output external media already enabled");
3060 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003061 }
kwiberg55b97fe2016-01-28 05:22:45 -08003062 _inputExternalMediaCallbackPtr = &processObject;
3063 channel_state_.SetInputExternalMedia(true);
3064 }
3065 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003066}
3067
kwiberg55b97fe2016-01-28 05:22:45 -08003068int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
3069 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3070 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003071
kwiberg55b97fe2016-01-28 05:22:45 -08003072 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003073
kwiberg55b97fe2016-01-28 05:22:45 -08003074 if (kPlaybackPerChannel == type) {
3075 if (!_outputExternalMediaCallbackPtr) {
3076 _engineStatisticsPtr->SetLastError(
3077 VE_INVALID_OPERATION, kTraceWarning,
3078 "Channel::DeRegisterExternalMediaProcessing() "
3079 "output external media already disabled");
3080 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003081 }
kwiberg55b97fe2016-01-28 05:22:45 -08003082 _outputExternalMedia = false;
3083 _outputExternalMediaCallbackPtr = NULL;
3084 } else if (kRecordingPerChannel == type) {
3085 if (!_inputExternalMediaCallbackPtr) {
3086 _engineStatisticsPtr->SetLastError(
3087 VE_INVALID_OPERATION, kTraceWarning,
3088 "Channel::DeRegisterExternalMediaProcessing() "
3089 "input external media already disabled");
3090 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003091 }
kwiberg55b97fe2016-01-28 05:22:45 -08003092 channel_state_.SetInputExternalMedia(false);
3093 _inputExternalMediaCallbackPtr = NULL;
3094 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003095
kwiberg55b97fe2016-01-28 05:22:45 -08003096 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003097}
3098
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003099int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08003100 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3101 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003102
kwiberg55b97fe2016-01-28 05:22:45 -08003103 if (channel_state_.Get().playing) {
3104 _engineStatisticsPtr->SetLastError(
3105 VE_INVALID_OPERATION, kTraceError,
3106 "Channel::SetExternalMixing() "
3107 "external mixing cannot be changed while playing.");
3108 return -1;
3109 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003110
kwiberg55b97fe2016-01-28 05:22:45 -08003111 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003112
kwiberg55b97fe2016-01-28 05:22:45 -08003113 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003114}
3115
kwiberg55b97fe2016-01-28 05:22:45 -08003116int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3117 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003118}
3119
wu@webrtc.org24301a62013-12-13 19:17:43 +00003120void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3121 audio_coding_->GetDecodingCallStatistics(stats);
3122}
3123
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003124bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3125 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003126 rtc::CritScope lock(&video_sync_lock_);
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003127 if (_average_jitter_buffer_delay_us == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003128 return false;
3129 }
kwiberg55b97fe2016-01-28 05:22:45 -08003130 *jitter_buffer_delay_ms =
3131 (_average_jitter_buffer_delay_us + 500) / 1000 + _recPacketDelayMs;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003132 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003133 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003134}
3135
solenberg358057b2015-11-27 10:46:42 -08003136uint32_t Channel::GetDelayEstimate() const {
3137 int jitter_buffer_delay_ms = 0;
3138 int playout_buffer_delay_ms = 0;
3139 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3140 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3141}
3142
deadbeef74375882015-08-13 12:09:10 -07003143int Channel::LeastRequiredDelayMs() const {
3144 return audio_coding_->LeastRequiredDelayMs();
3145}
3146
kwiberg55b97fe2016-01-28 05:22:45 -08003147int Channel::SetMinimumPlayoutDelay(int delayMs) {
3148 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3149 "Channel::SetMinimumPlayoutDelay()");
3150 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3151 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3152 _engineStatisticsPtr->SetLastError(
3153 VE_INVALID_ARGUMENT, kTraceError,
3154 "SetMinimumPlayoutDelay() invalid min delay");
3155 return -1;
3156 }
3157 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3158 _engineStatisticsPtr->SetLastError(
3159 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3160 "SetMinimumPlayoutDelay() failed to set min playout delay");
3161 return -1;
3162 }
3163 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003164}
3165
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003166int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003167 uint32_t playout_timestamp_rtp = 0;
3168 {
tommi31fc21f2016-01-21 10:37:37 -08003169 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003170 playout_timestamp_rtp = playout_timestamp_rtp_;
3171 }
kwiberg55b97fe2016-01-28 05:22:45 -08003172 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003173 _engineStatisticsPtr->SetLastError(
3174 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3175 "GetPlayoutTimestamp() failed to retrieve timestamp");
3176 return -1;
3177 }
deadbeef74375882015-08-13 12:09:10 -07003178 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003179 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003180}
3181
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003182int Channel::SetInitTimestamp(unsigned int timestamp) {
3183 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003184 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003185 if (channel_state_.Get().sending) {
3186 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3187 "SetInitTimestamp() already sending");
3188 return -1;
3189 }
3190 _rtpRtcpModule->SetStartTimestamp(timestamp);
3191 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003192}
3193
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003194int Channel::SetInitSequenceNumber(short sequenceNumber) {
3195 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3196 "Channel::SetInitSequenceNumber()");
3197 if (channel_state_.Get().sending) {
3198 _engineStatisticsPtr->SetLastError(
3199 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3200 return -1;
3201 }
3202 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3203 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003204}
3205
kwiberg55b97fe2016-01-28 05:22:45 -08003206int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3207 RtpReceiver** rtp_receiver) const {
3208 *rtpRtcpModule = _rtpRtcpModule.get();
3209 *rtp_receiver = rtp_receiver_.get();
3210 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003211}
3212
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003213// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3214// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003215int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003216 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003217 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003218
kwiberg55b97fe2016-01-28 05:22:45 -08003219 {
3220 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003221
kwiberg55b97fe2016-01-28 05:22:45 -08003222 if (_inputFilePlayerPtr == NULL) {
3223 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3224 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3225 " doesnt exist");
3226 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003227 }
3228
kwiberg55b97fe2016-01-28 05:22:45 -08003229 if (_inputFilePlayerPtr->Get10msAudioFromFile(fileBuffer.get(), fileSamples,
3230 mixingFrequency) == -1) {
3231 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3232 "Channel::MixOrReplaceAudioWithFile() file mixing "
3233 "failed");
3234 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003235 }
kwiberg55b97fe2016-01-28 05:22:45 -08003236 if (fileSamples == 0) {
3237 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3238 "Channel::MixOrReplaceAudioWithFile() file is ended");
3239 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003240 }
kwiberg55b97fe2016-01-28 05:22:45 -08003241 }
3242
3243 assert(_audioFrame.samples_per_channel_ == fileSamples);
3244
3245 if (_mixFileWithMicrophone) {
3246 // Currently file stream is always mono.
3247 // TODO(xians): Change the code when FilePlayer supports real stereo.
3248 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3249 1, fileSamples);
3250 } else {
3251 // Replace ACM audio with file.
3252 // Currently file stream is always mono.
3253 // TODO(xians): Change the code when FilePlayer supports real stereo.
3254 _audioFrame.UpdateFrame(
3255 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3256 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3257 }
3258 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003259}
3260
kwiberg55b97fe2016-01-28 05:22:45 -08003261int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3262 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003263
kwibergb7f89d62016-02-17 10:04:18 -08003264 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003265 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003266
kwiberg55b97fe2016-01-28 05:22:45 -08003267 {
3268 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003269
kwiberg55b97fe2016-01-28 05:22:45 -08003270 if (_outputFilePlayerPtr == NULL) {
3271 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3272 "Channel::MixAudioWithFile() file mixing failed");
3273 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003274 }
3275
kwiberg55b97fe2016-01-28 05:22:45 -08003276 // We should get the frequency we ask for.
3277 if (_outputFilePlayerPtr->Get10msAudioFromFile(
3278 fileBuffer.get(), fileSamples, mixingFrequency) == -1) {
3279 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3280 "Channel::MixAudioWithFile() file mixing failed");
3281 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003282 }
kwiberg55b97fe2016-01-28 05:22:45 -08003283 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003284
kwiberg55b97fe2016-01-28 05:22:45 -08003285 if (audioFrame.samples_per_channel_ == fileSamples) {
3286 // Currently file stream is always mono.
3287 // TODO(xians): Change the code when FilePlayer supports real stereo.
3288 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3289 fileSamples);
3290 } else {
3291 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3292 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3293 ") != "
3294 "fileSamples(%" PRIuS ")",
3295 audioFrame.samples_per_channel_, fileSamples);
3296 return -1;
3297 }
3298
3299 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003300}
3301
deadbeef74375882015-08-13 12:09:10 -07003302void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003303 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003304
henrik.lundin96bd5022016-04-06 04:13:56 -07003305 if (!jitter_buffer_playout_timestamp_) {
3306 // This can happen if this channel has not received any RTP packets. In
3307 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003308 return;
3309 }
3310
3311 uint16_t delay_ms = 0;
3312 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003313 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003314 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3315 " delay from the ADM");
3316 _engineStatisticsPtr->SetLastError(
3317 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3318 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3319 return;
3320 }
3321
henrik.lundin96bd5022016-04-06 04:13:56 -07003322 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3323 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003324
3325 // Remove the playout delay.
henrik.lundin96bd5022016-04-06 04:13:56 -07003326 playout_timestamp -= (delay_ms * (GetPlayoutFrequency() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003327
kwiberg55b97fe2016-01-28 05:22:45 -08003328 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003329 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003330 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003331
3332 {
tommi31fc21f2016-01-21 10:37:37 -08003333 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003334 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003335 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003336 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003337 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003338 }
3339 playout_delay_ms_ = delay_ms;
3340 }
3341}
3342
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003343// Called for incoming RTP packets after successful RTP header parsing.
3344void Channel::UpdatePacketDelay(uint32_t rtp_timestamp,
3345 uint16_t sequence_number) {
kwiberg55b97fe2016-01-28 05:22:45 -08003346 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003347 "Channel::UpdatePacketDelay(timestamp=%lu, sequenceNumber=%u)",
3348 rtp_timestamp, sequence_number);
niklase@google.com470e71d2011-07-07 08:21:25 +00003349
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003350 // Get frequency of last received payload
wu@webrtc.org94454b72014-06-05 20:34:08 +00003351 int rtp_receive_frequency = GetPlayoutFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +00003352
turaj@webrtc.org167b6df2013-12-13 21:05:07 +00003353 // |jitter_buffer_playout_timestamp_| updated in UpdatePlayoutTimestamp for
henrik.lundin96bd5022016-04-06 04:13:56 -07003354 // every incoming packet. May be empty if no valid playout timestamp is
3355 // available.
3356 // If |rtp_timestamp| is newer than |jitter_buffer_playout_timestamp_|, the
3357 // resulting difference is positive and will be used. When the inverse is
3358 // true (can happen when a network glitch causes a packet to arrive late,
3359 // and during long comfort noise periods with clock drift), or when
3360 // |jitter_buffer_playout_timestamp_| has no value, the difference is not
3361 // changed from the initial 0.
3362 uint32_t timestamp_diff_ms = 0;
3363 if (jitter_buffer_playout_timestamp_ &&
3364 IsNewerTimestamp(rtp_timestamp, *jitter_buffer_playout_timestamp_)) {
3365 timestamp_diff_ms = (rtp_timestamp - *jitter_buffer_playout_timestamp_) /
3366 (rtp_receive_frequency / 1000);
3367 if (timestamp_diff_ms > (2 * kVoiceEngineMaxMinPlayoutDelayMs)) {
3368 // Diff is too large; set it to zero instead.
3369 timestamp_diff_ms = 0;
3370 }
henrik.lundin@webrtc.orgd6692992014-03-20 12:04:09 +00003371 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003372
kwiberg55b97fe2016-01-28 05:22:45 -08003373 uint16_t packet_delay_ms =
3374 (rtp_timestamp - _previousTimestamp) / (rtp_receive_frequency / 1000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003375
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003376 _previousTimestamp = rtp_timestamp;
niklase@google.com470e71d2011-07-07 08:21:25 +00003377
kwiberg55b97fe2016-01-28 05:22:45 -08003378 if (timestamp_diff_ms == 0)
3379 return;
niklase@google.com470e71d2011-07-07 08:21:25 +00003380
deadbeef74375882015-08-13 12:09:10 -07003381 {
tommi31fc21f2016-01-21 10:37:37 -08003382 rtc::CritScope lock(&video_sync_lock_);
niklase@google.com470e71d2011-07-07 08:21:25 +00003383
deadbeef74375882015-08-13 12:09:10 -07003384 if (packet_delay_ms >= 10 && packet_delay_ms <= 60) {
3385 _recPacketDelayMs = packet_delay_ms;
3386 }
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003387
deadbeef74375882015-08-13 12:09:10 -07003388 if (_average_jitter_buffer_delay_us == 0) {
3389 _average_jitter_buffer_delay_us = timestamp_diff_ms * 1000;
3390 return;
3391 }
3392
3393 // Filter average delay value using exponential filter (alpha is
3394 // 7/8). We derive 1000 *_average_jitter_buffer_delay_us here (reduces
3395 // risk of rounding error) and compensate for it in GetDelayEstimate()
3396 // later.
kwiberg55b97fe2016-01-28 05:22:45 -08003397 _average_jitter_buffer_delay_us =
3398 (_average_jitter_buffer_delay_us * 7 + 1000 * timestamp_diff_ms + 500) /
3399 8;
deadbeef74375882015-08-13 12:09:10 -07003400 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003401}
3402
kwiberg55b97fe2016-01-28 05:22:45 -08003403void Channel::RegisterReceiveCodecsToRTPModule() {
3404 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3405 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003406
kwiberg55b97fe2016-01-28 05:22:45 -08003407 CodecInst codec;
3408 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003409
kwiberg55b97fe2016-01-28 05:22:45 -08003410 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3411 // Open up the RTP/RTCP receiver for all supported codecs
3412 if ((audio_coding_->Codec(idx, &codec) == -1) ||
3413 (rtp_receiver_->RegisterReceivePayload(
3414 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3415 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
3416 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3417 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3418 " to register %s (%d/%d/%" PRIuS
3419 "/%d) to RTP/RTCP "
3420 "receiver",
3421 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3422 codec.rate);
3423 } else {
3424 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3425 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3426 "(%d/%d/%" PRIuS
3427 "/%d) has been added to the RTP/RTCP "
3428 "receiver",
3429 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3430 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003431 }
kwiberg55b97fe2016-01-28 05:22:45 -08003432 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003433}
3434
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00003435// Assuming this method is called with valid payload type.
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003436int Channel::SetRedPayloadType(int red_payload_type) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003437 CodecInst codec;
3438 bool found_red = false;
3439
3440 // Get default RED settings from the ACM database
3441 const int num_codecs = AudioCodingModule::NumberOfCodecs();
3442 for (int idx = 0; idx < num_codecs; idx++) {
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00003443 audio_coding_->Codec(idx, &codec);
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003444 if (!STR_CASE_CMP(codec.plname, "RED")) {
3445 found_red = true;
3446 break;
3447 }
3448 }
3449
3450 if (!found_red) {
3451 _engineStatisticsPtr->SetLastError(
3452 VE_CODEC_ERROR, kTraceError,
3453 "SetRedPayloadType() RED is not supported");
3454 return -1;
3455 }
3456
turaj@webrtc.org9d532fd2013-01-31 18:34:19 +00003457 codec.pltype = red_payload_type;
kwibergc8d071e2016-04-06 12:22:38 -07003458 if (!codec_manager_.RegisterEncoder(codec) ||
3459 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003460 _engineStatisticsPtr->SetLastError(
3461 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3462 "SetRedPayloadType() RED registration in ACM module failed");
3463 return -1;
3464 }
3465
3466 if (_rtpRtcpModule->SetSendREDPayloadType(red_payload_type) != 0) {
3467 _engineStatisticsPtr->SetLastError(
3468 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
3469 "SetRedPayloadType() RED registration in RTP/RTCP module failed");
3470 return -1;
3471 }
3472 return 0;
3473}
3474
kwiberg55b97fe2016-01-28 05:22:45 -08003475int Channel::SetSendRtpHeaderExtension(bool enable,
3476 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003477 unsigned char id) {
3478 int error = 0;
3479 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3480 if (enable) {
3481 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3482 }
3483 return error;
3484}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003485
wu@webrtc.org94454b72014-06-05 20:34:08 +00003486int32_t Channel::GetPlayoutFrequency() {
3487 int32_t playout_frequency = audio_coding_->PlayoutFrequency();
3488 CodecInst current_recive_codec;
3489 if (audio_coding_->ReceiveCodec(&current_recive_codec) == 0) {
3490 if (STR_CASE_CMP("G722", current_recive_codec.plname) == 0) {
3491 // Even though the actual sampling rate for G.722 audio is
3492 // 16,000 Hz, the RTP clock rate for the G722 payload format is
3493 // 8,000 Hz because that value was erroneously assigned in
3494 // RFC 1890 and must remain unchanged for backward compatibility.
3495 playout_frequency = 8000;
3496 } else if (STR_CASE_CMP("opus", current_recive_codec.plname) == 0) {
3497 // We are resampling Opus internally to 32,000 Hz until all our
3498 // DSP routines can operate at 48,000 Hz, but the RTP clock
3499 // rate for the Opus payload format is standardized to 48,000 Hz,
3500 // because that is the maximum supported decoding sampling rate.
3501 playout_frequency = 48000;
3502 }
3503 }
3504 return playout_frequency;
3505}
3506
Minyue2013aec2015-05-13 14:14:42 +02003507int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003508 RtcpMode method = _rtpRtcpModule->RTCP();
3509 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003510 return 0;
3511 }
3512 std::vector<RTCPReportBlock> report_blocks;
3513 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003514
3515 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003516 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003517 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003518 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003519 Channel* channel = associate_send_channel_.channel();
3520 // Tries to get RTT from an associated channel. This is important for
3521 // receive-only channels.
3522 if (channel) {
3523 // To prevent infinite recursion and deadlock, calling GetRTT of
3524 // associate channel should always use "false" for argument:
3525 // |allow_associate_channel|.
3526 rtt = channel->GetRTT(false);
3527 }
3528 }
3529 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003530 }
3531
3532 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3533 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3534 for (; it != report_blocks.end(); ++it) {
3535 if (it->remoteSSRC == remoteSSRC)
3536 break;
3537 }
3538 if (it == report_blocks.end()) {
3539 // We have not received packets with SSRC matching the report blocks.
3540 // To calculate RTT we try with the SSRC of the first report block.
3541 // This is very important for send-only channels where we don't know
3542 // the SSRC of the other end.
3543 remoteSSRC = report_blocks[0].remoteSSRC;
3544 }
Minyue2013aec2015-05-13 14:14:42 +02003545
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003546 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003547 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003548 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003549 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3550 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003551 return 0;
3552 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003553 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003554}
3555
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003556} // namespace voe
3557} // namespace webrtc