blob: a6c0c8d050538c45774ddee0883e6dad4a72450e [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)
486 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame) ==
487 -1) {
488 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
489 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
490 // In all likelihood, the audio in this frame is garbage. We return an
491 // error so that the audio mixer module doesn't add it to the mix. As
492 // a result, it won't be played out and the actions skipped here are
493 // irrelevant.
494 return -1;
495 }
496
497 if (_RxVadDetection) {
498 UpdateRxVadDetection(*audioFrame);
499 }
500
501 // Convert module ID to internal VoE channel ID
502 audioFrame->id_ = VoEChannelId(audioFrame->id_);
503 // Store speech type for dead-or-alive detection
504 _outputSpeechType = audioFrame->speech_type_;
505
506 ChannelState::State state = channel_state_.Get();
507
508 if (state.rx_apm_is_enabled) {
509 int err = rx_audioproc_->ProcessStream(audioFrame);
510 if (err) {
511 LOG(LS_ERROR) << "ProcessStream() error: " << err;
512 assert(false);
Ivo Creusenae856f22015-09-17 16:30:16 +0200513 }
kwiberg55b97fe2016-01-28 05:22:45 -0800514 }
515
516 {
517 // Pass the audio buffers to an optional sink callback, before applying
518 // scaling/panning, as that applies to the mix operation.
519 // External recipients of the audio (e.g. via AudioTrack), will do their
520 // own mixing/dynamic processing.
521 rtc::CritScope cs(&_callbackCritSect);
522 if (audio_sink_) {
523 AudioSinkInterface::Data data(
524 &audioFrame->data_[0], audioFrame->samples_per_channel_,
525 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
526 audioFrame->timestamp_);
527 audio_sink_->OnData(data);
528 }
529 }
530
531 float output_gain = 1.0f;
532 float left_pan = 1.0f;
533 float right_pan = 1.0f;
534 {
535 rtc::CritScope cs(&volume_settings_critsect_);
536 output_gain = _outputGain;
537 left_pan = _panLeft;
538 right_pan = _panRight;
539 }
540
541 // Output volume scaling
542 if (output_gain < 0.99f || output_gain > 1.01f) {
543 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
544 }
545
546 // Scale left and/or right channel(s) if stereo and master balance is
547 // active
548
549 if (left_pan != 1.0f || right_pan != 1.0f) {
550 if (audioFrame->num_channels_ == 1) {
551 // Emulate stereo mode since panning is active.
552 // The mono signal is copied to both left and right channels here.
553 AudioFrameOperations::MonoToStereo(audioFrame);
554 }
555 // For true stereo mode (when we are receiving a stereo signal), no
556 // action is needed.
557
558 // Do the panning operation (the audio frame contains stereo at this
559 // stage)
560 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
561 }
562
563 // Mix decoded PCM output with file if file mixing is enabled
564 if (state.output_file_playing) {
565 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
566 }
567
568 // External media
569 if (_outputExternalMedia) {
570 rtc::CritScope cs(&_callbackCritSect);
571 const bool isStereo = (audioFrame->num_channels_ == 2);
572 if (_outputExternalMediaCallbackPtr) {
573 _outputExternalMediaCallbackPtr->Process(
574 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
575 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
576 isStereo);
577 }
578 }
579
580 // Record playout if enabled
581 {
582 rtc::CritScope cs(&_fileCritSect);
583
584 if (_outputFileRecording && _outputFileRecorderPtr) {
585 _outputFileRecorderPtr->RecordAudioToFile(*audioFrame);
586 }
587 }
588
589 // Measure audio level (0-9)
590 _outputAudioLevel.ComputeLevel(*audioFrame);
591
592 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
593 // The first frame with a valid rtp timestamp.
594 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
595 }
596
597 if (capture_start_rtp_time_stamp_ >= 0) {
598 // audioFrame.timestamp_ should be valid from now on.
599
600 // Compute elapsed time.
601 int64_t unwrap_timestamp =
602 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
603 audioFrame->elapsed_time_ms_ =
604 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
605 (GetPlayoutFrequency() / 1000);
606
niklase@google.com470e71d2011-07-07 08:21:25 +0000607 {
kwiberg55b97fe2016-01-28 05:22:45 -0800608 rtc::CritScope lock(&ts_stats_lock_);
609 // Compute ntp time.
610 audioFrame->ntp_time_ms_ =
611 ntp_estimator_.Estimate(audioFrame->timestamp_);
612 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
613 if (audioFrame->ntp_time_ms_ > 0) {
614 // Compute |capture_start_ntp_time_ms_| so that
615 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
616 capture_start_ntp_time_ms_ =
617 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000618 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000619 }
kwiberg55b97fe2016-01-28 05:22:45 -0800620 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000621
kwiberg55b97fe2016-01-28 05:22:45 -0800622 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000623}
624
kwiberg55b97fe2016-01-28 05:22:45 -0800625int32_t Channel::NeededFrequency(int32_t id) const {
626 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
627 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000628
kwiberg55b97fe2016-01-28 05:22:45 -0800629 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000630
kwiberg55b97fe2016-01-28 05:22:45 -0800631 // Determine highest needed receive frequency
632 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000633
kwiberg55b97fe2016-01-28 05:22:45 -0800634 // Return the bigger of playout and receive frequency in the ACM.
635 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
636 highestNeeded = audio_coding_->PlayoutFrequency();
637 } else {
638 highestNeeded = receiveFrequency;
639 }
640
641 // Special case, if we're playing a file on the playout side
642 // we take that frequency into consideration as well
643 // This is not needed on sending side, since the codec will
644 // limit the spectrum anyway.
645 if (channel_state_.Get().output_file_playing) {
646 rtc::CritScope cs(&_fileCritSect);
647 if (_outputFilePlayerPtr) {
648 if (_outputFilePlayerPtr->Frequency() > highestNeeded) {
649 highestNeeded = _outputFilePlayerPtr->Frequency();
650 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000651 }
kwiberg55b97fe2016-01-28 05:22:45 -0800652 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000653
kwiberg55b97fe2016-01-28 05:22:45 -0800654 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000655}
656
ivocb04965c2015-09-09 00:09:43 -0700657int32_t Channel::CreateChannel(Channel*& channel,
658 int32_t channelId,
659 uint32_t instanceId,
660 RtcEventLog* const event_log,
661 const Config& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800662 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
663 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
664 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000665
kwiberg55b97fe2016-01-28 05:22:45 -0800666 channel = new Channel(channelId, instanceId, event_log, config);
667 if (channel == NULL) {
668 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
669 "Channel::CreateChannel() unable to allocate memory for"
670 " channel");
671 return -1;
672 }
673 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000674}
675
kwiberg55b97fe2016-01-28 05:22:45 -0800676void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
677 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
678 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
679 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000680
kwiberg55b97fe2016-01-28 05:22:45 -0800681 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000682}
683
kwiberg55b97fe2016-01-28 05:22:45 -0800684void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
685 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
686 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
687 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000688
kwiberg55b97fe2016-01-28 05:22:45 -0800689 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000690}
691
kwiberg55b97fe2016-01-28 05:22:45 -0800692void Channel::PlayFileEnded(int32_t id) {
693 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
694 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000695
kwiberg55b97fe2016-01-28 05:22:45 -0800696 if (id == _inputFilePlayerId) {
697 channel_state_.SetInputFilePlaying(false);
698 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
699 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000700 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800701 } else if (id == _outputFilePlayerId) {
702 channel_state_.SetOutputFilePlaying(false);
703 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
704 "Channel::PlayFileEnded() => output file player module is"
705 " shutdown");
706 }
707}
708
709void Channel::RecordFileEnded(int32_t id) {
710 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
711 "Channel::RecordFileEnded(id=%d)", id);
712
713 assert(id == _outputFileRecorderId);
714
715 rtc::CritScope cs(&_fileCritSect);
716
717 _outputFileRecording = false;
718 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
719 "Channel::RecordFileEnded() => output file recorder module is"
720 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000721}
722
pbos@webrtc.org92135212013-05-14 08:31:39 +0000723Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000724 uint32_t instanceId,
ivocb04965c2015-09-09 00:09:43 -0700725 RtcEventLog* const event_log,
726 const Config& config)
tommi31fc21f2016-01-21 10:37:37 -0800727 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100728 _channelId(channelId),
729 event_log_(event_log),
730 rtp_header_parser_(RtpHeaderParser::Create()),
731 rtp_payload_registry_(
732 new RTPPayloadRegistry(RTPPayloadStrategy::CreateStrategy(true))),
733 rtp_receive_statistics_(
734 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
735 rtp_receiver_(
736 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100737 this,
738 this,
739 rtp_payload_registry_.get())),
740 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
741 _outputAudioLevel(),
742 _externalTransport(false),
743 _inputFilePlayerPtr(NULL),
744 _outputFilePlayerPtr(NULL),
745 _outputFileRecorderPtr(NULL),
746 // Avoid conflict with other channels by adding 1024 - 1026,
747 // won't use as much as 1024 channels.
748 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
749 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
750 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
751 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100752 _outputExternalMedia(false),
753 _inputExternalMediaCallbackPtr(NULL),
754 _outputExternalMediaCallbackPtr(NULL),
755 _timeStamp(0), // This is just an offset, RTP module will add it's own
756 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100757 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100758 playout_timestamp_rtp_(0),
759 playout_timestamp_rtcp_(0),
760 playout_delay_ms_(0),
761 _numberOfDiscardedPackets(0),
762 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100763 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
764 capture_start_rtp_time_stamp_(-1),
765 capture_start_ntp_time_ms_(-1),
766 _engineStatisticsPtr(NULL),
767 _outputMixerPtr(NULL),
768 _transmitMixerPtr(NULL),
769 _moduleProcessThreadPtr(NULL),
770 _audioDeviceModulePtr(NULL),
771 _voiceEngineObserverPtr(NULL),
772 _callbackCritSectPtr(NULL),
773 _transportPtr(NULL),
774 _rxVadObserverPtr(NULL),
775 _oldVadDecision(-1),
776 _sendFrameType(0),
777 _externalMixing(false),
778 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700779 input_mute_(false),
780 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100781 _panLeft(1.0f),
782 _panRight(1.0f),
783 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100784 _lastLocalTimeStamp(0),
785 _lastPayloadType(0),
786 _includeAudioLevelIndication(false),
787 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100788 _average_jitter_buffer_delay_us(0),
789 _previousTimestamp(0),
790 _recPacketDelayMs(20),
791 _RxVadDetection(false),
792 _rxAgcIsEnabled(false),
793 _rxNsIsEnabled(false),
794 restored_packet_in_use_(false),
795 rtcp_observer_(new VoERtcpObserver(this)),
796 network_predictor_(new NetworkPredictor(Clock::GetRealTimeClock())),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100797 associate_send_channel_(ChannelOwner(nullptr)),
798 pacing_enabled_(config.Get<VoicePacing>().enabled),
stefanbba9dec2016-02-01 04:39:55 -0800799 feedback_observer_proxy_(new TransportFeedbackProxy()),
800 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
801 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()) {
kwiberg55b97fe2016-01-28 05:22:45 -0800802 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
803 "Channel::Channel() - ctor");
804 AudioCodingModule::Config acm_config;
805 acm_config.id = VoEModuleId(instanceId, channelId);
806 if (config.Get<NetEqCapacityConfig>().enabled) {
807 // Clamping the buffer capacity at 20 packets. While going lower will
808 // probably work, it makes little sense.
809 acm_config.neteq_config.max_packets_in_buffer =
810 std::max(20, config.Get<NetEqCapacityConfig>().capacity);
811 }
812 acm_config.neteq_config.enable_fast_accelerate =
813 config.Get<NetEqFastAccelerate>().enabled;
814 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200815
kwiberg55b97fe2016-01-28 05:22:45 -0800816 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000817
kwiberg55b97fe2016-01-28 05:22:45 -0800818 RtpRtcp::Configuration configuration;
819 configuration.audio = true;
820 configuration.outgoing_transport = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800821 configuration.receive_statistics = rtp_receive_statistics_.get();
822 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800823 if (pacing_enabled_) {
824 configuration.paced_sender = rtp_packet_sender_proxy_.get();
825 configuration.transport_sequence_number_allocator =
826 seq_num_allocator_proxy_.get();
827 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
828 }
kwiberg55b97fe2016-01-28 05:22:45 -0800829 configuration.event_log = event_log;
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000830
kwiberg55b97fe2016-01-28 05:22:45 -0800831 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100832 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000833
kwiberg55b97fe2016-01-28 05:22:45 -0800834 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
835 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
836 statistics_proxy_.get());
aluebs@webrtc.orgf927fd62014-04-16 11:58:18 +0000837
kwiberg55b97fe2016-01-28 05:22:45 -0800838 Config audioproc_config;
839 audioproc_config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
840 rx_audioproc_.reset(AudioProcessing::Create(audioproc_config));
niklase@google.com470e71d2011-07-07 08:21:25 +0000841}
842
kwiberg55b97fe2016-01-28 05:22:45 -0800843Channel::~Channel() {
844 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
845 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
846 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000847
kwiberg55b97fe2016-01-28 05:22:45 -0800848 if (_outputExternalMedia) {
849 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
850 }
851 if (channel_state_.Get().input_external_media) {
852 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
853 }
854 StopSend();
855 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000856
kwiberg55b97fe2016-01-28 05:22:45 -0800857 {
858 rtc::CritScope cs(&_fileCritSect);
859 if (_inputFilePlayerPtr) {
860 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
861 _inputFilePlayerPtr->StopPlayingFile();
862 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
863 _inputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000864 }
kwiberg55b97fe2016-01-28 05:22:45 -0800865 if (_outputFilePlayerPtr) {
866 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
867 _outputFilePlayerPtr->StopPlayingFile();
868 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
869 _outputFilePlayerPtr = NULL;
870 }
871 if (_outputFileRecorderPtr) {
872 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
873 _outputFileRecorderPtr->StopRecording();
874 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
875 _outputFileRecorderPtr = NULL;
876 }
877 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000878
kwiberg55b97fe2016-01-28 05:22:45 -0800879 // The order to safely shutdown modules in a channel is:
880 // 1. De-register callbacks in modules
881 // 2. De-register modules in process thread
882 // 3. Destroy modules
883 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
884 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
885 "~Channel() failed to de-register transport callback"
886 " (Audio coding module)");
887 }
888 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
889 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
890 "~Channel() failed to de-register VAD callback"
891 " (Audio coding module)");
892 }
893 // De-register modules in process thread
894 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +0000895
kwiberg55b97fe2016-01-28 05:22:45 -0800896 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +0000897}
898
kwiberg55b97fe2016-01-28 05:22:45 -0800899int32_t Channel::Init() {
900 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
901 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000902
kwiberg55b97fe2016-01-28 05:22:45 -0800903 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000904
kwiberg55b97fe2016-01-28 05:22:45 -0800905 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000906
kwiberg55b97fe2016-01-28 05:22:45 -0800907 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
908 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
909 "Channel::Init() must call SetEngineInformation() first");
910 return -1;
911 }
912
913 // --- Add modules to process thread (for periodic schedulation)
914
915 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
916
917 // --- ACM initialization
918
919 if (audio_coding_->InitializeReceiver() == -1) {
920 _engineStatisticsPtr->SetLastError(
921 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
922 "Channel::Init() unable to initialize the ACM - 1");
923 return -1;
924 }
925
926 // --- RTP/RTCP module initialization
927
928 // Ensure that RTCP is enabled by default for the created channel.
929 // Note that, the module will keep generating RTCP until it is explicitly
930 // disabled by the user.
931 // After StopListen (when no sockets exists), RTCP packets will no longer
932 // be transmitted since the Transport object will then be invalid.
933 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
934 // RTCP is enabled by default.
935 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
936 // --- Register all permanent callbacks
937 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
938 (audio_coding_->RegisterVADCallback(this) == -1);
939
940 if (fail) {
941 _engineStatisticsPtr->SetLastError(
942 VE_CANNOT_INIT_CHANNEL, kTraceError,
943 "Channel::Init() callbacks not registered");
944 return -1;
945 }
946
947 // --- Register all supported codecs to the receiving side of the
948 // RTP/RTCP module
949
950 CodecInst codec;
951 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
952
953 for (int idx = 0; idx < nSupportedCodecs; idx++) {
954 // Open up the RTP/RTCP receiver for all supported codecs
955 if ((audio_coding_->Codec(idx, &codec) == -1) ||
956 (rtp_receiver_->RegisterReceivePayload(
957 codec.plname, codec.pltype, codec.plfreq, codec.channels,
958 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
959 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
960 "Channel::Init() unable to register %s "
961 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
962 codec.plname, codec.pltype, codec.plfreq, codec.channels,
963 codec.rate);
964 } else {
965 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
966 "Channel::Init() %s (%d/%d/%" PRIuS
967 "/%d) has been "
968 "added to the RTP/RTCP receiver",
969 codec.plname, codec.pltype, codec.plfreq, codec.channels,
970 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000971 }
972
kwiberg55b97fe2016-01-28 05:22:45 -0800973 // Ensure that PCMU is used as default codec on the sending side
974 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
975 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +0000976 }
977
kwiberg55b97fe2016-01-28 05:22:45 -0800978 // Register default PT for outband 'telephone-event'
979 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -0700980 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
981 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800982 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
983 "Channel::Init() failed to register outband "
984 "'telephone-event' (%d/%d) correctly",
985 codec.pltype, codec.plfreq);
986 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000987 }
988
kwiberg55b97fe2016-01-28 05:22:45 -0800989 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -0700990 if (!codec_manager_.RegisterEncoder(codec) ||
991 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
992 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec) ||
993 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800994 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
995 "Channel::Init() failed to register CN (%d/%d) "
996 "correctly - 1",
997 codec.pltype, codec.plfreq);
998 }
999 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001000#ifdef WEBRTC_CODEC_RED
kwiberg55b97fe2016-01-28 05:22:45 -08001001 // Register RED to the receiving side of the ACM.
1002 // We will not receive an OnInitializeDecoder() callback for RED.
1003 if (!STR_CASE_CMP(codec.plname, "RED")) {
kwibergc8d071e2016-04-06 12:22:38 -07001004 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001005 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1006 "Channel::Init() failed to register RED (%d/%d) "
1007 "correctly",
1008 codec.pltype, codec.plfreq);
1009 }
1010 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001011#endif
kwiberg55b97fe2016-01-28 05:22:45 -08001012 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001013
kwiberg55b97fe2016-01-28 05:22:45 -08001014 if (rx_audioproc_->noise_suppression()->set_level(kDefaultNsMode) != 0) {
1015 LOG(LS_ERROR) << "noise_suppression()->set_level(kDefaultNsMode) failed.";
1016 return -1;
1017 }
1018 if (rx_audioproc_->gain_control()->set_mode(kDefaultRxAgcMode) != 0) {
1019 LOG(LS_ERROR) << "gain_control()->set_mode(kDefaultRxAgcMode) failed.";
1020 return -1;
1021 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001022
kwiberg55b97fe2016-01-28 05:22:45 -08001023 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001024}
1025
kwiberg55b97fe2016-01-28 05:22:45 -08001026int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1027 OutputMixer& outputMixer,
1028 voe::TransmitMixer& transmitMixer,
1029 ProcessThread& moduleProcessThread,
1030 AudioDeviceModule& audioDeviceModule,
1031 VoiceEngineObserver* voiceEngineObserver,
1032 rtc::CriticalSection* callbackCritSect) {
1033 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1034 "Channel::SetEngineInformation()");
1035 _engineStatisticsPtr = &engineStatistics;
1036 _outputMixerPtr = &outputMixer;
1037 _transmitMixerPtr = &transmitMixer,
1038 _moduleProcessThreadPtr = &moduleProcessThread;
1039 _audioDeviceModulePtr = &audioDeviceModule;
1040 _voiceEngineObserverPtr = voiceEngineObserver;
1041 _callbackCritSectPtr = callbackCritSect;
1042 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001043}
1044
kwiberg55b97fe2016-01-28 05:22:45 -08001045int32_t Channel::UpdateLocalTimeStamp() {
1046 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1047 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001048}
1049
kwibergb7f89d62016-02-17 10:04:18 -08001050void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001051 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001052 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001053}
1054
kwiberg55b97fe2016-01-28 05:22:45 -08001055int32_t Channel::StartPlayout() {
1056 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1057 "Channel::StartPlayout()");
1058 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001059 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001060 }
1061
1062 if (!_externalMixing) {
1063 // Add participant as candidates for mixing.
1064 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1065 _engineStatisticsPtr->SetLastError(
1066 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1067 "StartPlayout() failed to add participant to mixer");
1068 return -1;
1069 }
1070 }
1071
1072 channel_state_.SetPlaying(true);
1073 if (RegisterFilePlayingToMixer() != 0)
1074 return -1;
1075
1076 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001077}
1078
kwiberg55b97fe2016-01-28 05:22:45 -08001079int32_t Channel::StopPlayout() {
1080 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1081 "Channel::StopPlayout()");
1082 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001083 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001084 }
1085
1086 if (!_externalMixing) {
1087 // Remove participant as candidates for mixing
1088 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1089 _engineStatisticsPtr->SetLastError(
1090 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1091 "StopPlayout() failed to remove participant from mixer");
1092 return -1;
1093 }
1094 }
1095
1096 channel_state_.SetPlaying(false);
1097 _outputAudioLevel.Clear();
1098
1099 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001100}
1101
kwiberg55b97fe2016-01-28 05:22:45 -08001102int32_t Channel::StartSend() {
1103 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1104 "Channel::StartSend()");
1105 // Resume the previous sequence number which was reset by StopSend().
1106 // This needs to be done before |sending| is set to true.
1107 if (send_sequence_number_)
1108 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001109
kwiberg55b97fe2016-01-28 05:22:45 -08001110 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001111 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001112 }
1113 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001114
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001115 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001116 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1117 _engineStatisticsPtr->SetLastError(
1118 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1119 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001120 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001121 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001122 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001123 return -1;
1124 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001125
kwiberg55b97fe2016-01-28 05:22:45 -08001126 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001127}
1128
kwiberg55b97fe2016-01-28 05:22:45 -08001129int32_t Channel::StopSend() {
1130 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1131 "Channel::StopSend()");
1132 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001133 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001134 }
1135 channel_state_.SetSending(false);
1136
1137 // Store the sequence number to be able to pick up the same sequence for
1138 // the next StartSend(). This is needed for restarting device, otherwise
1139 // it might cause libSRTP to complain about packets being replayed.
1140 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1141 // CL is landed. See issue
1142 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1143 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1144
1145 // Reset sending SSRC and sequence number and triggers direct transmission
1146 // of RTCP BYE
1147 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1148 _engineStatisticsPtr->SetLastError(
1149 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1150 "StartSend() RTP/RTCP failed to stop sending");
1151 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001152 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001153
1154 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001155}
1156
kwiberg55b97fe2016-01-28 05:22:45 -08001157int32_t Channel::StartReceiving() {
1158 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1159 "Channel::StartReceiving()");
1160 if (channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001161 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001162 }
1163 channel_state_.SetReceiving(true);
1164 _numberOfDiscardedPackets = 0;
1165 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001166}
1167
kwiberg55b97fe2016-01-28 05:22:45 -08001168int32_t Channel::StopReceiving() {
1169 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1170 "Channel::StopReceiving()");
1171 if (!channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001172 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001173 }
1174
1175 channel_state_.SetReceiving(false);
1176 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001177}
1178
kwiberg55b97fe2016-01-28 05:22:45 -08001179int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1180 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1181 "Channel::RegisterVoiceEngineObserver()");
1182 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001183
kwiberg55b97fe2016-01-28 05:22:45 -08001184 if (_voiceEngineObserverPtr) {
1185 _engineStatisticsPtr->SetLastError(
1186 VE_INVALID_OPERATION, kTraceError,
1187 "RegisterVoiceEngineObserver() observer already enabled");
1188 return -1;
1189 }
1190 _voiceEngineObserverPtr = &observer;
1191 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001192}
1193
kwiberg55b97fe2016-01-28 05:22:45 -08001194int32_t Channel::DeRegisterVoiceEngineObserver() {
1195 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1196 "Channel::DeRegisterVoiceEngineObserver()");
1197 rtc::CritScope cs(&_callbackCritSect);
1198
1199 if (!_voiceEngineObserverPtr) {
1200 _engineStatisticsPtr->SetLastError(
1201 VE_INVALID_OPERATION, kTraceWarning,
1202 "DeRegisterVoiceEngineObserver() observer already disabled");
1203 return 0;
1204 }
1205 _voiceEngineObserverPtr = NULL;
1206 return 0;
1207}
1208
1209int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001210 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001211 if (send_codec) {
1212 codec = *send_codec;
1213 return 0;
1214 }
1215 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001216}
1217
kwiberg55b97fe2016-01-28 05:22:45 -08001218int32_t Channel::GetRecCodec(CodecInst& codec) {
1219 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001220}
1221
kwiberg55b97fe2016-01-28 05:22:45 -08001222int32_t Channel::SetSendCodec(const CodecInst& codec) {
1223 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1224 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001225
kwibergc8d071e2016-04-06 12:22:38 -07001226 if (!codec_manager_.RegisterEncoder(codec) ||
1227 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001228 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1229 "SetSendCodec() failed to register codec to ACM");
1230 return -1;
1231 }
1232
1233 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1234 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1235 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1236 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1237 "SetSendCodec() failed to register codec to"
1238 " RTP/RTCP module");
1239 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001240 }
kwiberg55b97fe2016-01-28 05:22:45 -08001241 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001242
kwiberg55b97fe2016-01-28 05:22:45 -08001243 if (_rtpRtcpModule->SetAudioPacketSize(codec.pacsize) != 0) {
1244 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1245 "SetSendCodec() failed to set audio packet size");
1246 return -1;
1247 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001248
kwiberg55b97fe2016-01-28 05:22:45 -08001249 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001250}
1251
Ivo Creusenadf89b72015-04-29 16:03:33 +02001252void Channel::SetBitRate(int bitrate_bps) {
1253 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1254 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
1255 audio_coding_->SetBitRate(bitrate_bps);
1256}
1257
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001258void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue@webrtc.org74aaf292014-07-16 21:28:26 +00001259 network_predictor_->UpdatePacketLossRate(fraction_lost);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001260 uint8_t average_fraction_loss = network_predictor_->GetLossRate();
1261
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001262 // Normalizes rate to 0 - 100.
kwiberg55b97fe2016-01-28 05:22:45 -08001263 if (audio_coding_->SetPacketLossRate(100 * average_fraction_loss / 255) !=
1264 0) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001265 assert(false); // This should not happen.
1266 }
1267}
1268
kwiberg55b97fe2016-01-28 05:22:45 -08001269int32_t Channel::SetVADStatus(bool enableVAD,
1270 ACMVADMode mode,
1271 bool disableDTX) {
1272 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1273 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001274 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1275 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1276 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001277 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1278 kTraceError,
1279 "SetVADStatus() failed to set VAD");
1280 return -1;
1281 }
1282 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001283}
1284
kwiberg55b97fe2016-01-28 05:22:45 -08001285int32_t Channel::GetVADStatus(bool& enabledVAD,
1286 ACMVADMode& mode,
1287 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001288 const auto* params = codec_manager_.GetStackParams();
1289 enabledVAD = params->use_cng;
1290 mode = params->vad_mode;
1291 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001292 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001293}
1294
kwiberg55b97fe2016-01-28 05:22:45 -08001295int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1296 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1297 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001298
kwiberg55b97fe2016-01-28 05:22:45 -08001299 if (channel_state_.Get().playing) {
1300 _engineStatisticsPtr->SetLastError(
1301 VE_ALREADY_PLAYING, kTraceError,
1302 "SetRecPayloadType() unable to set PT while playing");
1303 return -1;
1304 }
1305 if (channel_state_.Get().receiving) {
1306 _engineStatisticsPtr->SetLastError(
1307 VE_ALREADY_LISTENING, kTraceError,
1308 "SetRecPayloadType() unable to set PT while listening");
1309 return -1;
1310 }
1311
1312 if (codec.pltype == -1) {
1313 // De-register the selected codec (RTP/RTCP module and ACM)
1314
1315 int8_t pltype(-1);
1316 CodecInst rxCodec = codec;
1317
1318 // Get payload type for the given codec
1319 rtp_payload_registry_->ReceivePayloadType(
1320 rxCodec.plname, rxCodec.plfreq, rxCodec.channels,
1321 (rxCodec.rate < 0) ? 0 : rxCodec.rate, &pltype);
1322 rxCodec.pltype = pltype;
1323
1324 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1325 _engineStatisticsPtr->SetLastError(
1326 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1327 "SetRecPayloadType() RTP/RTCP-module deregistration "
1328 "failed");
1329 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001330 }
kwiberg55b97fe2016-01-28 05:22:45 -08001331 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1332 _engineStatisticsPtr->SetLastError(
1333 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1334 "SetRecPayloadType() ACM deregistration failed - 1");
1335 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001336 }
kwiberg55b97fe2016-01-28 05:22:45 -08001337 return 0;
1338 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001339
kwiberg55b97fe2016-01-28 05:22:45 -08001340 if (rtp_receiver_->RegisterReceivePayload(
1341 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1342 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1343 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001344 // TODO(kwiberg): Retrying is probably not necessary, since
1345 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001346 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001347 if (rtp_receiver_->RegisterReceivePayload(
kwiberg55b97fe2016-01-28 05:22:45 -08001348 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1349 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1350 _engineStatisticsPtr->SetLastError(
1351 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1352 "SetRecPayloadType() RTP/RTCP-module registration failed");
1353 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001354 }
kwiberg55b97fe2016-01-28 05:22:45 -08001355 }
kwibergc8d071e2016-04-06 12:22:38 -07001356 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001357 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergc8d071e2016-04-06 12:22:38 -07001358 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001359 _engineStatisticsPtr->SetLastError(
1360 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1361 "SetRecPayloadType() ACM registration failed - 1");
1362 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001363 }
kwiberg55b97fe2016-01-28 05:22:45 -08001364 }
1365 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001366}
1367
kwiberg55b97fe2016-01-28 05:22:45 -08001368int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1369 int8_t payloadType(-1);
1370 if (rtp_payload_registry_->ReceivePayloadType(
1371 codec.plname, codec.plfreq, codec.channels,
1372 (codec.rate < 0) ? 0 : codec.rate, &payloadType) != 0) {
1373 _engineStatisticsPtr->SetLastError(
1374 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1375 "GetRecPayloadType() failed to retrieve RX payload type");
1376 return -1;
1377 }
1378 codec.pltype = payloadType;
1379 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001380}
1381
kwiberg55b97fe2016-01-28 05:22:45 -08001382int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1383 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1384 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001385
kwiberg55b97fe2016-01-28 05:22:45 -08001386 CodecInst codec;
1387 int32_t samplingFreqHz(-1);
1388 const size_t kMono = 1;
1389 if (frequency == kFreq32000Hz)
1390 samplingFreqHz = 32000;
1391 else if (frequency == kFreq16000Hz)
1392 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001393
kwiberg55b97fe2016-01-28 05:22:45 -08001394 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1395 _engineStatisticsPtr->SetLastError(
1396 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1397 "SetSendCNPayloadType() failed to retrieve default CN codec "
1398 "settings");
1399 return -1;
1400 }
1401
1402 // Modify the payload type (must be set to dynamic range)
1403 codec.pltype = type;
1404
kwibergc8d071e2016-04-06 12:22:38 -07001405 if (!codec_manager_.RegisterEncoder(codec) ||
1406 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001407 _engineStatisticsPtr->SetLastError(
1408 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1409 "SetSendCNPayloadType() failed to register CN to ACM");
1410 return -1;
1411 }
1412
1413 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1414 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1415 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1416 _engineStatisticsPtr->SetLastError(
1417 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1418 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1419 "module");
1420 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001421 }
kwiberg55b97fe2016-01-28 05:22:45 -08001422 }
1423 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001424}
1425
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001426int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001427 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001428 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001429
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001430 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001431 _engineStatisticsPtr->SetLastError(
1432 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001433 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001434 return -1;
1435 }
1436 return 0;
1437}
1438
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001439int Channel::SetOpusDtx(bool enable_dtx) {
1440 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1441 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001442 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001443 : audio_coding_->DisableOpusDtx();
1444 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001445 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1446 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001447 return -1;
1448 }
1449 return 0;
1450}
1451
mflodman3d7db262016-04-29 00:57:13 -07001452int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001453 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001454 "Channel::RegisterExternalTransport()");
1455
kwiberg55b97fe2016-01-28 05:22:45 -08001456 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001457 if (_externalTransport) {
1458 _engineStatisticsPtr->SetLastError(
1459 VE_INVALID_OPERATION, kTraceError,
1460 "RegisterExternalTransport() external transport already enabled");
1461 return -1;
1462 }
1463 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001464 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001465 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001466}
1467
kwiberg55b97fe2016-01-28 05:22:45 -08001468int32_t Channel::DeRegisterExternalTransport() {
1469 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1470 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001471
kwiberg55b97fe2016-01-28 05:22:45 -08001472 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001473 if (_transportPtr) {
1474 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1475 "DeRegisterExternalTransport() all transport is disabled");
1476 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001477 _engineStatisticsPtr->SetLastError(
1478 VE_INVALID_OPERATION, kTraceWarning,
1479 "DeRegisterExternalTransport() external transport already "
1480 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001481 }
1482 _externalTransport = false;
1483 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001484 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001485}
1486
mflodman3d7db262016-04-29 00:57:13 -07001487int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001488 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001489 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001490 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001491 "Channel::ReceivedRTPPacket()");
1492
1493 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001494 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001495
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001496 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001497 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1498 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1499 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001500 return -1;
1501 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001502 header.payload_type_frequency =
1503 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001504 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001505 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001506 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001507 rtp_receive_statistics_->IncomingPacket(
1508 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001509 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001510
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001511 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001512}
1513
1514bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001515 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001516 const RTPHeader& header,
1517 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001518 if (rtp_payload_registry_->IsRtx(header)) {
1519 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001520 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001521 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001522 assert(packet_length >= header.headerLength);
1523 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001524 PayloadUnion payload_specific;
1525 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001526 &payload_specific)) {
1527 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001528 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001529 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1530 payload_specific, in_order);
1531}
1532
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001533bool Channel::HandleRtxPacket(const uint8_t* packet,
1534 size_t packet_length,
1535 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001536 if (!rtp_payload_registry_->IsRtx(header))
1537 return false;
1538
1539 // Remove the RTX header and parse the original RTP header.
1540 if (packet_length < header.headerLength)
1541 return false;
1542 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1543 return false;
1544 if (restored_packet_in_use_) {
1545 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1546 "Multiple RTX headers detected, dropping packet");
1547 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001548 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001549 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001550 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1551 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001552 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1553 "Incoming RTX packet: invalid RTP header");
1554 return false;
1555 }
1556 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001557 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001558 restored_packet_in_use_ = false;
1559 return ret;
1560}
1561
1562bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1563 StreamStatistician* statistician =
1564 rtp_receive_statistics_->GetStatistician(header.ssrc);
1565 if (!statistician)
1566 return false;
1567 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001568}
1569
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001570bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1571 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001572 // Retransmissions are handled separately if RTX is enabled.
1573 if (rtp_payload_registry_->RtxEnabled())
1574 return false;
1575 StreamStatistician* statistician =
1576 rtp_receive_statistics_->GetStatistician(header.ssrc);
1577 if (!statistician)
1578 return false;
1579 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001580 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001581 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001582 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001583}
1584
mflodman3d7db262016-04-29 00:57:13 -07001585int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001586 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001587 "Channel::ReceivedRTCPPacket()");
1588 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001589 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001590
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001591 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001592 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001593 _engineStatisticsPtr->SetLastError(
1594 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1595 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1596 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001597
Minyue2013aec2015-05-13 14:14:42 +02001598 int64_t rtt = GetRTT(true);
1599 if (rtt == 0) {
1600 // Waiting for valid RTT.
1601 return 0;
1602 }
1603 uint32_t ntp_secs = 0;
1604 uint32_t ntp_frac = 0;
1605 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001606 if (0 !=
1607 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1608 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001609 // Waiting for RTCP.
1610 return 0;
1611 }
1612
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001613 {
tommi31fc21f2016-01-21 10:37:37 -08001614 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001615 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001616 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001617 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001618}
1619
niklase@google.com470e71d2011-07-07 08:21:25 +00001620int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001621 bool loop,
1622 FileFormats format,
1623 int startPosition,
1624 float volumeScaling,
1625 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001626 const CodecInst* codecInst) {
1627 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1628 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1629 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1630 "stopPosition=%d)",
1631 fileName, loop, format, volumeScaling, startPosition,
1632 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001633
kwiberg55b97fe2016-01-28 05:22:45 -08001634 if (channel_state_.Get().output_file_playing) {
1635 _engineStatisticsPtr->SetLastError(
1636 VE_ALREADY_PLAYING, kTraceError,
1637 "StartPlayingFileLocally() is already playing");
1638 return -1;
1639 }
1640
1641 {
1642 rtc::CritScope cs(&_fileCritSect);
1643
1644 if (_outputFilePlayerPtr) {
1645 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1646 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1647 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001648 }
1649
kwiberg55b97fe2016-01-28 05:22:45 -08001650 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1651 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001652
kwiberg55b97fe2016-01-28 05:22:45 -08001653 if (_outputFilePlayerPtr == NULL) {
1654 _engineStatisticsPtr->SetLastError(
1655 VE_INVALID_ARGUMENT, kTraceError,
1656 "StartPlayingFileLocally() filePlayer format is not correct");
1657 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001658 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001659
kwiberg55b97fe2016-01-28 05:22:45 -08001660 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001661
kwiberg55b97fe2016-01-28 05:22:45 -08001662 if (_outputFilePlayerPtr->StartPlayingFile(
1663 fileName, loop, startPosition, volumeScaling, notificationTime,
1664 stopPosition, (const CodecInst*)codecInst) != 0) {
1665 _engineStatisticsPtr->SetLastError(
1666 VE_BAD_FILE, kTraceError,
1667 "StartPlayingFile() failed to start file playout");
1668 _outputFilePlayerPtr->StopPlayingFile();
1669 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1670 _outputFilePlayerPtr = NULL;
1671 return -1;
1672 }
1673 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1674 channel_state_.SetOutputFilePlaying(true);
1675 }
1676
1677 if (RegisterFilePlayingToMixer() != 0)
1678 return -1;
1679
1680 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001681}
1682
1683int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001684 FileFormats format,
1685 int startPosition,
1686 float volumeScaling,
1687 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001688 const CodecInst* codecInst) {
1689 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1690 "Channel::StartPlayingFileLocally(format=%d,"
1691 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1692 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001693
kwiberg55b97fe2016-01-28 05:22:45 -08001694 if (stream == NULL) {
1695 _engineStatisticsPtr->SetLastError(
1696 VE_BAD_FILE, kTraceError,
1697 "StartPlayingFileLocally() NULL as input stream");
1698 return -1;
1699 }
1700
1701 if (channel_state_.Get().output_file_playing) {
1702 _engineStatisticsPtr->SetLastError(
1703 VE_ALREADY_PLAYING, kTraceError,
1704 "StartPlayingFileLocally() is already playing");
1705 return -1;
1706 }
1707
1708 {
1709 rtc::CritScope cs(&_fileCritSect);
1710
1711 // Destroy the old instance
1712 if (_outputFilePlayerPtr) {
1713 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1714 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1715 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001716 }
1717
kwiberg55b97fe2016-01-28 05:22:45 -08001718 // Create the instance
1719 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1720 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001721
kwiberg55b97fe2016-01-28 05:22:45 -08001722 if (_outputFilePlayerPtr == NULL) {
1723 _engineStatisticsPtr->SetLastError(
1724 VE_INVALID_ARGUMENT, kTraceError,
1725 "StartPlayingFileLocally() filePlayer format isnot correct");
1726 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001727 }
1728
kwiberg55b97fe2016-01-28 05:22:45 -08001729 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001730
kwiberg55b97fe2016-01-28 05:22:45 -08001731 if (_outputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1732 volumeScaling, notificationTime,
1733 stopPosition, codecInst) != 0) {
1734 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1735 "StartPlayingFile() failed to "
1736 "start file playout");
1737 _outputFilePlayerPtr->StopPlayingFile();
1738 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1739 _outputFilePlayerPtr = NULL;
1740 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001741 }
kwiberg55b97fe2016-01-28 05:22:45 -08001742 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1743 channel_state_.SetOutputFilePlaying(true);
1744 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001745
kwiberg55b97fe2016-01-28 05:22:45 -08001746 if (RegisterFilePlayingToMixer() != 0)
1747 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001748
kwiberg55b97fe2016-01-28 05:22:45 -08001749 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001750}
1751
kwiberg55b97fe2016-01-28 05:22:45 -08001752int Channel::StopPlayingFileLocally() {
1753 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1754 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001755
kwiberg55b97fe2016-01-28 05:22:45 -08001756 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001757 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001758 }
1759
1760 {
1761 rtc::CritScope cs(&_fileCritSect);
1762
1763 if (_outputFilePlayerPtr->StopPlayingFile() != 0) {
1764 _engineStatisticsPtr->SetLastError(
1765 VE_STOP_RECORDING_FAILED, kTraceError,
1766 "StopPlayingFile() could not stop playing");
1767 return -1;
1768 }
1769 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1770 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1771 _outputFilePlayerPtr = NULL;
1772 channel_state_.SetOutputFilePlaying(false);
1773 }
1774 // _fileCritSect cannot be taken while calling
1775 // SetAnonymousMixibilityStatus. Refer to comments in
1776 // StartPlayingFileLocally(const char* ...) for more details.
1777 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1778 _engineStatisticsPtr->SetLastError(
1779 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1780 "StopPlayingFile() failed to stop participant from playing as"
1781 "file in the mixer");
1782 return -1;
1783 }
1784
1785 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001786}
1787
kwiberg55b97fe2016-01-28 05:22:45 -08001788int Channel::IsPlayingFileLocally() const {
1789 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001790}
1791
kwiberg55b97fe2016-01-28 05:22:45 -08001792int Channel::RegisterFilePlayingToMixer() {
1793 // Return success for not registering for file playing to mixer if:
1794 // 1. playing file before playout is started on that channel.
1795 // 2. starting playout without file playing on that channel.
1796 if (!channel_state_.Get().playing ||
1797 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001798 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001799 }
1800
1801 // |_fileCritSect| cannot be taken while calling
1802 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1803 // frames can be pulled by the mixer. Since the frames are generated from
1804 // the file, _fileCritSect will be taken. This would result in a deadlock.
1805 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1806 channel_state_.SetOutputFilePlaying(false);
1807 rtc::CritScope cs(&_fileCritSect);
1808 _engineStatisticsPtr->SetLastError(
1809 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1810 "StartPlayingFile() failed to add participant as file to mixer");
1811 _outputFilePlayerPtr->StopPlayingFile();
1812 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1813 _outputFilePlayerPtr = NULL;
1814 return -1;
1815 }
1816
1817 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001818}
1819
niklase@google.com470e71d2011-07-07 08:21:25 +00001820int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001821 bool loop,
1822 FileFormats format,
1823 int startPosition,
1824 float volumeScaling,
1825 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001826 const CodecInst* codecInst) {
1827 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1828 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1829 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1830 "stopPosition=%d)",
1831 fileName, loop, format, volumeScaling, startPosition,
1832 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001833
kwiberg55b97fe2016-01-28 05:22:45 -08001834 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001835
kwiberg55b97fe2016-01-28 05:22:45 -08001836 if (channel_state_.Get().input_file_playing) {
1837 _engineStatisticsPtr->SetLastError(
1838 VE_ALREADY_PLAYING, kTraceWarning,
1839 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001840 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001841 }
1842
1843 // Destroy the old instance
1844 if (_inputFilePlayerPtr) {
1845 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1846 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1847 _inputFilePlayerPtr = NULL;
1848 }
1849
1850 // Create the instance
1851 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1852 (const FileFormats)format);
1853
1854 if (_inputFilePlayerPtr == NULL) {
1855 _engineStatisticsPtr->SetLastError(
1856 VE_INVALID_ARGUMENT, kTraceError,
1857 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1858 return -1;
1859 }
1860
1861 const uint32_t notificationTime(0);
1862
1863 if (_inputFilePlayerPtr->StartPlayingFile(
1864 fileName, loop, startPosition, volumeScaling, notificationTime,
1865 stopPosition, (const CodecInst*)codecInst) != 0) {
1866 _engineStatisticsPtr->SetLastError(
1867 VE_BAD_FILE, kTraceError,
1868 "StartPlayingFile() failed to start file playout");
1869 _inputFilePlayerPtr->StopPlayingFile();
1870 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1871 _inputFilePlayerPtr = NULL;
1872 return -1;
1873 }
1874 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1875 channel_state_.SetInputFilePlaying(true);
1876
1877 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001878}
1879
1880int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001881 FileFormats format,
1882 int startPosition,
1883 float volumeScaling,
1884 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001885 const CodecInst* codecInst) {
1886 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1887 "Channel::StartPlayingFileAsMicrophone(format=%d, "
1888 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1889 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001890
kwiberg55b97fe2016-01-28 05:22:45 -08001891 if (stream == NULL) {
1892 _engineStatisticsPtr->SetLastError(
1893 VE_BAD_FILE, kTraceError,
1894 "StartPlayingFileAsMicrophone NULL as input stream");
1895 return -1;
1896 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001897
kwiberg55b97fe2016-01-28 05:22:45 -08001898 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001899
kwiberg55b97fe2016-01-28 05:22:45 -08001900 if (channel_state_.Get().input_file_playing) {
1901 _engineStatisticsPtr->SetLastError(
1902 VE_ALREADY_PLAYING, kTraceWarning,
1903 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001904 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001905 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001906
kwiberg55b97fe2016-01-28 05:22:45 -08001907 // Destroy the old instance
1908 if (_inputFilePlayerPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001909 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1910 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1911 _inputFilePlayerPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001912 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001913
kwiberg55b97fe2016-01-28 05:22:45 -08001914 // Create the instance
1915 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1916 (const FileFormats)format);
1917
1918 if (_inputFilePlayerPtr == NULL) {
1919 _engineStatisticsPtr->SetLastError(
1920 VE_INVALID_ARGUMENT, kTraceError,
1921 "StartPlayingInputFile() filePlayer format isnot correct");
1922 return -1;
1923 }
1924
1925 const uint32_t notificationTime(0);
1926
1927 if (_inputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1928 volumeScaling, notificationTime,
1929 stopPosition, codecInst) != 0) {
1930 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1931 "StartPlayingFile() failed to start "
1932 "file playout");
1933 _inputFilePlayerPtr->StopPlayingFile();
1934 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1935 _inputFilePlayerPtr = NULL;
1936 return -1;
1937 }
1938
1939 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1940 channel_state_.SetInputFilePlaying(true);
1941
1942 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001943}
1944
kwiberg55b97fe2016-01-28 05:22:45 -08001945int Channel::StopPlayingFileAsMicrophone() {
1946 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1947 "Channel::StopPlayingFileAsMicrophone()");
1948
1949 rtc::CritScope cs(&_fileCritSect);
1950
1951 if (!channel_state_.Get().input_file_playing) {
1952 return 0;
1953 }
1954
1955 if (_inputFilePlayerPtr->StopPlayingFile() != 0) {
1956 _engineStatisticsPtr->SetLastError(
1957 VE_STOP_RECORDING_FAILED, kTraceError,
1958 "StopPlayingFile() could not stop playing");
1959 return -1;
1960 }
1961 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1962 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1963 _inputFilePlayerPtr = NULL;
1964 channel_state_.SetInputFilePlaying(false);
1965
1966 return 0;
1967}
1968
1969int Channel::IsPlayingFileAsMicrophone() const {
1970 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001971}
1972
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00001973int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08001974 const CodecInst* codecInst) {
1975 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1976 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00001977
kwiberg55b97fe2016-01-28 05:22:45 -08001978 if (_outputFileRecording) {
1979 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
1980 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00001981 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001982 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001983
kwiberg55b97fe2016-01-28 05:22:45 -08001984 FileFormats format;
1985 const uint32_t notificationTime(0); // Not supported in VoE
1986 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00001987
kwiberg55b97fe2016-01-28 05:22:45 -08001988 if ((codecInst != NULL) &&
1989 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
1990 _engineStatisticsPtr->SetLastError(
1991 VE_BAD_ARGUMENT, kTraceError,
1992 "StartRecordingPlayout() invalid compression");
1993 return (-1);
1994 }
1995 if (codecInst == NULL) {
1996 format = kFileFormatPcm16kHzFile;
1997 codecInst = &dummyCodec;
1998 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
1999 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2000 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2001 format = kFileFormatWavFile;
2002 } else {
2003 format = kFileFormatCompressedFile;
2004 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002005
kwiberg55b97fe2016-01-28 05:22:45 -08002006 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002007
kwiberg55b97fe2016-01-28 05:22:45 -08002008 // Destroy the old instance
2009 if (_outputFileRecorderPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002010 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2011 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2012 _outputFileRecorderPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08002013 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002014
kwiberg55b97fe2016-01-28 05:22:45 -08002015 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2016 _outputFileRecorderId, (const FileFormats)format);
2017 if (_outputFileRecorderPtr == NULL) {
2018 _engineStatisticsPtr->SetLastError(
2019 VE_INVALID_ARGUMENT, kTraceError,
2020 "StartRecordingPlayout() fileRecorder format isnot correct");
2021 return -1;
2022 }
2023
2024 if (_outputFileRecorderPtr->StartRecordingAudioFile(
2025 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2026 _engineStatisticsPtr->SetLastError(
2027 VE_BAD_FILE, kTraceError,
2028 "StartRecordingAudioFile() failed to start file recording");
2029 _outputFileRecorderPtr->StopRecording();
2030 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2031 _outputFileRecorderPtr = NULL;
2032 return -1;
2033 }
2034 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2035 _outputFileRecording = true;
2036
2037 return 0;
2038}
2039
2040int Channel::StartRecordingPlayout(OutStream* stream,
2041 const CodecInst* codecInst) {
2042 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2043 "Channel::StartRecordingPlayout()");
2044
2045 if (_outputFileRecording) {
2046 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2047 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002048 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002049 }
2050
2051 FileFormats format;
2052 const uint32_t notificationTime(0); // Not supported in VoE
2053 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2054
2055 if (codecInst != NULL && codecInst->channels != 1) {
2056 _engineStatisticsPtr->SetLastError(
2057 VE_BAD_ARGUMENT, kTraceError,
2058 "StartRecordingPlayout() invalid compression");
2059 return (-1);
2060 }
2061 if (codecInst == NULL) {
2062 format = kFileFormatPcm16kHzFile;
2063 codecInst = &dummyCodec;
2064 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2065 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2066 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2067 format = kFileFormatWavFile;
2068 } else {
2069 format = kFileFormatCompressedFile;
2070 }
2071
2072 rtc::CritScope cs(&_fileCritSect);
2073
2074 // Destroy the old instance
2075 if (_outputFileRecorderPtr) {
2076 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2077 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2078 _outputFileRecorderPtr = NULL;
2079 }
2080
2081 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2082 _outputFileRecorderId, (const FileFormats)format);
2083 if (_outputFileRecorderPtr == NULL) {
2084 _engineStatisticsPtr->SetLastError(
2085 VE_INVALID_ARGUMENT, kTraceError,
2086 "StartRecordingPlayout() fileRecorder format isnot correct");
2087 return -1;
2088 }
2089
2090 if (_outputFileRecorderPtr->StartRecordingAudioFile(*stream, *codecInst,
2091 notificationTime) != 0) {
2092 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2093 "StartRecordingPlayout() failed to "
2094 "start file recording");
2095 _outputFileRecorderPtr->StopRecording();
2096 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2097 _outputFileRecorderPtr = NULL;
2098 return -1;
2099 }
2100
2101 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2102 _outputFileRecording = true;
2103
2104 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002105}
2106
kwiberg55b97fe2016-01-28 05:22:45 -08002107int Channel::StopRecordingPlayout() {
2108 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2109 "Channel::StopRecordingPlayout()");
2110
2111 if (!_outputFileRecording) {
2112 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2113 "StopRecordingPlayout() isnot recording");
2114 return -1;
2115 }
2116
2117 rtc::CritScope cs(&_fileCritSect);
2118
2119 if (_outputFileRecorderPtr->StopRecording() != 0) {
2120 _engineStatisticsPtr->SetLastError(
2121 VE_STOP_RECORDING_FAILED, kTraceError,
2122 "StopRecording() could not stop recording");
2123 return (-1);
2124 }
2125 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2126 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2127 _outputFileRecorderPtr = NULL;
2128 _outputFileRecording = false;
2129
2130 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002131}
2132
kwiberg55b97fe2016-01-28 05:22:45 -08002133void Channel::SetMixWithMicStatus(bool mix) {
2134 rtc::CritScope cs(&_fileCritSect);
2135 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002136}
2137
kwiberg55b97fe2016-01-28 05:22:45 -08002138int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2139 int8_t currentLevel = _outputAudioLevel.Level();
2140 level = static_cast<int32_t>(currentLevel);
2141 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002142}
2143
kwiberg55b97fe2016-01-28 05:22:45 -08002144int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2145 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2146 level = static_cast<int32_t>(currentLevel);
2147 return 0;
2148}
2149
solenberg1c2af8e2016-03-24 10:36:00 -07002150int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002151 rtc::CritScope cs(&volume_settings_critsect_);
2152 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002153 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002154 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002155 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002156}
2157
solenberg1c2af8e2016-03-24 10:36:00 -07002158bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002159 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002160 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002161}
2162
kwiberg55b97fe2016-01-28 05:22:45 -08002163int Channel::SetOutputVolumePan(float left, float right) {
2164 rtc::CritScope cs(&volume_settings_critsect_);
2165 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002166 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002167 _panLeft = left;
2168 _panRight = right;
2169 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002170}
2171
kwiberg55b97fe2016-01-28 05:22:45 -08002172int Channel::GetOutputVolumePan(float& left, float& right) const {
2173 rtc::CritScope cs(&volume_settings_critsect_);
2174 left = _panLeft;
2175 right = _panRight;
2176 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002177}
2178
kwiberg55b97fe2016-01-28 05:22:45 -08002179int Channel::SetChannelOutputVolumeScaling(float scaling) {
2180 rtc::CritScope cs(&volume_settings_critsect_);
2181 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002182 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002183 _outputGain = scaling;
2184 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002185}
2186
kwiberg55b97fe2016-01-28 05:22:45 -08002187int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2188 rtc::CritScope cs(&volume_settings_critsect_);
2189 scaling = _outputGain;
2190 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002191}
2192
solenberg8842c3e2016-03-11 03:06:41 -08002193int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002194 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002195 "Channel::SendTelephoneEventOutband(...)");
2196 RTC_DCHECK_LE(0, event);
2197 RTC_DCHECK_GE(255, event);
2198 RTC_DCHECK_LE(0, duration_ms);
2199 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002200 if (!Sending()) {
2201 return -1;
2202 }
solenberg8842c3e2016-03-11 03:06:41 -08002203 if (_rtpRtcpModule->SendTelephoneEventOutband(
2204 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002205 _engineStatisticsPtr->SetLastError(
2206 VE_SEND_DTMF_FAILED, kTraceWarning,
2207 "SendTelephoneEventOutband() failed to send event");
2208 return -1;
2209 }
2210 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002211}
2212
solenberg31642aa2016-03-14 08:00:37 -07002213int Channel::SetSendTelephoneEventPayloadType(int payload_type) {
kwiberg55b97fe2016-01-28 05:22:45 -08002214 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002215 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002216 RTC_DCHECK_LE(0, payload_type);
2217 RTC_DCHECK_GE(127, payload_type);
2218 CodecInst codec = {0};
kwiberg55b97fe2016-01-28 05:22:45 -08002219 codec.plfreq = 8000;
solenberg31642aa2016-03-14 08:00:37 -07002220 codec.pltype = payload_type;
kwiberg55b97fe2016-01-28 05:22:45 -08002221 memcpy(codec.plname, "telephone-event", 16);
2222 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2223 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2224 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2225 _engineStatisticsPtr->SetLastError(
2226 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2227 "SetSendTelephoneEventPayloadType() failed to register send"
2228 "payload type");
2229 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002230 }
kwiberg55b97fe2016-01-28 05:22:45 -08002231 }
kwiberg55b97fe2016-01-28 05:22:45 -08002232 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002233}
2234
kwiberg55b97fe2016-01-28 05:22:45 -08002235int Channel::UpdateRxVadDetection(AudioFrame& audioFrame) {
2236 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2237 "Channel::UpdateRxVadDetection()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002238
kwiberg55b97fe2016-01-28 05:22:45 -08002239 int vadDecision = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002240
kwiberg55b97fe2016-01-28 05:22:45 -08002241 vadDecision = (audioFrame.vad_activity_ == AudioFrame::kVadActive) ? 1 : 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002242
kwiberg55b97fe2016-01-28 05:22:45 -08002243 if ((vadDecision != _oldVadDecision) && _rxVadObserverPtr) {
2244 OnRxVadDetected(vadDecision);
2245 _oldVadDecision = vadDecision;
2246 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002247
kwiberg55b97fe2016-01-28 05:22:45 -08002248 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2249 "Channel::UpdateRxVadDetection() => vadDecision=%d",
2250 vadDecision);
2251 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002252}
2253
kwiberg55b97fe2016-01-28 05:22:45 -08002254int Channel::RegisterRxVadObserver(VoERxVadCallback& observer) {
2255 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2256 "Channel::RegisterRxVadObserver()");
2257 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002258
kwiberg55b97fe2016-01-28 05:22:45 -08002259 if (_rxVadObserverPtr) {
2260 _engineStatisticsPtr->SetLastError(
2261 VE_INVALID_OPERATION, kTraceError,
2262 "RegisterRxVadObserver() observer already enabled");
2263 return -1;
2264 }
2265 _rxVadObserverPtr = &observer;
2266 _RxVadDetection = true;
2267 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002268}
2269
kwiberg55b97fe2016-01-28 05:22:45 -08002270int Channel::DeRegisterRxVadObserver() {
2271 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2272 "Channel::DeRegisterRxVadObserver()");
2273 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002274
kwiberg55b97fe2016-01-28 05:22:45 -08002275 if (!_rxVadObserverPtr) {
2276 _engineStatisticsPtr->SetLastError(
2277 VE_INVALID_OPERATION, kTraceWarning,
2278 "DeRegisterRxVadObserver() observer already disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00002279 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002280 }
2281 _rxVadObserverPtr = NULL;
2282 _RxVadDetection = false;
2283 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002284}
2285
kwiberg55b97fe2016-01-28 05:22:45 -08002286int Channel::VoiceActivityIndicator(int& activity) {
2287 activity = _sendFrameType;
2288 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002289}
2290
2291#ifdef WEBRTC_VOICE_ENGINE_AGC
2292
kwiberg55b97fe2016-01-28 05:22:45 -08002293int Channel::SetRxAgcStatus(bool enable, AgcModes mode) {
2294 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2295 "Channel::SetRxAgcStatus(enable=%d, mode=%d)", (int)enable,
2296 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002297
kwiberg55b97fe2016-01-28 05:22:45 -08002298 GainControl::Mode agcMode = kDefaultRxAgcMode;
2299 switch (mode) {
2300 case kAgcDefault:
2301 break;
2302 case kAgcUnchanged:
2303 agcMode = rx_audioproc_->gain_control()->mode();
2304 break;
2305 case kAgcFixedDigital:
2306 agcMode = GainControl::kFixedDigital;
2307 break;
2308 case kAgcAdaptiveDigital:
2309 agcMode = GainControl::kAdaptiveDigital;
2310 break;
2311 default:
2312 _engineStatisticsPtr->SetLastError(VE_INVALID_ARGUMENT, kTraceError,
2313 "SetRxAgcStatus() invalid Agc mode");
2314 return -1;
2315 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002316
kwiberg55b97fe2016-01-28 05:22:45 -08002317 if (rx_audioproc_->gain_control()->set_mode(agcMode) != 0) {
2318 _engineStatisticsPtr->SetLastError(
2319 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc mode");
2320 return -1;
2321 }
2322 if (rx_audioproc_->gain_control()->Enable(enable) != 0) {
2323 _engineStatisticsPtr->SetLastError(
2324 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc state");
2325 return -1;
2326 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002327
kwiberg55b97fe2016-01-28 05:22:45 -08002328 _rxAgcIsEnabled = enable;
2329 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002330
kwiberg55b97fe2016-01-28 05:22:45 -08002331 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002332}
2333
kwiberg55b97fe2016-01-28 05:22:45 -08002334int Channel::GetRxAgcStatus(bool& enabled, AgcModes& mode) {
2335 bool enable = rx_audioproc_->gain_control()->is_enabled();
2336 GainControl::Mode agcMode = rx_audioproc_->gain_control()->mode();
niklase@google.com470e71d2011-07-07 08:21:25 +00002337
kwiberg55b97fe2016-01-28 05:22:45 -08002338 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002339
kwiberg55b97fe2016-01-28 05:22:45 -08002340 switch (agcMode) {
2341 case GainControl::kFixedDigital:
2342 mode = kAgcFixedDigital;
2343 break;
2344 case GainControl::kAdaptiveDigital:
2345 mode = kAgcAdaptiveDigital;
2346 break;
2347 default:
2348 _engineStatisticsPtr->SetLastError(VE_APM_ERROR, kTraceError,
2349 "GetRxAgcStatus() invalid Agc mode");
2350 return -1;
2351 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002352
kwiberg55b97fe2016-01-28 05:22:45 -08002353 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002354}
2355
kwiberg55b97fe2016-01-28 05:22:45 -08002356int Channel::SetRxAgcConfig(AgcConfig config) {
2357 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2358 "Channel::SetRxAgcConfig()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002359
kwiberg55b97fe2016-01-28 05:22:45 -08002360 if (rx_audioproc_->gain_control()->set_target_level_dbfs(
2361 config.targetLeveldBOv) != 0) {
2362 _engineStatisticsPtr->SetLastError(
2363 VE_APM_ERROR, kTraceError,
2364 "SetRxAgcConfig() failed to set target peak |level|"
2365 "(or envelope) of the Agc");
2366 return -1;
2367 }
2368 if (rx_audioproc_->gain_control()->set_compression_gain_db(
2369 config.digitalCompressionGaindB) != 0) {
2370 _engineStatisticsPtr->SetLastError(
2371 VE_APM_ERROR, kTraceError,
2372 "SetRxAgcConfig() failed to set the range in |gain| the"
2373 " digital compression stage may apply");
2374 return -1;
2375 }
2376 if (rx_audioproc_->gain_control()->enable_limiter(config.limiterEnable) !=
2377 0) {
2378 _engineStatisticsPtr->SetLastError(
2379 VE_APM_ERROR, kTraceError,
2380 "SetRxAgcConfig() failed to set hard limiter to the signal");
2381 return -1;
2382 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002383
kwiberg55b97fe2016-01-28 05:22:45 -08002384 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002385}
2386
kwiberg55b97fe2016-01-28 05:22:45 -08002387int Channel::GetRxAgcConfig(AgcConfig& config) {
2388 config.targetLeveldBOv = rx_audioproc_->gain_control()->target_level_dbfs();
2389 config.digitalCompressionGaindB =
2390 rx_audioproc_->gain_control()->compression_gain_db();
2391 config.limiterEnable = rx_audioproc_->gain_control()->is_limiter_enabled();
niklase@google.com470e71d2011-07-07 08:21:25 +00002392
kwiberg55b97fe2016-01-28 05:22:45 -08002393 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002394}
2395
kwiberg55b97fe2016-01-28 05:22:45 -08002396#endif // #ifdef WEBRTC_VOICE_ENGINE_AGC
niklase@google.com470e71d2011-07-07 08:21:25 +00002397
2398#ifdef WEBRTC_VOICE_ENGINE_NR
2399
kwiberg55b97fe2016-01-28 05:22:45 -08002400int Channel::SetRxNsStatus(bool enable, NsModes mode) {
2401 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2402 "Channel::SetRxNsStatus(enable=%d, mode=%d)", (int)enable,
2403 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002404
kwiberg55b97fe2016-01-28 05:22:45 -08002405 NoiseSuppression::Level nsLevel = kDefaultNsMode;
2406 switch (mode) {
2407 case kNsDefault:
2408 break;
2409 case kNsUnchanged:
2410 nsLevel = rx_audioproc_->noise_suppression()->level();
2411 break;
2412 case kNsConference:
2413 nsLevel = NoiseSuppression::kHigh;
2414 break;
2415 case kNsLowSuppression:
2416 nsLevel = NoiseSuppression::kLow;
2417 break;
2418 case kNsModerateSuppression:
2419 nsLevel = NoiseSuppression::kModerate;
2420 break;
2421 case kNsHighSuppression:
2422 nsLevel = NoiseSuppression::kHigh;
2423 break;
2424 case kNsVeryHighSuppression:
2425 nsLevel = NoiseSuppression::kVeryHigh;
2426 break;
2427 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002428
kwiberg55b97fe2016-01-28 05:22:45 -08002429 if (rx_audioproc_->noise_suppression()->set_level(nsLevel) != 0) {
2430 _engineStatisticsPtr->SetLastError(
2431 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS level");
2432 return -1;
2433 }
2434 if (rx_audioproc_->noise_suppression()->Enable(enable) != 0) {
2435 _engineStatisticsPtr->SetLastError(
2436 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS state");
2437 return -1;
2438 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002439
kwiberg55b97fe2016-01-28 05:22:45 -08002440 _rxNsIsEnabled = enable;
2441 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002442
kwiberg55b97fe2016-01-28 05:22:45 -08002443 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002444}
2445
kwiberg55b97fe2016-01-28 05:22:45 -08002446int Channel::GetRxNsStatus(bool& enabled, NsModes& mode) {
2447 bool enable = rx_audioproc_->noise_suppression()->is_enabled();
2448 NoiseSuppression::Level ncLevel = rx_audioproc_->noise_suppression()->level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002449
kwiberg55b97fe2016-01-28 05:22:45 -08002450 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002451
kwiberg55b97fe2016-01-28 05:22:45 -08002452 switch (ncLevel) {
2453 case NoiseSuppression::kLow:
2454 mode = kNsLowSuppression;
2455 break;
2456 case NoiseSuppression::kModerate:
2457 mode = kNsModerateSuppression;
2458 break;
2459 case NoiseSuppression::kHigh:
2460 mode = kNsHighSuppression;
2461 break;
2462 case NoiseSuppression::kVeryHigh:
2463 mode = kNsVeryHighSuppression;
2464 break;
2465 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002466
kwiberg55b97fe2016-01-28 05:22:45 -08002467 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002468}
2469
kwiberg55b97fe2016-01-28 05:22:45 -08002470#endif // #ifdef WEBRTC_VOICE_ENGINE_NR
niklase@google.com470e71d2011-07-07 08:21:25 +00002471
kwiberg55b97fe2016-01-28 05:22:45 -08002472int Channel::SetLocalSSRC(unsigned int ssrc) {
2473 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2474 "Channel::SetLocalSSRC()");
2475 if (channel_state_.Get().sending) {
2476 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2477 "SetLocalSSRC() already sending");
2478 return -1;
2479 }
2480 _rtpRtcpModule->SetSSRC(ssrc);
2481 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002482}
2483
kwiberg55b97fe2016-01-28 05:22:45 -08002484int Channel::GetLocalSSRC(unsigned int& ssrc) {
2485 ssrc = _rtpRtcpModule->SSRC();
2486 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002487}
2488
kwiberg55b97fe2016-01-28 05:22:45 -08002489int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2490 ssrc = rtp_receiver_->SSRC();
2491 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002492}
2493
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002494int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002495 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002496 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002497}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002498
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002499int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2500 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002501 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2502 if (enable &&
2503 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2504 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002505 return -1;
2506 }
2507 return 0;
2508}
2509
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002510int Channel::SetSendAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2511 return SetSendRtpHeaderExtension(enable, kRtpExtensionAbsoluteSendTime, id);
2512}
2513
2514int Channel::SetReceiveAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2515 rtp_header_parser_->DeregisterRtpHeaderExtension(
2516 kRtpExtensionAbsoluteSendTime);
kwiberg55b97fe2016-01-28 05:22:45 -08002517 if (enable &&
2518 !rtp_header_parser_->RegisterRtpHeaderExtension(
2519 kRtpExtensionAbsoluteSendTime, id)) {
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00002520 return -1;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002521 }
2522 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002523}
2524
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002525void Channel::EnableSendTransportSequenceNumber(int id) {
2526 int ret =
2527 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2528 RTC_DCHECK_EQ(0, ret);
2529}
2530
stefan3313ec92016-01-21 06:32:43 -08002531void Channel::EnableReceiveTransportSequenceNumber(int id) {
2532 rtp_header_parser_->DeregisterRtpHeaderExtension(
2533 kRtpExtensionTransportSequenceNumber);
2534 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2535 kRtpExtensionTransportSequenceNumber, id);
2536 RTC_DCHECK(ret);
2537}
2538
stefanbba9dec2016-02-01 04:39:55 -08002539void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002540 RtpPacketSender* rtp_packet_sender,
2541 TransportFeedbackObserver* transport_feedback_observer,
2542 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002543 RTC_DCHECK(rtp_packet_sender);
2544 RTC_DCHECK(transport_feedback_observer);
2545 RTC_DCHECK(packet_router && !packet_router_);
2546 feedback_observer_proxy_->SetTransportFeedbackObserver(
2547 transport_feedback_observer);
2548 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2549 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2550 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002551 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002552 packet_router_ = packet_router;
2553}
2554
stefanbba9dec2016-02-01 04:39:55 -08002555void Channel::RegisterReceiverCongestionControlObjects(
2556 PacketRouter* packet_router) {
2557 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002558 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002559 packet_router_ = packet_router;
2560}
2561
2562void Channel::ResetCongestionControlObjects() {
2563 RTC_DCHECK(packet_router_);
2564 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2565 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2566 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002567 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002568 packet_router_ = nullptr;
2569 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2570}
2571
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002572void Channel::SetRTCPStatus(bool enable) {
2573 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2574 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002575 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002576}
2577
kwiberg55b97fe2016-01-28 05:22:45 -08002578int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002579 RtcpMode method = _rtpRtcpModule->RTCP();
2580 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002581 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002582}
2583
kwiberg55b97fe2016-01-28 05:22:45 -08002584int Channel::SetRTCP_CNAME(const char cName[256]) {
2585 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2586 "Channel::SetRTCP_CNAME()");
2587 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2588 _engineStatisticsPtr->SetLastError(
2589 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2590 "SetRTCP_CNAME() failed to set RTCP CNAME");
2591 return -1;
2592 }
2593 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002594}
2595
kwiberg55b97fe2016-01-28 05:22:45 -08002596int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2597 if (cName == NULL) {
2598 _engineStatisticsPtr->SetLastError(
2599 VE_INVALID_ARGUMENT, kTraceError,
2600 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2601 return -1;
2602 }
2603 char cname[RTCP_CNAME_SIZE];
2604 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2605 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2606 _engineStatisticsPtr->SetLastError(
2607 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2608 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2609 return -1;
2610 }
2611 strcpy(cName, cname);
2612 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002613}
2614
kwiberg55b97fe2016-01-28 05:22:45 -08002615int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2616 unsigned int& NTPLow,
2617 unsigned int& timestamp,
2618 unsigned int& playoutTimestamp,
2619 unsigned int* jitter,
2620 unsigned short* fractionLost) {
2621 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002622
kwiberg55b97fe2016-01-28 05:22:45 -08002623 RTCPSenderInfo senderInfo;
2624 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2625 _engineStatisticsPtr->SetLastError(
2626 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2627 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2628 "side");
2629 return -1;
2630 }
2631
2632 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2633 // and octet count)
2634 NTPHigh = senderInfo.NTPseconds;
2635 NTPLow = senderInfo.NTPfraction;
2636 timestamp = senderInfo.RTPtimeStamp;
2637
2638 // --- Locally derived information
2639
2640 // This value is updated on each incoming RTCP packet (0 when no packet
2641 // has been received)
2642 playoutTimestamp = playout_timestamp_rtcp_;
2643
2644 if (NULL != jitter || NULL != fractionLost) {
2645 // Get all RTCP receiver report blocks that have been received on this
2646 // channel. If we receive RTP packets from a remote source we know the
2647 // remote SSRC and use the report block from him.
2648 // Otherwise use the first report block.
2649 std::vector<RTCPReportBlock> remote_stats;
2650 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2651 remote_stats.empty()) {
2652 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2653 "GetRemoteRTCPData() failed to measure statistics due"
2654 " to lack of received RTP and/or RTCP packets");
2655 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002656 }
2657
kwiberg55b97fe2016-01-28 05:22:45 -08002658 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2659 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2660 for (; it != remote_stats.end(); ++it) {
2661 if (it->remoteSSRC == remoteSSRC)
2662 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002663 }
kwiberg55b97fe2016-01-28 05:22:45 -08002664
2665 if (it == remote_stats.end()) {
2666 // If we have not received any RTCP packets from this SSRC it probably
2667 // means that we have not received any RTP packets.
2668 // Use the first received report block instead.
2669 it = remote_stats.begin();
2670 remoteSSRC = it->remoteSSRC;
2671 }
2672
2673 if (jitter) {
2674 *jitter = it->jitter;
2675 }
2676
2677 if (fractionLost) {
2678 *fractionLost = it->fractionLost;
2679 }
2680 }
2681 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002682}
2683
kwiberg55b97fe2016-01-28 05:22:45 -08002684int Channel::SendApplicationDefinedRTCPPacket(
2685 unsigned char subType,
2686 unsigned int name,
2687 const char* data,
2688 unsigned short dataLengthInBytes) {
2689 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2690 "Channel::SendApplicationDefinedRTCPPacket()");
2691 if (!channel_state_.Get().sending) {
2692 _engineStatisticsPtr->SetLastError(
2693 VE_NOT_SENDING, kTraceError,
2694 "SendApplicationDefinedRTCPPacket() not sending");
2695 return -1;
2696 }
2697 if (NULL == data) {
2698 _engineStatisticsPtr->SetLastError(
2699 VE_INVALID_ARGUMENT, kTraceError,
2700 "SendApplicationDefinedRTCPPacket() invalid data value");
2701 return -1;
2702 }
2703 if (dataLengthInBytes % 4 != 0) {
2704 _engineStatisticsPtr->SetLastError(
2705 VE_INVALID_ARGUMENT, kTraceError,
2706 "SendApplicationDefinedRTCPPacket() invalid length value");
2707 return -1;
2708 }
2709 RtcpMode status = _rtpRtcpModule->RTCP();
2710 if (status == RtcpMode::kOff) {
2711 _engineStatisticsPtr->SetLastError(
2712 VE_RTCP_ERROR, kTraceError,
2713 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2714 return -1;
2715 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002716
kwiberg55b97fe2016-01-28 05:22:45 -08002717 // Create and schedule the RTCP APP packet for transmission
2718 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2719 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2720 _engineStatisticsPtr->SetLastError(
2721 VE_SEND_ERROR, kTraceError,
2722 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2723 return -1;
2724 }
2725 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002726}
2727
kwiberg55b97fe2016-01-28 05:22:45 -08002728int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2729 unsigned int& maxJitterMs,
2730 unsigned int& discardedPackets) {
2731 // The jitter statistics is updated for each received RTP packet and is
2732 // based on received packets.
2733 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2734 // If RTCP is off, there is no timed thread in the RTCP module regularly
2735 // generating new stats, trigger the update manually here instead.
2736 StreamStatistician* statistician =
2737 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2738 if (statistician) {
2739 // Don't use returned statistics, use data from proxy instead so that
2740 // max jitter can be fetched atomically.
2741 RtcpStatistics s;
2742 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002743 }
kwiberg55b97fe2016-01-28 05:22:45 -08002744 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002745
kwiberg55b97fe2016-01-28 05:22:45 -08002746 ChannelStatistics stats = statistics_proxy_->GetStats();
2747 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2748 if (playoutFrequency > 0) {
2749 // Scale RTP statistics given the current playout frequency
2750 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2751 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2752 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002753
kwiberg55b97fe2016-01-28 05:22:45 -08002754 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002755
kwiberg55b97fe2016-01-28 05:22:45 -08002756 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002757}
2758
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002759int Channel::GetRemoteRTCPReportBlocks(
2760 std::vector<ReportBlock>* report_blocks) {
2761 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002762 _engineStatisticsPtr->SetLastError(
2763 VE_INVALID_ARGUMENT, kTraceError,
2764 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002765 return -1;
2766 }
2767
2768 // Get the report blocks from the latest received RTCP Sender or Receiver
2769 // Report. Each element in the vector contains the sender's SSRC and a
2770 // report block according to RFC 3550.
2771 std::vector<RTCPReportBlock> rtcp_report_blocks;
2772 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002773 return -1;
2774 }
2775
2776 if (rtcp_report_blocks.empty())
2777 return 0;
2778
2779 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2780 for (; it != rtcp_report_blocks.end(); ++it) {
2781 ReportBlock report_block;
2782 report_block.sender_SSRC = it->remoteSSRC;
2783 report_block.source_SSRC = it->sourceSSRC;
2784 report_block.fraction_lost = it->fractionLost;
2785 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2786 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2787 report_block.interarrival_jitter = it->jitter;
2788 report_block.last_SR_timestamp = it->lastSR;
2789 report_block.delay_since_last_SR = it->delaySinceLastSR;
2790 report_blocks->push_back(report_block);
2791 }
2792 return 0;
2793}
2794
kwiberg55b97fe2016-01-28 05:22:45 -08002795int Channel::GetRTPStatistics(CallStatistics& stats) {
2796 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002797
kwiberg55b97fe2016-01-28 05:22:45 -08002798 // The jitter statistics is updated for each received RTP packet and is
2799 // based on received packets.
2800 RtcpStatistics statistics;
2801 StreamStatistician* statistician =
2802 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002803 if (statistician) {
2804 statistician->GetStatistics(&statistics,
2805 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002806 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002807
kwiberg55b97fe2016-01-28 05:22:45 -08002808 stats.fractionLost = statistics.fraction_lost;
2809 stats.cumulativeLost = statistics.cumulative_lost;
2810 stats.extendedMax = statistics.extended_max_sequence_number;
2811 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002812
kwiberg55b97fe2016-01-28 05:22:45 -08002813 // --- RTT
2814 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002815
kwiberg55b97fe2016-01-28 05:22:45 -08002816 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002817
kwiberg55b97fe2016-01-28 05:22:45 -08002818 size_t bytesSent(0);
2819 uint32_t packetsSent(0);
2820 size_t bytesReceived(0);
2821 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002822
kwiberg55b97fe2016-01-28 05:22:45 -08002823 if (statistician) {
2824 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2825 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002826
kwiberg55b97fe2016-01-28 05:22:45 -08002827 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2828 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2829 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2830 " output will not be complete");
2831 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002832
kwiberg55b97fe2016-01-28 05:22:45 -08002833 stats.bytesSent = bytesSent;
2834 stats.packetsSent = packetsSent;
2835 stats.bytesReceived = bytesReceived;
2836 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002837
kwiberg55b97fe2016-01-28 05:22:45 -08002838 // --- Timestamps
2839 {
2840 rtc::CritScope lock(&ts_stats_lock_);
2841 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2842 }
2843 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002844}
2845
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002846int Channel::SetREDStatus(bool enable, int redPayloadtype) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002847 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002848 "Channel::SetREDStatus()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002849
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002850 if (enable) {
2851 if (redPayloadtype < 0 || redPayloadtype > 127) {
2852 _engineStatisticsPtr->SetLastError(
2853 VE_PLTYPE_ERROR, kTraceError,
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002854 "SetREDStatus() invalid RED payload type");
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002855 return -1;
2856 }
2857
2858 if (SetRedPayloadType(redPayloadtype) < 0) {
2859 _engineStatisticsPtr->SetLastError(
2860 VE_CODEC_ERROR, kTraceError,
2861 "SetSecondarySendCodec() Failed to register RED ACM");
2862 return -1;
2863 }
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002864 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002865
kwibergc8d071e2016-04-06 12:22:38 -07002866 if (!codec_manager_.SetCopyRed(enable) ||
2867 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002868 _engineStatisticsPtr->SetLastError(
2869 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgaa5ea1c2014-05-23 15:16:51 +00002870 "SetREDStatus() failed to set RED state in the ACM");
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002871 return -1;
2872 }
2873 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002874}
2875
kwiberg55b97fe2016-01-28 05:22:45 -08002876int Channel::GetREDStatus(bool& enabled, int& redPayloadtype) {
kwibergc8d071e2016-04-06 12:22:38 -07002877 enabled = codec_manager_.GetStackParams()->use_red;
kwiberg55b97fe2016-01-28 05:22:45 -08002878 if (enabled) {
2879 int8_t payloadType = 0;
2880 if (_rtpRtcpModule->SendREDPayloadType(&payloadType) != 0) {
2881 _engineStatisticsPtr->SetLastError(
2882 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2883 "GetREDStatus() failed to retrieve RED PT from RTP/RTCP "
2884 "module");
2885 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002886 }
kwiberg55b97fe2016-01-28 05:22:45 -08002887 redPayloadtype = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +00002888 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002889 }
2890 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002891}
2892
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002893int Channel::SetCodecFECStatus(bool enable) {
2894 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2895 "Channel::SetCodecFECStatus()");
2896
kwibergc8d071e2016-04-06 12:22:38 -07002897 if (!codec_manager_.SetCodecFEC(enable) ||
2898 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002899 _engineStatisticsPtr->SetLastError(
2900 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2901 "SetCodecFECStatus() failed to set FEC state");
2902 return -1;
2903 }
2904 return 0;
2905}
2906
2907bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002908 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002909}
2910
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002911void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2912 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002913 // If pacing is enabled we always store packets.
2914 if (!pacing_enabled_)
2915 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002916 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
2917 rtp_receiver_->SetNACKStatus(enable ? kNackRtcp : kNackOff);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002918 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002919 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002920 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002921 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002922}
2923
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002924// Called when we are missing one or more packets.
2925int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002926 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2927}
2928
kwiberg55b97fe2016-01-28 05:22:45 -08002929uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2930 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2931 "Channel::Demultiplex()");
2932 _audioFrame.CopyFrom(audioFrame);
2933 _audioFrame.id_ = _channelId;
2934 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002935}
2936
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002937void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002938 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002939 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002940 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002941 CodecInst codec;
2942 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002943
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002944 // Never upsample or upmix the capture signal here. This should be done at the
2945 // end of the send chain.
2946 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2947 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2948 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2949 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002950}
2951
kwiberg55b97fe2016-01-28 05:22:45 -08002952uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2953 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2954 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002955
kwiberg55b97fe2016-01-28 05:22:45 -08002956 if (_audioFrame.samples_per_channel_ == 0) {
2957 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2958 "Channel::PrepareEncodeAndSend() invalid audio frame");
2959 return 0xFFFFFFFF;
2960 }
2961
2962 if (channel_state_.Get().input_file_playing) {
2963 MixOrReplaceAudioWithFile(mixingFrequency);
2964 }
2965
solenberg1c2af8e2016-03-24 10:36:00 -07002966 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2967 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002968
2969 if (channel_state_.Get().input_external_media) {
2970 rtc::CritScope cs(&_callbackCritSect);
2971 const bool isStereo = (_audioFrame.num_channels_ == 2);
2972 if (_inputExternalMediaCallbackPtr) {
2973 _inputExternalMediaCallbackPtr->Process(
2974 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2975 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2976 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002977 }
kwiberg55b97fe2016-01-28 05:22:45 -08002978 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002979
kwiberg55b97fe2016-01-28 05:22:45 -08002980 if (_includeAudioLevelIndication) {
2981 size_t length =
2982 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
solenberg1c2af8e2016-03-24 10:36:00 -07002983 if (is_muted && previous_frame_muted_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002984 rms_level_.ProcessMuted(length);
2985 } else {
2986 rms_level_.Process(_audioFrame.data_, length);
niklase@google.com470e71d2011-07-07 08:21:25 +00002987 }
kwiberg55b97fe2016-01-28 05:22:45 -08002988 }
solenberg1c2af8e2016-03-24 10:36:00 -07002989 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002990
kwiberg55b97fe2016-01-28 05:22:45 -08002991 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002992}
2993
kwiberg55b97fe2016-01-28 05:22:45 -08002994uint32_t Channel::EncodeAndSend() {
2995 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2996 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002997
kwiberg55b97fe2016-01-28 05:22:45 -08002998 assert(_audioFrame.num_channels_ <= 2);
2999 if (_audioFrame.samples_per_channel_ == 0) {
3000 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3001 "Channel::EncodeAndSend() invalid audio frame");
3002 return 0xFFFFFFFF;
3003 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003004
kwiberg55b97fe2016-01-28 05:22:45 -08003005 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00003006
kwiberg55b97fe2016-01-28 05:22:45 -08003007 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00003008
kwiberg55b97fe2016-01-28 05:22:45 -08003009 // The ACM resamples internally.
3010 _audioFrame.timestamp_ = _timeStamp;
3011 // This call will trigger AudioPacketizationCallback::SendData if encoding
3012 // is done and payload is ready for packetization and transmission.
3013 // Otherwise, it will return without invoking the callback.
3014 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
3015 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
3016 "Channel::EncodeAndSend() ACM encoding failed");
3017 return 0xFFFFFFFF;
3018 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003019
kwiberg55b97fe2016-01-28 05:22:45 -08003020 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
3021 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003022}
3023
Minyue2013aec2015-05-13 14:14:42 +02003024void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08003025 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003026 Channel* channel = associate_send_channel_.channel();
3027 if (channel && channel->ChannelId() == channel_id) {
3028 // If this channel is associated with a send channel of the specified
3029 // Channel ID, disassociate with it.
3030 ChannelOwner ref(NULL);
3031 associate_send_channel_ = ref;
3032 }
3033}
3034
kwiberg55b97fe2016-01-28 05:22:45 -08003035int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
3036 VoEMediaProcess& processObject) {
3037 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3038 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003039
kwiberg55b97fe2016-01-28 05:22:45 -08003040 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003041
kwiberg55b97fe2016-01-28 05:22:45 -08003042 if (kPlaybackPerChannel == type) {
3043 if (_outputExternalMediaCallbackPtr) {
3044 _engineStatisticsPtr->SetLastError(
3045 VE_INVALID_OPERATION, kTraceError,
3046 "Channel::RegisterExternalMediaProcessing() "
3047 "output external media already enabled");
3048 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003049 }
kwiberg55b97fe2016-01-28 05:22:45 -08003050 _outputExternalMediaCallbackPtr = &processObject;
3051 _outputExternalMedia = true;
3052 } else if (kRecordingPerChannel == type) {
3053 if (_inputExternalMediaCallbackPtr) {
3054 _engineStatisticsPtr->SetLastError(
3055 VE_INVALID_OPERATION, kTraceError,
3056 "Channel::RegisterExternalMediaProcessing() "
3057 "output external media already enabled");
3058 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003059 }
kwiberg55b97fe2016-01-28 05:22:45 -08003060 _inputExternalMediaCallbackPtr = &processObject;
3061 channel_state_.SetInputExternalMedia(true);
3062 }
3063 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003064}
3065
kwiberg55b97fe2016-01-28 05:22:45 -08003066int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
3067 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3068 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003069
kwiberg55b97fe2016-01-28 05:22:45 -08003070 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003071
kwiberg55b97fe2016-01-28 05:22:45 -08003072 if (kPlaybackPerChannel == type) {
3073 if (!_outputExternalMediaCallbackPtr) {
3074 _engineStatisticsPtr->SetLastError(
3075 VE_INVALID_OPERATION, kTraceWarning,
3076 "Channel::DeRegisterExternalMediaProcessing() "
3077 "output external media already disabled");
3078 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003079 }
kwiberg55b97fe2016-01-28 05:22:45 -08003080 _outputExternalMedia = false;
3081 _outputExternalMediaCallbackPtr = NULL;
3082 } else if (kRecordingPerChannel == type) {
3083 if (!_inputExternalMediaCallbackPtr) {
3084 _engineStatisticsPtr->SetLastError(
3085 VE_INVALID_OPERATION, kTraceWarning,
3086 "Channel::DeRegisterExternalMediaProcessing() "
3087 "input external media already disabled");
3088 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003089 }
kwiberg55b97fe2016-01-28 05:22:45 -08003090 channel_state_.SetInputExternalMedia(false);
3091 _inputExternalMediaCallbackPtr = NULL;
3092 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003093
kwiberg55b97fe2016-01-28 05:22:45 -08003094 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003095}
3096
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003097int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08003098 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3099 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003100
kwiberg55b97fe2016-01-28 05:22:45 -08003101 if (channel_state_.Get().playing) {
3102 _engineStatisticsPtr->SetLastError(
3103 VE_INVALID_OPERATION, kTraceError,
3104 "Channel::SetExternalMixing() "
3105 "external mixing cannot be changed while playing.");
3106 return -1;
3107 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003108
kwiberg55b97fe2016-01-28 05:22:45 -08003109 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003110
kwiberg55b97fe2016-01-28 05:22:45 -08003111 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003112}
3113
kwiberg55b97fe2016-01-28 05:22:45 -08003114int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3115 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003116}
3117
wu@webrtc.org24301a62013-12-13 19:17:43 +00003118void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3119 audio_coding_->GetDecodingCallStatistics(stats);
3120}
3121
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003122bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3123 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003124 rtc::CritScope lock(&video_sync_lock_);
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003125 if (_average_jitter_buffer_delay_us == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003126 return false;
3127 }
kwiberg55b97fe2016-01-28 05:22:45 -08003128 *jitter_buffer_delay_ms =
3129 (_average_jitter_buffer_delay_us + 500) / 1000 + _recPacketDelayMs;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003130 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003131 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003132}
3133
solenberg358057b2015-11-27 10:46:42 -08003134uint32_t Channel::GetDelayEstimate() const {
3135 int jitter_buffer_delay_ms = 0;
3136 int playout_buffer_delay_ms = 0;
3137 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3138 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3139}
3140
deadbeef74375882015-08-13 12:09:10 -07003141int Channel::LeastRequiredDelayMs() const {
3142 return audio_coding_->LeastRequiredDelayMs();
3143}
3144
kwiberg55b97fe2016-01-28 05:22:45 -08003145int Channel::SetMinimumPlayoutDelay(int delayMs) {
3146 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3147 "Channel::SetMinimumPlayoutDelay()");
3148 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3149 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3150 _engineStatisticsPtr->SetLastError(
3151 VE_INVALID_ARGUMENT, kTraceError,
3152 "SetMinimumPlayoutDelay() invalid min delay");
3153 return -1;
3154 }
3155 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3156 _engineStatisticsPtr->SetLastError(
3157 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3158 "SetMinimumPlayoutDelay() failed to set min playout delay");
3159 return -1;
3160 }
3161 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003162}
3163
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003164int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003165 uint32_t playout_timestamp_rtp = 0;
3166 {
tommi31fc21f2016-01-21 10:37:37 -08003167 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003168 playout_timestamp_rtp = playout_timestamp_rtp_;
3169 }
kwiberg55b97fe2016-01-28 05:22:45 -08003170 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003171 _engineStatisticsPtr->SetLastError(
3172 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3173 "GetPlayoutTimestamp() failed to retrieve timestamp");
3174 return -1;
3175 }
deadbeef74375882015-08-13 12:09:10 -07003176 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003177 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003178}
3179
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003180int Channel::SetInitTimestamp(unsigned int timestamp) {
3181 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003182 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003183 if (channel_state_.Get().sending) {
3184 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3185 "SetInitTimestamp() already sending");
3186 return -1;
3187 }
3188 _rtpRtcpModule->SetStartTimestamp(timestamp);
3189 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003190}
3191
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003192int Channel::SetInitSequenceNumber(short sequenceNumber) {
3193 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3194 "Channel::SetInitSequenceNumber()");
3195 if (channel_state_.Get().sending) {
3196 _engineStatisticsPtr->SetLastError(
3197 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3198 return -1;
3199 }
3200 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3201 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003202}
3203
kwiberg55b97fe2016-01-28 05:22:45 -08003204int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3205 RtpReceiver** rtp_receiver) const {
3206 *rtpRtcpModule = _rtpRtcpModule.get();
3207 *rtp_receiver = rtp_receiver_.get();
3208 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003209}
3210
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003211// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3212// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003213int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003214 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003215 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003216
kwiberg55b97fe2016-01-28 05:22:45 -08003217 {
3218 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003219
kwiberg55b97fe2016-01-28 05:22:45 -08003220 if (_inputFilePlayerPtr == NULL) {
3221 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3222 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3223 " doesnt exist");
3224 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003225 }
3226
kwiberg55b97fe2016-01-28 05:22:45 -08003227 if (_inputFilePlayerPtr->Get10msAudioFromFile(fileBuffer.get(), fileSamples,
3228 mixingFrequency) == -1) {
3229 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3230 "Channel::MixOrReplaceAudioWithFile() file mixing "
3231 "failed");
3232 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003233 }
kwiberg55b97fe2016-01-28 05:22:45 -08003234 if (fileSamples == 0) {
3235 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3236 "Channel::MixOrReplaceAudioWithFile() file is ended");
3237 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003238 }
kwiberg55b97fe2016-01-28 05:22:45 -08003239 }
3240
3241 assert(_audioFrame.samples_per_channel_ == fileSamples);
3242
3243 if (_mixFileWithMicrophone) {
3244 // Currently file stream is always mono.
3245 // TODO(xians): Change the code when FilePlayer supports real stereo.
3246 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3247 1, fileSamples);
3248 } else {
3249 // Replace ACM audio with file.
3250 // Currently file stream is always mono.
3251 // TODO(xians): Change the code when FilePlayer supports real stereo.
3252 _audioFrame.UpdateFrame(
3253 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3254 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3255 }
3256 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003257}
3258
kwiberg55b97fe2016-01-28 05:22:45 -08003259int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3260 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003261
kwibergb7f89d62016-02-17 10:04:18 -08003262 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003263 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003264
kwiberg55b97fe2016-01-28 05:22:45 -08003265 {
3266 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003267
kwiberg55b97fe2016-01-28 05:22:45 -08003268 if (_outputFilePlayerPtr == NULL) {
3269 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3270 "Channel::MixAudioWithFile() file mixing failed");
3271 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003272 }
3273
kwiberg55b97fe2016-01-28 05:22:45 -08003274 // We should get the frequency we ask for.
3275 if (_outputFilePlayerPtr->Get10msAudioFromFile(
3276 fileBuffer.get(), fileSamples, mixingFrequency) == -1) {
3277 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3278 "Channel::MixAudioWithFile() file mixing failed");
3279 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003280 }
kwiberg55b97fe2016-01-28 05:22:45 -08003281 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003282
kwiberg55b97fe2016-01-28 05:22:45 -08003283 if (audioFrame.samples_per_channel_ == fileSamples) {
3284 // Currently file stream is always mono.
3285 // TODO(xians): Change the code when FilePlayer supports real stereo.
3286 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3287 fileSamples);
3288 } else {
3289 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3290 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3291 ") != "
3292 "fileSamples(%" PRIuS ")",
3293 audioFrame.samples_per_channel_, fileSamples);
3294 return -1;
3295 }
3296
3297 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003298}
3299
deadbeef74375882015-08-13 12:09:10 -07003300void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003301 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003302
henrik.lundin96bd5022016-04-06 04:13:56 -07003303 if (!jitter_buffer_playout_timestamp_) {
3304 // This can happen if this channel has not received any RTP packets. In
3305 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003306 return;
3307 }
3308
3309 uint16_t delay_ms = 0;
3310 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003311 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003312 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3313 " delay from the ADM");
3314 _engineStatisticsPtr->SetLastError(
3315 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3316 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3317 return;
3318 }
3319
henrik.lundin96bd5022016-04-06 04:13:56 -07003320 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3321 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003322
3323 // Remove the playout delay.
henrik.lundin96bd5022016-04-06 04:13:56 -07003324 playout_timestamp -= (delay_ms * (GetPlayoutFrequency() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003325
kwiberg55b97fe2016-01-28 05:22:45 -08003326 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003327 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003328 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003329
3330 {
tommi31fc21f2016-01-21 10:37:37 -08003331 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003332 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003333 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003334 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003335 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003336 }
3337 playout_delay_ms_ = delay_ms;
3338 }
3339}
3340
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003341// Called for incoming RTP packets after successful RTP header parsing.
3342void Channel::UpdatePacketDelay(uint32_t rtp_timestamp,
3343 uint16_t sequence_number) {
kwiberg55b97fe2016-01-28 05:22:45 -08003344 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003345 "Channel::UpdatePacketDelay(timestamp=%lu, sequenceNumber=%u)",
3346 rtp_timestamp, sequence_number);
niklase@google.com470e71d2011-07-07 08:21:25 +00003347
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003348 // Get frequency of last received payload
wu@webrtc.org94454b72014-06-05 20:34:08 +00003349 int rtp_receive_frequency = GetPlayoutFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +00003350
turaj@webrtc.org167b6df2013-12-13 21:05:07 +00003351 // |jitter_buffer_playout_timestamp_| updated in UpdatePlayoutTimestamp for
henrik.lundin96bd5022016-04-06 04:13:56 -07003352 // every incoming packet. May be empty if no valid playout timestamp is
3353 // available.
3354 // If |rtp_timestamp| is newer than |jitter_buffer_playout_timestamp_|, the
3355 // resulting difference is positive and will be used. When the inverse is
3356 // true (can happen when a network glitch causes a packet to arrive late,
3357 // and during long comfort noise periods with clock drift), or when
3358 // |jitter_buffer_playout_timestamp_| has no value, the difference is not
3359 // changed from the initial 0.
3360 uint32_t timestamp_diff_ms = 0;
3361 if (jitter_buffer_playout_timestamp_ &&
3362 IsNewerTimestamp(rtp_timestamp, *jitter_buffer_playout_timestamp_)) {
3363 timestamp_diff_ms = (rtp_timestamp - *jitter_buffer_playout_timestamp_) /
3364 (rtp_receive_frequency / 1000);
3365 if (timestamp_diff_ms > (2 * kVoiceEngineMaxMinPlayoutDelayMs)) {
3366 // Diff is too large; set it to zero instead.
3367 timestamp_diff_ms = 0;
3368 }
henrik.lundin@webrtc.orgd6692992014-03-20 12:04:09 +00003369 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003370
kwiberg55b97fe2016-01-28 05:22:45 -08003371 uint16_t packet_delay_ms =
3372 (rtp_timestamp - _previousTimestamp) / (rtp_receive_frequency / 1000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003373
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003374 _previousTimestamp = rtp_timestamp;
niklase@google.com470e71d2011-07-07 08:21:25 +00003375
kwiberg55b97fe2016-01-28 05:22:45 -08003376 if (timestamp_diff_ms == 0)
3377 return;
niklase@google.com470e71d2011-07-07 08:21:25 +00003378
deadbeef74375882015-08-13 12:09:10 -07003379 {
tommi31fc21f2016-01-21 10:37:37 -08003380 rtc::CritScope lock(&video_sync_lock_);
niklase@google.com470e71d2011-07-07 08:21:25 +00003381
deadbeef74375882015-08-13 12:09:10 -07003382 if (packet_delay_ms >= 10 && packet_delay_ms <= 60) {
3383 _recPacketDelayMs = packet_delay_ms;
3384 }
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003385
deadbeef74375882015-08-13 12:09:10 -07003386 if (_average_jitter_buffer_delay_us == 0) {
3387 _average_jitter_buffer_delay_us = timestamp_diff_ms * 1000;
3388 return;
3389 }
3390
3391 // Filter average delay value using exponential filter (alpha is
3392 // 7/8). We derive 1000 *_average_jitter_buffer_delay_us here (reduces
3393 // risk of rounding error) and compensate for it in GetDelayEstimate()
3394 // later.
kwiberg55b97fe2016-01-28 05:22:45 -08003395 _average_jitter_buffer_delay_us =
3396 (_average_jitter_buffer_delay_us * 7 + 1000 * timestamp_diff_ms + 500) /
3397 8;
deadbeef74375882015-08-13 12:09:10 -07003398 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003399}
3400
kwiberg55b97fe2016-01-28 05:22:45 -08003401void Channel::RegisterReceiveCodecsToRTPModule() {
3402 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3403 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003404
kwiberg55b97fe2016-01-28 05:22:45 -08003405 CodecInst codec;
3406 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003407
kwiberg55b97fe2016-01-28 05:22:45 -08003408 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3409 // Open up the RTP/RTCP receiver for all supported codecs
3410 if ((audio_coding_->Codec(idx, &codec) == -1) ||
3411 (rtp_receiver_->RegisterReceivePayload(
3412 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3413 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
3414 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3415 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3416 " to register %s (%d/%d/%" PRIuS
3417 "/%d) to RTP/RTCP "
3418 "receiver",
3419 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3420 codec.rate);
3421 } else {
3422 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3423 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3424 "(%d/%d/%" PRIuS
3425 "/%d) has been added to the RTP/RTCP "
3426 "receiver",
3427 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3428 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003429 }
kwiberg55b97fe2016-01-28 05:22:45 -08003430 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003431}
3432
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00003433// Assuming this method is called with valid payload type.
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003434int Channel::SetRedPayloadType(int red_payload_type) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003435 CodecInst codec;
3436 bool found_red = false;
3437
3438 // Get default RED settings from the ACM database
3439 const int num_codecs = AudioCodingModule::NumberOfCodecs();
3440 for (int idx = 0; idx < num_codecs; idx++) {
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00003441 audio_coding_->Codec(idx, &codec);
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003442 if (!STR_CASE_CMP(codec.plname, "RED")) {
3443 found_red = true;
3444 break;
3445 }
3446 }
3447
3448 if (!found_red) {
3449 _engineStatisticsPtr->SetLastError(
3450 VE_CODEC_ERROR, kTraceError,
3451 "SetRedPayloadType() RED is not supported");
3452 return -1;
3453 }
3454
turaj@webrtc.org9d532fd2013-01-31 18:34:19 +00003455 codec.pltype = red_payload_type;
kwibergc8d071e2016-04-06 12:22:38 -07003456 if (!codec_manager_.RegisterEncoder(codec) ||
3457 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003458 _engineStatisticsPtr->SetLastError(
3459 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3460 "SetRedPayloadType() RED registration in ACM module failed");
3461 return -1;
3462 }
3463
3464 if (_rtpRtcpModule->SetSendREDPayloadType(red_payload_type) != 0) {
3465 _engineStatisticsPtr->SetLastError(
3466 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
3467 "SetRedPayloadType() RED registration in RTP/RTCP module failed");
3468 return -1;
3469 }
3470 return 0;
3471}
3472
kwiberg55b97fe2016-01-28 05:22:45 -08003473int Channel::SetSendRtpHeaderExtension(bool enable,
3474 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003475 unsigned char id) {
3476 int error = 0;
3477 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3478 if (enable) {
3479 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3480 }
3481 return error;
3482}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003483
wu@webrtc.org94454b72014-06-05 20:34:08 +00003484int32_t Channel::GetPlayoutFrequency() {
3485 int32_t playout_frequency = audio_coding_->PlayoutFrequency();
3486 CodecInst current_recive_codec;
3487 if (audio_coding_->ReceiveCodec(&current_recive_codec) == 0) {
3488 if (STR_CASE_CMP("G722", current_recive_codec.plname) == 0) {
3489 // Even though the actual sampling rate for G.722 audio is
3490 // 16,000 Hz, the RTP clock rate for the G722 payload format is
3491 // 8,000 Hz because that value was erroneously assigned in
3492 // RFC 1890 and must remain unchanged for backward compatibility.
3493 playout_frequency = 8000;
3494 } else if (STR_CASE_CMP("opus", current_recive_codec.plname) == 0) {
3495 // We are resampling Opus internally to 32,000 Hz until all our
3496 // DSP routines can operate at 48,000 Hz, but the RTP clock
3497 // rate for the Opus payload format is standardized to 48,000 Hz,
3498 // because that is the maximum supported decoding sampling rate.
3499 playout_frequency = 48000;
3500 }
3501 }
3502 return playout_frequency;
3503}
3504
Minyue2013aec2015-05-13 14:14:42 +02003505int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003506 RtcpMode method = _rtpRtcpModule->RTCP();
3507 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003508 return 0;
3509 }
3510 std::vector<RTCPReportBlock> report_blocks;
3511 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003512
3513 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003514 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003515 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003516 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003517 Channel* channel = associate_send_channel_.channel();
3518 // Tries to get RTT from an associated channel. This is important for
3519 // receive-only channels.
3520 if (channel) {
3521 // To prevent infinite recursion and deadlock, calling GetRTT of
3522 // associate channel should always use "false" for argument:
3523 // |allow_associate_channel|.
3524 rtt = channel->GetRTT(false);
3525 }
3526 }
3527 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003528 }
3529
3530 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3531 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3532 for (; it != report_blocks.end(); ++it) {
3533 if (it->remoteSSRC == remoteSSRC)
3534 break;
3535 }
3536 if (it == report_blocks.end()) {
3537 // We have not received packets with SSRC matching the report blocks.
3538 // To calculate RTT we try with the SSRC of the first report block.
3539 // This is very important for send-only channels where we don't know
3540 // the SSRC of the other end.
3541 remoteSSRC = report_blocks[0].remoteSSRC;
3542 }
Minyue2013aec2015-05-13 14:14:42 +02003543
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003544 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003545 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003546 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003547 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3548 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003549 return 0;
3550 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003551 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003552}
3553
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003554} // namespace voe
3555} // namespace webrtc