blob: b9adde7e3ec14b25098d468f124b4df08bc5be45 [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
kwiberg55b97fe2016-01-28 05:22:45 -08001452int32_t Channel::RegisterExternalTransport(Transport& transport) {
1453 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);
niklase@google.com470e71d2011-07-07 08:21:25 +00001457
kwiberg55b97fe2016-01-28 05:22:45 -08001458 if (_externalTransport) {
1459 _engineStatisticsPtr->SetLastError(
1460 VE_INVALID_OPERATION, kTraceError,
1461 "RegisterExternalTransport() external transport already enabled");
1462 return -1;
1463 }
1464 _externalTransport = true;
1465 _transportPtr = &transport;
1466 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001467}
1468
kwiberg55b97fe2016-01-28 05:22:45 -08001469int32_t Channel::DeRegisterExternalTransport() {
1470 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1471 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001472
kwiberg55b97fe2016-01-28 05:22:45 -08001473 rtc::CritScope cs(&_callbackCritSect);
xians@webrtc.org83661f52011-11-25 10:58:15 +00001474
kwiberg55b97fe2016-01-28 05:22:45 -08001475 if (!_transportPtr) {
1476 _engineStatisticsPtr->SetLastError(
1477 VE_INVALID_OPERATION, kTraceWarning,
1478 "DeRegisterExternalTransport() external transport already "
1479 "disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00001480 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001481 }
1482 _externalTransport = false;
1483 _transportPtr = NULL;
1484 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1485 "DeRegisterExternalTransport() all transport is disabled");
1486 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001487}
1488
kwiberg55b97fe2016-01-28 05:22:45 -08001489int32_t Channel::ReceivedRTPPacket(const int8_t* data,
1490 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001491 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001492 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001493 "Channel::ReceivedRTPPacket()");
1494
1495 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001496 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001497
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001498 const uint8_t* received_packet = reinterpret_cast<const uint8_t*>(data);
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001499 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001500 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1501 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1502 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001503 return -1;
1504 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001505 header.payload_type_frequency =
1506 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001507 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001508 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001509 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001510 rtp_receive_statistics_->IncomingPacket(
1511 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001512 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001513
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001514 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001515}
1516
1517bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001518 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001519 const RTPHeader& header,
1520 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001521 if (rtp_payload_registry_->IsRtx(header)) {
1522 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001523 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001524 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001525 assert(packet_length >= header.headerLength);
1526 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001527 PayloadUnion payload_specific;
1528 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001529 &payload_specific)) {
1530 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001531 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001532 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1533 payload_specific, in_order);
1534}
1535
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001536bool Channel::HandleRtxPacket(const uint8_t* packet,
1537 size_t packet_length,
1538 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001539 if (!rtp_payload_registry_->IsRtx(header))
1540 return false;
1541
1542 // Remove the RTX header and parse the original RTP header.
1543 if (packet_length < header.headerLength)
1544 return false;
1545 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1546 return false;
1547 if (restored_packet_in_use_) {
1548 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1549 "Multiple RTX headers detected, dropping packet");
1550 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001551 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001552 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001553 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1554 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001555 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1556 "Incoming RTX packet: invalid RTP header");
1557 return false;
1558 }
1559 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001560 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001561 restored_packet_in_use_ = false;
1562 return ret;
1563}
1564
1565bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1566 StreamStatistician* statistician =
1567 rtp_receive_statistics_->GetStatistician(header.ssrc);
1568 if (!statistician)
1569 return false;
1570 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001571}
1572
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001573bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1574 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001575 // Retransmissions are handled separately if RTX is enabled.
1576 if (rtp_payload_registry_->RtxEnabled())
1577 return false;
1578 StreamStatistician* statistician =
1579 rtp_receive_statistics_->GetStatistician(header.ssrc);
1580 if (!statistician)
1581 return false;
1582 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001583 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001584 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001585 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001586}
1587
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001588int32_t Channel::ReceivedRTCPPacket(const int8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001589 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001590 "Channel::ReceivedRTCPPacket()");
1591 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001592 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001593
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001594 // Deliver RTCP packet to RTP/RTCP module for parsing
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001595 if (_rtpRtcpModule->IncomingRtcpPacket((const uint8_t*)data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001596 _engineStatisticsPtr->SetLastError(
1597 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1598 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1599 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001600
Minyue2013aec2015-05-13 14:14:42 +02001601 int64_t rtt = GetRTT(true);
1602 if (rtt == 0) {
1603 // Waiting for valid RTT.
1604 return 0;
1605 }
1606 uint32_t ntp_secs = 0;
1607 uint32_t ntp_frac = 0;
1608 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001609 if (0 !=
1610 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1611 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001612 // Waiting for RTCP.
1613 return 0;
1614 }
1615
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001616 {
tommi31fc21f2016-01-21 10:37:37 -08001617 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001618 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001619 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001620 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001621}
1622
niklase@google.com470e71d2011-07-07 08:21:25 +00001623int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001624 bool loop,
1625 FileFormats format,
1626 int startPosition,
1627 float volumeScaling,
1628 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001629 const CodecInst* codecInst) {
1630 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1631 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1632 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1633 "stopPosition=%d)",
1634 fileName, loop, format, volumeScaling, startPosition,
1635 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001636
kwiberg55b97fe2016-01-28 05:22:45 -08001637 if (channel_state_.Get().output_file_playing) {
1638 _engineStatisticsPtr->SetLastError(
1639 VE_ALREADY_PLAYING, kTraceError,
1640 "StartPlayingFileLocally() is already playing");
1641 return -1;
1642 }
1643
1644 {
1645 rtc::CritScope cs(&_fileCritSect);
1646
1647 if (_outputFilePlayerPtr) {
1648 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1649 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1650 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001651 }
1652
kwiberg55b97fe2016-01-28 05:22:45 -08001653 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1654 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001655
kwiberg55b97fe2016-01-28 05:22:45 -08001656 if (_outputFilePlayerPtr == NULL) {
1657 _engineStatisticsPtr->SetLastError(
1658 VE_INVALID_ARGUMENT, kTraceError,
1659 "StartPlayingFileLocally() filePlayer format is not correct");
1660 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001661 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001662
kwiberg55b97fe2016-01-28 05:22:45 -08001663 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001664
kwiberg55b97fe2016-01-28 05:22:45 -08001665 if (_outputFilePlayerPtr->StartPlayingFile(
1666 fileName, loop, startPosition, volumeScaling, notificationTime,
1667 stopPosition, (const CodecInst*)codecInst) != 0) {
1668 _engineStatisticsPtr->SetLastError(
1669 VE_BAD_FILE, kTraceError,
1670 "StartPlayingFile() failed to start file playout");
1671 _outputFilePlayerPtr->StopPlayingFile();
1672 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1673 _outputFilePlayerPtr = NULL;
1674 return -1;
1675 }
1676 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1677 channel_state_.SetOutputFilePlaying(true);
1678 }
1679
1680 if (RegisterFilePlayingToMixer() != 0)
1681 return -1;
1682
1683 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001684}
1685
1686int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001687 FileFormats format,
1688 int startPosition,
1689 float volumeScaling,
1690 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001691 const CodecInst* codecInst) {
1692 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1693 "Channel::StartPlayingFileLocally(format=%d,"
1694 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1695 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001696
kwiberg55b97fe2016-01-28 05:22:45 -08001697 if (stream == NULL) {
1698 _engineStatisticsPtr->SetLastError(
1699 VE_BAD_FILE, kTraceError,
1700 "StartPlayingFileLocally() NULL as input stream");
1701 return -1;
1702 }
1703
1704 if (channel_state_.Get().output_file_playing) {
1705 _engineStatisticsPtr->SetLastError(
1706 VE_ALREADY_PLAYING, kTraceError,
1707 "StartPlayingFileLocally() is already playing");
1708 return -1;
1709 }
1710
1711 {
1712 rtc::CritScope cs(&_fileCritSect);
1713
1714 // Destroy the old instance
1715 if (_outputFilePlayerPtr) {
1716 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1717 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1718 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001719 }
1720
kwiberg55b97fe2016-01-28 05:22:45 -08001721 // Create the instance
1722 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1723 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001724
kwiberg55b97fe2016-01-28 05:22:45 -08001725 if (_outputFilePlayerPtr == NULL) {
1726 _engineStatisticsPtr->SetLastError(
1727 VE_INVALID_ARGUMENT, kTraceError,
1728 "StartPlayingFileLocally() filePlayer format isnot correct");
1729 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001730 }
1731
kwiberg55b97fe2016-01-28 05:22:45 -08001732 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001733
kwiberg55b97fe2016-01-28 05:22:45 -08001734 if (_outputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1735 volumeScaling, notificationTime,
1736 stopPosition, codecInst) != 0) {
1737 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1738 "StartPlayingFile() failed to "
1739 "start file playout");
1740 _outputFilePlayerPtr->StopPlayingFile();
1741 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1742 _outputFilePlayerPtr = NULL;
1743 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001744 }
kwiberg55b97fe2016-01-28 05:22:45 -08001745 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1746 channel_state_.SetOutputFilePlaying(true);
1747 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001748
kwiberg55b97fe2016-01-28 05:22:45 -08001749 if (RegisterFilePlayingToMixer() != 0)
1750 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001751
kwiberg55b97fe2016-01-28 05:22:45 -08001752 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001753}
1754
kwiberg55b97fe2016-01-28 05:22:45 -08001755int Channel::StopPlayingFileLocally() {
1756 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1757 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001758
kwiberg55b97fe2016-01-28 05:22:45 -08001759 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001760 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001761 }
1762
1763 {
1764 rtc::CritScope cs(&_fileCritSect);
1765
1766 if (_outputFilePlayerPtr->StopPlayingFile() != 0) {
1767 _engineStatisticsPtr->SetLastError(
1768 VE_STOP_RECORDING_FAILED, kTraceError,
1769 "StopPlayingFile() could not stop playing");
1770 return -1;
1771 }
1772 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1773 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1774 _outputFilePlayerPtr = NULL;
1775 channel_state_.SetOutputFilePlaying(false);
1776 }
1777 // _fileCritSect cannot be taken while calling
1778 // SetAnonymousMixibilityStatus. Refer to comments in
1779 // StartPlayingFileLocally(const char* ...) for more details.
1780 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1781 _engineStatisticsPtr->SetLastError(
1782 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1783 "StopPlayingFile() failed to stop participant from playing as"
1784 "file in the mixer");
1785 return -1;
1786 }
1787
1788 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001789}
1790
kwiberg55b97fe2016-01-28 05:22:45 -08001791int Channel::IsPlayingFileLocally() const {
1792 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001793}
1794
kwiberg55b97fe2016-01-28 05:22:45 -08001795int Channel::RegisterFilePlayingToMixer() {
1796 // Return success for not registering for file playing to mixer if:
1797 // 1. playing file before playout is started on that channel.
1798 // 2. starting playout without file playing on that channel.
1799 if (!channel_state_.Get().playing ||
1800 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001801 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001802 }
1803
1804 // |_fileCritSect| cannot be taken while calling
1805 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1806 // frames can be pulled by the mixer. Since the frames are generated from
1807 // the file, _fileCritSect will be taken. This would result in a deadlock.
1808 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1809 channel_state_.SetOutputFilePlaying(false);
1810 rtc::CritScope cs(&_fileCritSect);
1811 _engineStatisticsPtr->SetLastError(
1812 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1813 "StartPlayingFile() failed to add participant as file to mixer");
1814 _outputFilePlayerPtr->StopPlayingFile();
1815 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1816 _outputFilePlayerPtr = NULL;
1817 return -1;
1818 }
1819
1820 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001821}
1822
niklase@google.com470e71d2011-07-07 08:21:25 +00001823int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001824 bool loop,
1825 FileFormats format,
1826 int startPosition,
1827 float volumeScaling,
1828 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001829 const CodecInst* codecInst) {
1830 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1831 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1832 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1833 "stopPosition=%d)",
1834 fileName, loop, format, volumeScaling, startPosition,
1835 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001836
kwiberg55b97fe2016-01-28 05:22:45 -08001837 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001838
kwiberg55b97fe2016-01-28 05:22:45 -08001839 if (channel_state_.Get().input_file_playing) {
1840 _engineStatisticsPtr->SetLastError(
1841 VE_ALREADY_PLAYING, kTraceWarning,
1842 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001843 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001844 }
1845
1846 // Destroy the old instance
1847 if (_inputFilePlayerPtr) {
1848 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1849 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1850 _inputFilePlayerPtr = NULL;
1851 }
1852
1853 // Create the instance
1854 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1855 (const FileFormats)format);
1856
1857 if (_inputFilePlayerPtr == NULL) {
1858 _engineStatisticsPtr->SetLastError(
1859 VE_INVALID_ARGUMENT, kTraceError,
1860 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1861 return -1;
1862 }
1863
1864 const uint32_t notificationTime(0);
1865
1866 if (_inputFilePlayerPtr->StartPlayingFile(
1867 fileName, loop, startPosition, volumeScaling, notificationTime,
1868 stopPosition, (const CodecInst*)codecInst) != 0) {
1869 _engineStatisticsPtr->SetLastError(
1870 VE_BAD_FILE, kTraceError,
1871 "StartPlayingFile() failed to start file playout");
1872 _inputFilePlayerPtr->StopPlayingFile();
1873 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1874 _inputFilePlayerPtr = NULL;
1875 return -1;
1876 }
1877 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1878 channel_state_.SetInputFilePlaying(true);
1879
1880 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001881}
1882
1883int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001884 FileFormats format,
1885 int startPosition,
1886 float volumeScaling,
1887 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001888 const CodecInst* codecInst) {
1889 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1890 "Channel::StartPlayingFileAsMicrophone(format=%d, "
1891 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1892 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001893
kwiberg55b97fe2016-01-28 05:22:45 -08001894 if (stream == NULL) {
1895 _engineStatisticsPtr->SetLastError(
1896 VE_BAD_FILE, kTraceError,
1897 "StartPlayingFileAsMicrophone NULL as input stream");
1898 return -1;
1899 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001900
kwiberg55b97fe2016-01-28 05:22:45 -08001901 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001902
kwiberg55b97fe2016-01-28 05:22:45 -08001903 if (channel_state_.Get().input_file_playing) {
1904 _engineStatisticsPtr->SetLastError(
1905 VE_ALREADY_PLAYING, kTraceWarning,
1906 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001907 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001908 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001909
kwiberg55b97fe2016-01-28 05:22:45 -08001910 // Destroy the old instance
1911 if (_inputFilePlayerPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001912 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1913 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1914 _inputFilePlayerPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001915 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001916
kwiberg55b97fe2016-01-28 05:22:45 -08001917 // Create the instance
1918 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1919 (const FileFormats)format);
1920
1921 if (_inputFilePlayerPtr == NULL) {
1922 _engineStatisticsPtr->SetLastError(
1923 VE_INVALID_ARGUMENT, kTraceError,
1924 "StartPlayingInputFile() filePlayer format isnot correct");
1925 return -1;
1926 }
1927
1928 const uint32_t notificationTime(0);
1929
1930 if (_inputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1931 volumeScaling, notificationTime,
1932 stopPosition, codecInst) != 0) {
1933 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1934 "StartPlayingFile() failed to start "
1935 "file playout");
1936 _inputFilePlayerPtr->StopPlayingFile();
1937 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1938 _inputFilePlayerPtr = NULL;
1939 return -1;
1940 }
1941
1942 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1943 channel_state_.SetInputFilePlaying(true);
1944
1945 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001946}
1947
kwiberg55b97fe2016-01-28 05:22:45 -08001948int Channel::StopPlayingFileAsMicrophone() {
1949 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1950 "Channel::StopPlayingFileAsMicrophone()");
1951
1952 rtc::CritScope cs(&_fileCritSect);
1953
1954 if (!channel_state_.Get().input_file_playing) {
1955 return 0;
1956 }
1957
1958 if (_inputFilePlayerPtr->StopPlayingFile() != 0) {
1959 _engineStatisticsPtr->SetLastError(
1960 VE_STOP_RECORDING_FAILED, kTraceError,
1961 "StopPlayingFile() could not stop playing");
1962 return -1;
1963 }
1964 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1965 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1966 _inputFilePlayerPtr = NULL;
1967 channel_state_.SetInputFilePlaying(false);
1968
1969 return 0;
1970}
1971
1972int Channel::IsPlayingFileAsMicrophone() const {
1973 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001974}
1975
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00001976int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08001977 const CodecInst* codecInst) {
1978 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1979 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00001980
kwiberg55b97fe2016-01-28 05:22:45 -08001981 if (_outputFileRecording) {
1982 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
1983 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00001984 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001985 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001986
kwiberg55b97fe2016-01-28 05:22:45 -08001987 FileFormats format;
1988 const uint32_t notificationTime(0); // Not supported in VoE
1989 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00001990
kwiberg55b97fe2016-01-28 05:22:45 -08001991 if ((codecInst != NULL) &&
1992 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
1993 _engineStatisticsPtr->SetLastError(
1994 VE_BAD_ARGUMENT, kTraceError,
1995 "StartRecordingPlayout() invalid compression");
1996 return (-1);
1997 }
1998 if (codecInst == NULL) {
1999 format = kFileFormatPcm16kHzFile;
2000 codecInst = &dummyCodec;
2001 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2002 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2003 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2004 format = kFileFormatWavFile;
2005 } else {
2006 format = kFileFormatCompressedFile;
2007 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002008
kwiberg55b97fe2016-01-28 05:22:45 -08002009 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002010
kwiberg55b97fe2016-01-28 05:22:45 -08002011 // Destroy the old instance
2012 if (_outputFileRecorderPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002013 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2014 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2015 _outputFileRecorderPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08002016 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002017
kwiberg55b97fe2016-01-28 05:22:45 -08002018 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2019 _outputFileRecorderId, (const FileFormats)format);
2020 if (_outputFileRecorderPtr == NULL) {
2021 _engineStatisticsPtr->SetLastError(
2022 VE_INVALID_ARGUMENT, kTraceError,
2023 "StartRecordingPlayout() fileRecorder format isnot correct");
2024 return -1;
2025 }
2026
2027 if (_outputFileRecorderPtr->StartRecordingAudioFile(
2028 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2029 _engineStatisticsPtr->SetLastError(
2030 VE_BAD_FILE, kTraceError,
2031 "StartRecordingAudioFile() failed to start file recording");
2032 _outputFileRecorderPtr->StopRecording();
2033 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2034 _outputFileRecorderPtr = NULL;
2035 return -1;
2036 }
2037 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2038 _outputFileRecording = true;
2039
2040 return 0;
2041}
2042
2043int Channel::StartRecordingPlayout(OutStream* stream,
2044 const CodecInst* codecInst) {
2045 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2046 "Channel::StartRecordingPlayout()");
2047
2048 if (_outputFileRecording) {
2049 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2050 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002051 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002052 }
2053
2054 FileFormats format;
2055 const uint32_t notificationTime(0); // Not supported in VoE
2056 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2057
2058 if (codecInst != NULL && codecInst->channels != 1) {
2059 _engineStatisticsPtr->SetLastError(
2060 VE_BAD_ARGUMENT, kTraceError,
2061 "StartRecordingPlayout() invalid compression");
2062 return (-1);
2063 }
2064 if (codecInst == NULL) {
2065 format = kFileFormatPcm16kHzFile;
2066 codecInst = &dummyCodec;
2067 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2068 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2069 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2070 format = kFileFormatWavFile;
2071 } else {
2072 format = kFileFormatCompressedFile;
2073 }
2074
2075 rtc::CritScope cs(&_fileCritSect);
2076
2077 // Destroy the old instance
2078 if (_outputFileRecorderPtr) {
2079 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2080 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2081 _outputFileRecorderPtr = NULL;
2082 }
2083
2084 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2085 _outputFileRecorderId, (const FileFormats)format);
2086 if (_outputFileRecorderPtr == NULL) {
2087 _engineStatisticsPtr->SetLastError(
2088 VE_INVALID_ARGUMENT, kTraceError,
2089 "StartRecordingPlayout() fileRecorder format isnot correct");
2090 return -1;
2091 }
2092
2093 if (_outputFileRecorderPtr->StartRecordingAudioFile(*stream, *codecInst,
2094 notificationTime) != 0) {
2095 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2096 "StartRecordingPlayout() failed to "
2097 "start file recording");
2098 _outputFileRecorderPtr->StopRecording();
2099 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2100 _outputFileRecorderPtr = NULL;
2101 return -1;
2102 }
2103
2104 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2105 _outputFileRecording = true;
2106
2107 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002108}
2109
kwiberg55b97fe2016-01-28 05:22:45 -08002110int Channel::StopRecordingPlayout() {
2111 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2112 "Channel::StopRecordingPlayout()");
2113
2114 if (!_outputFileRecording) {
2115 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2116 "StopRecordingPlayout() isnot recording");
2117 return -1;
2118 }
2119
2120 rtc::CritScope cs(&_fileCritSect);
2121
2122 if (_outputFileRecorderPtr->StopRecording() != 0) {
2123 _engineStatisticsPtr->SetLastError(
2124 VE_STOP_RECORDING_FAILED, kTraceError,
2125 "StopRecording() could not stop recording");
2126 return (-1);
2127 }
2128 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2129 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2130 _outputFileRecorderPtr = NULL;
2131 _outputFileRecording = false;
2132
2133 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002134}
2135
kwiberg55b97fe2016-01-28 05:22:45 -08002136void Channel::SetMixWithMicStatus(bool mix) {
2137 rtc::CritScope cs(&_fileCritSect);
2138 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002139}
2140
kwiberg55b97fe2016-01-28 05:22:45 -08002141int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2142 int8_t currentLevel = _outputAudioLevel.Level();
2143 level = static_cast<int32_t>(currentLevel);
2144 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002145}
2146
kwiberg55b97fe2016-01-28 05:22:45 -08002147int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2148 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2149 level = static_cast<int32_t>(currentLevel);
2150 return 0;
2151}
2152
solenberg1c2af8e2016-03-24 10:36:00 -07002153int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002154 rtc::CritScope cs(&volume_settings_critsect_);
2155 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002156 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002157 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002158 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002159}
2160
solenberg1c2af8e2016-03-24 10:36:00 -07002161bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002162 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002163 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002164}
2165
kwiberg55b97fe2016-01-28 05:22:45 -08002166int Channel::SetOutputVolumePan(float left, float right) {
2167 rtc::CritScope cs(&volume_settings_critsect_);
2168 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002169 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002170 _panLeft = left;
2171 _panRight = right;
2172 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002173}
2174
kwiberg55b97fe2016-01-28 05:22:45 -08002175int Channel::GetOutputVolumePan(float& left, float& right) const {
2176 rtc::CritScope cs(&volume_settings_critsect_);
2177 left = _panLeft;
2178 right = _panRight;
2179 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002180}
2181
kwiberg55b97fe2016-01-28 05:22:45 -08002182int Channel::SetChannelOutputVolumeScaling(float scaling) {
2183 rtc::CritScope cs(&volume_settings_critsect_);
2184 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002185 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002186 _outputGain = scaling;
2187 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002188}
2189
kwiberg55b97fe2016-01-28 05:22:45 -08002190int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2191 rtc::CritScope cs(&volume_settings_critsect_);
2192 scaling = _outputGain;
2193 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002194}
2195
solenberg8842c3e2016-03-11 03:06:41 -08002196int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002197 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002198 "Channel::SendTelephoneEventOutband(...)");
2199 RTC_DCHECK_LE(0, event);
2200 RTC_DCHECK_GE(255, event);
2201 RTC_DCHECK_LE(0, duration_ms);
2202 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002203 if (!Sending()) {
2204 return -1;
2205 }
solenberg8842c3e2016-03-11 03:06:41 -08002206 if (_rtpRtcpModule->SendTelephoneEventOutband(
2207 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002208 _engineStatisticsPtr->SetLastError(
2209 VE_SEND_DTMF_FAILED, kTraceWarning,
2210 "SendTelephoneEventOutband() failed to send event");
2211 return -1;
2212 }
2213 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002214}
2215
solenberg31642aa2016-03-14 08:00:37 -07002216int Channel::SetSendTelephoneEventPayloadType(int payload_type) {
kwiberg55b97fe2016-01-28 05:22:45 -08002217 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002218 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002219 RTC_DCHECK_LE(0, payload_type);
2220 RTC_DCHECK_GE(127, payload_type);
2221 CodecInst codec = {0};
kwiberg55b97fe2016-01-28 05:22:45 -08002222 codec.plfreq = 8000;
solenberg31642aa2016-03-14 08:00:37 -07002223 codec.pltype = payload_type;
kwiberg55b97fe2016-01-28 05:22:45 -08002224 memcpy(codec.plname, "telephone-event", 16);
2225 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2226 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2227 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2228 _engineStatisticsPtr->SetLastError(
2229 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2230 "SetSendTelephoneEventPayloadType() failed to register send"
2231 "payload type");
2232 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002233 }
kwiberg55b97fe2016-01-28 05:22:45 -08002234 }
kwiberg55b97fe2016-01-28 05:22:45 -08002235 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002236}
2237
kwiberg55b97fe2016-01-28 05:22:45 -08002238int Channel::UpdateRxVadDetection(AudioFrame& audioFrame) {
2239 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2240 "Channel::UpdateRxVadDetection()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002241
kwiberg55b97fe2016-01-28 05:22:45 -08002242 int vadDecision = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002243
kwiberg55b97fe2016-01-28 05:22:45 -08002244 vadDecision = (audioFrame.vad_activity_ == AudioFrame::kVadActive) ? 1 : 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002245
kwiberg55b97fe2016-01-28 05:22:45 -08002246 if ((vadDecision != _oldVadDecision) && _rxVadObserverPtr) {
2247 OnRxVadDetected(vadDecision);
2248 _oldVadDecision = vadDecision;
2249 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002250
kwiberg55b97fe2016-01-28 05:22:45 -08002251 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2252 "Channel::UpdateRxVadDetection() => vadDecision=%d",
2253 vadDecision);
2254 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002255}
2256
kwiberg55b97fe2016-01-28 05:22:45 -08002257int Channel::RegisterRxVadObserver(VoERxVadCallback& observer) {
2258 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2259 "Channel::RegisterRxVadObserver()");
2260 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002261
kwiberg55b97fe2016-01-28 05:22:45 -08002262 if (_rxVadObserverPtr) {
2263 _engineStatisticsPtr->SetLastError(
2264 VE_INVALID_OPERATION, kTraceError,
2265 "RegisterRxVadObserver() observer already enabled");
2266 return -1;
2267 }
2268 _rxVadObserverPtr = &observer;
2269 _RxVadDetection = true;
2270 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002271}
2272
kwiberg55b97fe2016-01-28 05:22:45 -08002273int Channel::DeRegisterRxVadObserver() {
2274 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2275 "Channel::DeRegisterRxVadObserver()");
2276 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002277
kwiberg55b97fe2016-01-28 05:22:45 -08002278 if (!_rxVadObserverPtr) {
2279 _engineStatisticsPtr->SetLastError(
2280 VE_INVALID_OPERATION, kTraceWarning,
2281 "DeRegisterRxVadObserver() observer already disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00002282 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002283 }
2284 _rxVadObserverPtr = NULL;
2285 _RxVadDetection = false;
2286 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002287}
2288
kwiberg55b97fe2016-01-28 05:22:45 -08002289int Channel::VoiceActivityIndicator(int& activity) {
2290 activity = _sendFrameType;
2291 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002292}
2293
2294#ifdef WEBRTC_VOICE_ENGINE_AGC
2295
kwiberg55b97fe2016-01-28 05:22:45 -08002296int Channel::SetRxAgcStatus(bool enable, AgcModes mode) {
2297 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2298 "Channel::SetRxAgcStatus(enable=%d, mode=%d)", (int)enable,
2299 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002300
kwiberg55b97fe2016-01-28 05:22:45 -08002301 GainControl::Mode agcMode = kDefaultRxAgcMode;
2302 switch (mode) {
2303 case kAgcDefault:
2304 break;
2305 case kAgcUnchanged:
2306 agcMode = rx_audioproc_->gain_control()->mode();
2307 break;
2308 case kAgcFixedDigital:
2309 agcMode = GainControl::kFixedDigital;
2310 break;
2311 case kAgcAdaptiveDigital:
2312 agcMode = GainControl::kAdaptiveDigital;
2313 break;
2314 default:
2315 _engineStatisticsPtr->SetLastError(VE_INVALID_ARGUMENT, kTraceError,
2316 "SetRxAgcStatus() invalid Agc mode");
2317 return -1;
2318 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002319
kwiberg55b97fe2016-01-28 05:22:45 -08002320 if (rx_audioproc_->gain_control()->set_mode(agcMode) != 0) {
2321 _engineStatisticsPtr->SetLastError(
2322 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc mode");
2323 return -1;
2324 }
2325 if (rx_audioproc_->gain_control()->Enable(enable) != 0) {
2326 _engineStatisticsPtr->SetLastError(
2327 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc state");
2328 return -1;
2329 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002330
kwiberg55b97fe2016-01-28 05:22:45 -08002331 _rxAgcIsEnabled = enable;
2332 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002333
kwiberg55b97fe2016-01-28 05:22:45 -08002334 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002335}
2336
kwiberg55b97fe2016-01-28 05:22:45 -08002337int Channel::GetRxAgcStatus(bool& enabled, AgcModes& mode) {
2338 bool enable = rx_audioproc_->gain_control()->is_enabled();
2339 GainControl::Mode agcMode = rx_audioproc_->gain_control()->mode();
niklase@google.com470e71d2011-07-07 08:21:25 +00002340
kwiberg55b97fe2016-01-28 05:22:45 -08002341 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002342
kwiberg55b97fe2016-01-28 05:22:45 -08002343 switch (agcMode) {
2344 case GainControl::kFixedDigital:
2345 mode = kAgcFixedDigital;
2346 break;
2347 case GainControl::kAdaptiveDigital:
2348 mode = kAgcAdaptiveDigital;
2349 break;
2350 default:
2351 _engineStatisticsPtr->SetLastError(VE_APM_ERROR, kTraceError,
2352 "GetRxAgcStatus() invalid Agc mode");
2353 return -1;
2354 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002355
kwiberg55b97fe2016-01-28 05:22:45 -08002356 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002357}
2358
kwiberg55b97fe2016-01-28 05:22:45 -08002359int Channel::SetRxAgcConfig(AgcConfig config) {
2360 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2361 "Channel::SetRxAgcConfig()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002362
kwiberg55b97fe2016-01-28 05:22:45 -08002363 if (rx_audioproc_->gain_control()->set_target_level_dbfs(
2364 config.targetLeveldBOv) != 0) {
2365 _engineStatisticsPtr->SetLastError(
2366 VE_APM_ERROR, kTraceError,
2367 "SetRxAgcConfig() failed to set target peak |level|"
2368 "(or envelope) of the Agc");
2369 return -1;
2370 }
2371 if (rx_audioproc_->gain_control()->set_compression_gain_db(
2372 config.digitalCompressionGaindB) != 0) {
2373 _engineStatisticsPtr->SetLastError(
2374 VE_APM_ERROR, kTraceError,
2375 "SetRxAgcConfig() failed to set the range in |gain| the"
2376 " digital compression stage may apply");
2377 return -1;
2378 }
2379 if (rx_audioproc_->gain_control()->enable_limiter(config.limiterEnable) !=
2380 0) {
2381 _engineStatisticsPtr->SetLastError(
2382 VE_APM_ERROR, kTraceError,
2383 "SetRxAgcConfig() failed to set hard limiter to the signal");
2384 return -1;
2385 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002386
kwiberg55b97fe2016-01-28 05:22:45 -08002387 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002388}
2389
kwiberg55b97fe2016-01-28 05:22:45 -08002390int Channel::GetRxAgcConfig(AgcConfig& config) {
2391 config.targetLeveldBOv = rx_audioproc_->gain_control()->target_level_dbfs();
2392 config.digitalCompressionGaindB =
2393 rx_audioproc_->gain_control()->compression_gain_db();
2394 config.limiterEnable = rx_audioproc_->gain_control()->is_limiter_enabled();
niklase@google.com470e71d2011-07-07 08:21:25 +00002395
kwiberg55b97fe2016-01-28 05:22:45 -08002396 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002397}
2398
kwiberg55b97fe2016-01-28 05:22:45 -08002399#endif // #ifdef WEBRTC_VOICE_ENGINE_AGC
niklase@google.com470e71d2011-07-07 08:21:25 +00002400
2401#ifdef WEBRTC_VOICE_ENGINE_NR
2402
kwiberg55b97fe2016-01-28 05:22:45 -08002403int Channel::SetRxNsStatus(bool enable, NsModes mode) {
2404 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2405 "Channel::SetRxNsStatus(enable=%d, mode=%d)", (int)enable,
2406 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002407
kwiberg55b97fe2016-01-28 05:22:45 -08002408 NoiseSuppression::Level nsLevel = kDefaultNsMode;
2409 switch (mode) {
2410 case kNsDefault:
2411 break;
2412 case kNsUnchanged:
2413 nsLevel = rx_audioproc_->noise_suppression()->level();
2414 break;
2415 case kNsConference:
2416 nsLevel = NoiseSuppression::kHigh;
2417 break;
2418 case kNsLowSuppression:
2419 nsLevel = NoiseSuppression::kLow;
2420 break;
2421 case kNsModerateSuppression:
2422 nsLevel = NoiseSuppression::kModerate;
2423 break;
2424 case kNsHighSuppression:
2425 nsLevel = NoiseSuppression::kHigh;
2426 break;
2427 case kNsVeryHighSuppression:
2428 nsLevel = NoiseSuppression::kVeryHigh;
2429 break;
2430 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002431
kwiberg55b97fe2016-01-28 05:22:45 -08002432 if (rx_audioproc_->noise_suppression()->set_level(nsLevel) != 0) {
2433 _engineStatisticsPtr->SetLastError(
2434 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS level");
2435 return -1;
2436 }
2437 if (rx_audioproc_->noise_suppression()->Enable(enable) != 0) {
2438 _engineStatisticsPtr->SetLastError(
2439 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS state");
2440 return -1;
2441 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002442
kwiberg55b97fe2016-01-28 05:22:45 -08002443 _rxNsIsEnabled = enable;
2444 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002445
kwiberg55b97fe2016-01-28 05:22:45 -08002446 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002447}
2448
kwiberg55b97fe2016-01-28 05:22:45 -08002449int Channel::GetRxNsStatus(bool& enabled, NsModes& mode) {
2450 bool enable = rx_audioproc_->noise_suppression()->is_enabled();
2451 NoiseSuppression::Level ncLevel = rx_audioproc_->noise_suppression()->level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002452
kwiberg55b97fe2016-01-28 05:22:45 -08002453 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002454
kwiberg55b97fe2016-01-28 05:22:45 -08002455 switch (ncLevel) {
2456 case NoiseSuppression::kLow:
2457 mode = kNsLowSuppression;
2458 break;
2459 case NoiseSuppression::kModerate:
2460 mode = kNsModerateSuppression;
2461 break;
2462 case NoiseSuppression::kHigh:
2463 mode = kNsHighSuppression;
2464 break;
2465 case NoiseSuppression::kVeryHigh:
2466 mode = kNsVeryHighSuppression;
2467 break;
2468 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002469
kwiberg55b97fe2016-01-28 05:22:45 -08002470 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002471}
2472
kwiberg55b97fe2016-01-28 05:22:45 -08002473#endif // #ifdef WEBRTC_VOICE_ENGINE_NR
niklase@google.com470e71d2011-07-07 08:21:25 +00002474
kwiberg55b97fe2016-01-28 05:22:45 -08002475int Channel::SetLocalSSRC(unsigned int ssrc) {
2476 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2477 "Channel::SetLocalSSRC()");
2478 if (channel_state_.Get().sending) {
2479 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2480 "SetLocalSSRC() already sending");
2481 return -1;
2482 }
2483 _rtpRtcpModule->SetSSRC(ssrc);
2484 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002485}
2486
kwiberg55b97fe2016-01-28 05:22:45 -08002487int Channel::GetLocalSSRC(unsigned int& ssrc) {
2488 ssrc = _rtpRtcpModule->SSRC();
2489 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002490}
2491
kwiberg55b97fe2016-01-28 05:22:45 -08002492int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2493 ssrc = rtp_receiver_->SSRC();
2494 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002495}
2496
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002497int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002498 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002499 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002500}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002501
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002502int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2503 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002504 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2505 if (enable &&
2506 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2507 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002508 return -1;
2509 }
2510 return 0;
2511}
2512
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002513int Channel::SetSendAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2514 return SetSendRtpHeaderExtension(enable, kRtpExtensionAbsoluteSendTime, id);
2515}
2516
2517int Channel::SetReceiveAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2518 rtp_header_parser_->DeregisterRtpHeaderExtension(
2519 kRtpExtensionAbsoluteSendTime);
kwiberg55b97fe2016-01-28 05:22:45 -08002520 if (enable &&
2521 !rtp_header_parser_->RegisterRtpHeaderExtension(
2522 kRtpExtensionAbsoluteSendTime, id)) {
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00002523 return -1;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002524 }
2525 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002526}
2527
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002528void Channel::EnableSendTransportSequenceNumber(int id) {
2529 int ret =
2530 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2531 RTC_DCHECK_EQ(0, ret);
2532}
2533
stefan3313ec92016-01-21 06:32:43 -08002534void Channel::EnableReceiveTransportSequenceNumber(int id) {
2535 rtp_header_parser_->DeregisterRtpHeaderExtension(
2536 kRtpExtensionTransportSequenceNumber);
2537 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2538 kRtpExtensionTransportSequenceNumber, id);
2539 RTC_DCHECK(ret);
2540}
2541
stefanbba9dec2016-02-01 04:39:55 -08002542void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002543 RtpPacketSender* rtp_packet_sender,
2544 TransportFeedbackObserver* transport_feedback_observer,
2545 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002546 RTC_DCHECK(rtp_packet_sender);
2547 RTC_DCHECK(transport_feedback_observer);
2548 RTC_DCHECK(packet_router && !packet_router_);
2549 feedback_observer_proxy_->SetTransportFeedbackObserver(
2550 transport_feedback_observer);
2551 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2552 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2553 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002554 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002555 packet_router_ = packet_router;
2556}
2557
stefanbba9dec2016-02-01 04:39:55 -08002558void Channel::RegisterReceiverCongestionControlObjects(
2559 PacketRouter* packet_router) {
2560 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002561 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002562 packet_router_ = packet_router;
2563}
2564
2565void Channel::ResetCongestionControlObjects() {
2566 RTC_DCHECK(packet_router_);
2567 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2568 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2569 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002570 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002571 packet_router_ = nullptr;
2572 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2573}
2574
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002575void Channel::SetRTCPStatus(bool enable) {
2576 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2577 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002578 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002579}
2580
kwiberg55b97fe2016-01-28 05:22:45 -08002581int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002582 RtcpMode method = _rtpRtcpModule->RTCP();
2583 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002584 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002585}
2586
kwiberg55b97fe2016-01-28 05:22:45 -08002587int Channel::SetRTCP_CNAME(const char cName[256]) {
2588 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2589 "Channel::SetRTCP_CNAME()");
2590 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2591 _engineStatisticsPtr->SetLastError(
2592 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2593 "SetRTCP_CNAME() failed to set RTCP CNAME");
2594 return -1;
2595 }
2596 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002597}
2598
kwiberg55b97fe2016-01-28 05:22:45 -08002599int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2600 if (cName == NULL) {
2601 _engineStatisticsPtr->SetLastError(
2602 VE_INVALID_ARGUMENT, kTraceError,
2603 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2604 return -1;
2605 }
2606 char cname[RTCP_CNAME_SIZE];
2607 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2608 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2609 _engineStatisticsPtr->SetLastError(
2610 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2611 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2612 return -1;
2613 }
2614 strcpy(cName, cname);
2615 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002616}
2617
kwiberg55b97fe2016-01-28 05:22:45 -08002618int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2619 unsigned int& NTPLow,
2620 unsigned int& timestamp,
2621 unsigned int& playoutTimestamp,
2622 unsigned int* jitter,
2623 unsigned short* fractionLost) {
2624 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002625
kwiberg55b97fe2016-01-28 05:22:45 -08002626 RTCPSenderInfo senderInfo;
2627 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2628 _engineStatisticsPtr->SetLastError(
2629 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2630 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2631 "side");
2632 return -1;
2633 }
2634
2635 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2636 // and octet count)
2637 NTPHigh = senderInfo.NTPseconds;
2638 NTPLow = senderInfo.NTPfraction;
2639 timestamp = senderInfo.RTPtimeStamp;
2640
2641 // --- Locally derived information
2642
2643 // This value is updated on each incoming RTCP packet (0 when no packet
2644 // has been received)
2645 playoutTimestamp = playout_timestamp_rtcp_;
2646
2647 if (NULL != jitter || NULL != fractionLost) {
2648 // Get all RTCP receiver report blocks that have been received on this
2649 // channel. If we receive RTP packets from a remote source we know the
2650 // remote SSRC and use the report block from him.
2651 // Otherwise use the first report block.
2652 std::vector<RTCPReportBlock> remote_stats;
2653 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2654 remote_stats.empty()) {
2655 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2656 "GetRemoteRTCPData() failed to measure statistics due"
2657 " to lack of received RTP and/or RTCP packets");
2658 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002659 }
2660
kwiberg55b97fe2016-01-28 05:22:45 -08002661 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2662 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2663 for (; it != remote_stats.end(); ++it) {
2664 if (it->remoteSSRC == remoteSSRC)
2665 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002666 }
kwiberg55b97fe2016-01-28 05:22:45 -08002667
2668 if (it == remote_stats.end()) {
2669 // If we have not received any RTCP packets from this SSRC it probably
2670 // means that we have not received any RTP packets.
2671 // Use the first received report block instead.
2672 it = remote_stats.begin();
2673 remoteSSRC = it->remoteSSRC;
2674 }
2675
2676 if (jitter) {
2677 *jitter = it->jitter;
2678 }
2679
2680 if (fractionLost) {
2681 *fractionLost = it->fractionLost;
2682 }
2683 }
2684 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002685}
2686
kwiberg55b97fe2016-01-28 05:22:45 -08002687int Channel::SendApplicationDefinedRTCPPacket(
2688 unsigned char subType,
2689 unsigned int name,
2690 const char* data,
2691 unsigned short dataLengthInBytes) {
2692 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2693 "Channel::SendApplicationDefinedRTCPPacket()");
2694 if (!channel_state_.Get().sending) {
2695 _engineStatisticsPtr->SetLastError(
2696 VE_NOT_SENDING, kTraceError,
2697 "SendApplicationDefinedRTCPPacket() not sending");
2698 return -1;
2699 }
2700 if (NULL == data) {
2701 _engineStatisticsPtr->SetLastError(
2702 VE_INVALID_ARGUMENT, kTraceError,
2703 "SendApplicationDefinedRTCPPacket() invalid data value");
2704 return -1;
2705 }
2706 if (dataLengthInBytes % 4 != 0) {
2707 _engineStatisticsPtr->SetLastError(
2708 VE_INVALID_ARGUMENT, kTraceError,
2709 "SendApplicationDefinedRTCPPacket() invalid length value");
2710 return -1;
2711 }
2712 RtcpMode status = _rtpRtcpModule->RTCP();
2713 if (status == RtcpMode::kOff) {
2714 _engineStatisticsPtr->SetLastError(
2715 VE_RTCP_ERROR, kTraceError,
2716 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2717 return -1;
2718 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002719
kwiberg55b97fe2016-01-28 05:22:45 -08002720 // Create and schedule the RTCP APP packet for transmission
2721 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2722 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2723 _engineStatisticsPtr->SetLastError(
2724 VE_SEND_ERROR, kTraceError,
2725 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2726 return -1;
2727 }
2728 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002729}
2730
kwiberg55b97fe2016-01-28 05:22:45 -08002731int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2732 unsigned int& maxJitterMs,
2733 unsigned int& discardedPackets) {
2734 // The jitter statistics is updated for each received RTP packet and is
2735 // based on received packets.
2736 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2737 // If RTCP is off, there is no timed thread in the RTCP module regularly
2738 // generating new stats, trigger the update manually here instead.
2739 StreamStatistician* statistician =
2740 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2741 if (statistician) {
2742 // Don't use returned statistics, use data from proxy instead so that
2743 // max jitter can be fetched atomically.
2744 RtcpStatistics s;
2745 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002746 }
kwiberg55b97fe2016-01-28 05:22:45 -08002747 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002748
kwiberg55b97fe2016-01-28 05:22:45 -08002749 ChannelStatistics stats = statistics_proxy_->GetStats();
2750 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2751 if (playoutFrequency > 0) {
2752 // Scale RTP statistics given the current playout frequency
2753 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2754 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2755 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002756
kwiberg55b97fe2016-01-28 05:22:45 -08002757 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002758
kwiberg55b97fe2016-01-28 05:22:45 -08002759 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002760}
2761
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002762int Channel::GetRemoteRTCPReportBlocks(
2763 std::vector<ReportBlock>* report_blocks) {
2764 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002765 _engineStatisticsPtr->SetLastError(
2766 VE_INVALID_ARGUMENT, kTraceError,
2767 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002768 return -1;
2769 }
2770
2771 // Get the report blocks from the latest received RTCP Sender or Receiver
2772 // Report. Each element in the vector contains the sender's SSRC and a
2773 // report block according to RFC 3550.
2774 std::vector<RTCPReportBlock> rtcp_report_blocks;
2775 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002776 return -1;
2777 }
2778
2779 if (rtcp_report_blocks.empty())
2780 return 0;
2781
2782 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2783 for (; it != rtcp_report_blocks.end(); ++it) {
2784 ReportBlock report_block;
2785 report_block.sender_SSRC = it->remoteSSRC;
2786 report_block.source_SSRC = it->sourceSSRC;
2787 report_block.fraction_lost = it->fractionLost;
2788 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2789 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2790 report_block.interarrival_jitter = it->jitter;
2791 report_block.last_SR_timestamp = it->lastSR;
2792 report_block.delay_since_last_SR = it->delaySinceLastSR;
2793 report_blocks->push_back(report_block);
2794 }
2795 return 0;
2796}
2797
kwiberg55b97fe2016-01-28 05:22:45 -08002798int Channel::GetRTPStatistics(CallStatistics& stats) {
2799 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002800
kwiberg55b97fe2016-01-28 05:22:45 -08002801 // The jitter statistics is updated for each received RTP packet and is
2802 // based on received packets.
2803 RtcpStatistics statistics;
2804 StreamStatistician* statistician =
2805 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002806 if (statistician) {
2807 statistician->GetStatistics(&statistics,
2808 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002809 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002810
kwiberg55b97fe2016-01-28 05:22:45 -08002811 stats.fractionLost = statistics.fraction_lost;
2812 stats.cumulativeLost = statistics.cumulative_lost;
2813 stats.extendedMax = statistics.extended_max_sequence_number;
2814 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002815
kwiberg55b97fe2016-01-28 05:22:45 -08002816 // --- RTT
2817 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002818
kwiberg55b97fe2016-01-28 05:22:45 -08002819 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002820
kwiberg55b97fe2016-01-28 05:22:45 -08002821 size_t bytesSent(0);
2822 uint32_t packetsSent(0);
2823 size_t bytesReceived(0);
2824 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002825
kwiberg55b97fe2016-01-28 05:22:45 -08002826 if (statistician) {
2827 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2828 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002829
kwiberg55b97fe2016-01-28 05:22:45 -08002830 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2831 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2832 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2833 " output will not be complete");
2834 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002835
kwiberg55b97fe2016-01-28 05:22:45 -08002836 stats.bytesSent = bytesSent;
2837 stats.packetsSent = packetsSent;
2838 stats.bytesReceived = bytesReceived;
2839 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002840
kwiberg55b97fe2016-01-28 05:22:45 -08002841 // --- Timestamps
2842 {
2843 rtc::CritScope lock(&ts_stats_lock_);
2844 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2845 }
2846 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002847}
2848
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002849int Channel::SetREDStatus(bool enable, int redPayloadtype) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002850 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002851 "Channel::SetREDStatus()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002852
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002853 if (enable) {
2854 if (redPayloadtype < 0 || redPayloadtype > 127) {
2855 _engineStatisticsPtr->SetLastError(
2856 VE_PLTYPE_ERROR, kTraceError,
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002857 "SetREDStatus() invalid RED payload type");
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002858 return -1;
2859 }
2860
2861 if (SetRedPayloadType(redPayloadtype) < 0) {
2862 _engineStatisticsPtr->SetLastError(
2863 VE_CODEC_ERROR, kTraceError,
2864 "SetSecondarySendCodec() Failed to register RED ACM");
2865 return -1;
2866 }
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002867 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002868
kwibergc8d071e2016-04-06 12:22:38 -07002869 if (!codec_manager_.SetCopyRed(enable) ||
2870 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002871 _engineStatisticsPtr->SetLastError(
2872 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgaa5ea1c2014-05-23 15:16:51 +00002873 "SetREDStatus() failed to set RED state in the ACM");
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002874 return -1;
2875 }
2876 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002877}
2878
kwiberg55b97fe2016-01-28 05:22:45 -08002879int Channel::GetREDStatus(bool& enabled, int& redPayloadtype) {
kwibergc8d071e2016-04-06 12:22:38 -07002880 enabled = codec_manager_.GetStackParams()->use_red;
kwiberg55b97fe2016-01-28 05:22:45 -08002881 if (enabled) {
2882 int8_t payloadType = 0;
2883 if (_rtpRtcpModule->SendREDPayloadType(&payloadType) != 0) {
2884 _engineStatisticsPtr->SetLastError(
2885 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2886 "GetREDStatus() failed to retrieve RED PT from RTP/RTCP "
2887 "module");
2888 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002889 }
kwiberg55b97fe2016-01-28 05:22:45 -08002890 redPayloadtype = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +00002891 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002892 }
2893 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002894}
2895
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002896int Channel::SetCodecFECStatus(bool enable) {
2897 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2898 "Channel::SetCodecFECStatus()");
2899
kwibergc8d071e2016-04-06 12:22:38 -07002900 if (!codec_manager_.SetCodecFEC(enable) ||
2901 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002902 _engineStatisticsPtr->SetLastError(
2903 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2904 "SetCodecFECStatus() failed to set FEC state");
2905 return -1;
2906 }
2907 return 0;
2908}
2909
2910bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002911 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002912}
2913
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002914void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2915 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002916 // If pacing is enabled we always store packets.
2917 if (!pacing_enabled_)
2918 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002919 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
2920 rtp_receiver_->SetNACKStatus(enable ? kNackRtcp : kNackOff);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002921 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002922 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002923 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002924 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002925}
2926
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002927// Called when we are missing one or more packets.
2928int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002929 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2930}
2931
kwiberg55b97fe2016-01-28 05:22:45 -08002932uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2933 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2934 "Channel::Demultiplex()");
2935 _audioFrame.CopyFrom(audioFrame);
2936 _audioFrame.id_ = _channelId;
2937 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002938}
2939
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002940void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002941 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002942 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002943 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002944 CodecInst codec;
2945 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002946
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002947 // Never upsample or upmix the capture signal here. This should be done at the
2948 // end of the send chain.
2949 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2950 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2951 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2952 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002953}
2954
kwiberg55b97fe2016-01-28 05:22:45 -08002955uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2956 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2957 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002958
kwiberg55b97fe2016-01-28 05:22:45 -08002959 if (_audioFrame.samples_per_channel_ == 0) {
2960 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2961 "Channel::PrepareEncodeAndSend() invalid audio frame");
2962 return 0xFFFFFFFF;
2963 }
2964
2965 if (channel_state_.Get().input_file_playing) {
2966 MixOrReplaceAudioWithFile(mixingFrequency);
2967 }
2968
solenberg1c2af8e2016-03-24 10:36:00 -07002969 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2970 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002971
2972 if (channel_state_.Get().input_external_media) {
2973 rtc::CritScope cs(&_callbackCritSect);
2974 const bool isStereo = (_audioFrame.num_channels_ == 2);
2975 if (_inputExternalMediaCallbackPtr) {
2976 _inputExternalMediaCallbackPtr->Process(
2977 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2978 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2979 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002980 }
kwiberg55b97fe2016-01-28 05:22:45 -08002981 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002982
kwiberg55b97fe2016-01-28 05:22:45 -08002983 if (_includeAudioLevelIndication) {
2984 size_t length =
2985 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
solenberg1c2af8e2016-03-24 10:36:00 -07002986 if (is_muted && previous_frame_muted_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002987 rms_level_.ProcessMuted(length);
2988 } else {
2989 rms_level_.Process(_audioFrame.data_, length);
niklase@google.com470e71d2011-07-07 08:21:25 +00002990 }
kwiberg55b97fe2016-01-28 05:22:45 -08002991 }
solenberg1c2af8e2016-03-24 10:36:00 -07002992 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002993
kwiberg55b97fe2016-01-28 05:22:45 -08002994 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002995}
2996
kwiberg55b97fe2016-01-28 05:22:45 -08002997uint32_t Channel::EncodeAndSend() {
2998 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2999 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003000
kwiberg55b97fe2016-01-28 05:22:45 -08003001 assert(_audioFrame.num_channels_ <= 2);
3002 if (_audioFrame.samples_per_channel_ == 0) {
3003 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3004 "Channel::EncodeAndSend() invalid audio frame");
3005 return 0xFFFFFFFF;
3006 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003007
kwiberg55b97fe2016-01-28 05:22:45 -08003008 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00003009
kwiberg55b97fe2016-01-28 05:22:45 -08003010 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00003011
kwiberg55b97fe2016-01-28 05:22:45 -08003012 // The ACM resamples internally.
3013 _audioFrame.timestamp_ = _timeStamp;
3014 // This call will trigger AudioPacketizationCallback::SendData if encoding
3015 // is done and payload is ready for packetization and transmission.
3016 // Otherwise, it will return without invoking the callback.
3017 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
3018 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
3019 "Channel::EncodeAndSend() ACM encoding failed");
3020 return 0xFFFFFFFF;
3021 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003022
kwiberg55b97fe2016-01-28 05:22:45 -08003023 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
3024 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003025}
3026
Minyue2013aec2015-05-13 14:14:42 +02003027void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08003028 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003029 Channel* channel = associate_send_channel_.channel();
3030 if (channel && channel->ChannelId() == channel_id) {
3031 // If this channel is associated with a send channel of the specified
3032 // Channel ID, disassociate with it.
3033 ChannelOwner ref(NULL);
3034 associate_send_channel_ = ref;
3035 }
3036}
3037
kwiberg55b97fe2016-01-28 05:22:45 -08003038int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
3039 VoEMediaProcess& processObject) {
3040 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3041 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003042
kwiberg55b97fe2016-01-28 05:22:45 -08003043 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003044
kwiberg55b97fe2016-01-28 05:22:45 -08003045 if (kPlaybackPerChannel == type) {
3046 if (_outputExternalMediaCallbackPtr) {
3047 _engineStatisticsPtr->SetLastError(
3048 VE_INVALID_OPERATION, kTraceError,
3049 "Channel::RegisterExternalMediaProcessing() "
3050 "output external media already enabled");
3051 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003052 }
kwiberg55b97fe2016-01-28 05:22:45 -08003053 _outputExternalMediaCallbackPtr = &processObject;
3054 _outputExternalMedia = true;
3055 } else if (kRecordingPerChannel == type) {
3056 if (_inputExternalMediaCallbackPtr) {
3057 _engineStatisticsPtr->SetLastError(
3058 VE_INVALID_OPERATION, kTraceError,
3059 "Channel::RegisterExternalMediaProcessing() "
3060 "output external media already enabled");
3061 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003062 }
kwiberg55b97fe2016-01-28 05:22:45 -08003063 _inputExternalMediaCallbackPtr = &processObject;
3064 channel_state_.SetInputExternalMedia(true);
3065 }
3066 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003067}
3068
kwiberg55b97fe2016-01-28 05:22:45 -08003069int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
3070 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3071 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003072
kwiberg55b97fe2016-01-28 05:22:45 -08003073 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003074
kwiberg55b97fe2016-01-28 05:22:45 -08003075 if (kPlaybackPerChannel == type) {
3076 if (!_outputExternalMediaCallbackPtr) {
3077 _engineStatisticsPtr->SetLastError(
3078 VE_INVALID_OPERATION, kTraceWarning,
3079 "Channel::DeRegisterExternalMediaProcessing() "
3080 "output external media already disabled");
3081 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003082 }
kwiberg55b97fe2016-01-28 05:22:45 -08003083 _outputExternalMedia = false;
3084 _outputExternalMediaCallbackPtr = NULL;
3085 } else if (kRecordingPerChannel == type) {
3086 if (!_inputExternalMediaCallbackPtr) {
3087 _engineStatisticsPtr->SetLastError(
3088 VE_INVALID_OPERATION, kTraceWarning,
3089 "Channel::DeRegisterExternalMediaProcessing() "
3090 "input external media already disabled");
3091 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003092 }
kwiberg55b97fe2016-01-28 05:22:45 -08003093 channel_state_.SetInputExternalMedia(false);
3094 _inputExternalMediaCallbackPtr = NULL;
3095 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003096
kwiberg55b97fe2016-01-28 05:22:45 -08003097 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003098}
3099
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003100int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08003101 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3102 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003103
kwiberg55b97fe2016-01-28 05:22:45 -08003104 if (channel_state_.Get().playing) {
3105 _engineStatisticsPtr->SetLastError(
3106 VE_INVALID_OPERATION, kTraceError,
3107 "Channel::SetExternalMixing() "
3108 "external mixing cannot be changed while playing.");
3109 return -1;
3110 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003111
kwiberg55b97fe2016-01-28 05:22:45 -08003112 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003113
kwiberg55b97fe2016-01-28 05:22:45 -08003114 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003115}
3116
kwiberg55b97fe2016-01-28 05:22:45 -08003117int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3118 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003119}
3120
wu@webrtc.org24301a62013-12-13 19:17:43 +00003121void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3122 audio_coding_->GetDecodingCallStatistics(stats);
3123}
3124
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003125bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3126 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003127 rtc::CritScope lock(&video_sync_lock_);
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003128 if (_average_jitter_buffer_delay_us == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003129 return false;
3130 }
kwiberg55b97fe2016-01-28 05:22:45 -08003131 *jitter_buffer_delay_ms =
3132 (_average_jitter_buffer_delay_us + 500) / 1000 + _recPacketDelayMs;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003133 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003134 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003135}
3136
solenberg358057b2015-11-27 10:46:42 -08003137uint32_t Channel::GetDelayEstimate() const {
3138 int jitter_buffer_delay_ms = 0;
3139 int playout_buffer_delay_ms = 0;
3140 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3141 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3142}
3143
deadbeef74375882015-08-13 12:09:10 -07003144int Channel::LeastRequiredDelayMs() const {
3145 return audio_coding_->LeastRequiredDelayMs();
3146}
3147
kwiberg55b97fe2016-01-28 05:22:45 -08003148int Channel::SetMinimumPlayoutDelay(int delayMs) {
3149 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3150 "Channel::SetMinimumPlayoutDelay()");
3151 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3152 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3153 _engineStatisticsPtr->SetLastError(
3154 VE_INVALID_ARGUMENT, kTraceError,
3155 "SetMinimumPlayoutDelay() invalid min delay");
3156 return -1;
3157 }
3158 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3159 _engineStatisticsPtr->SetLastError(
3160 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3161 "SetMinimumPlayoutDelay() failed to set min playout delay");
3162 return -1;
3163 }
3164 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003165}
3166
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003167int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003168 uint32_t playout_timestamp_rtp = 0;
3169 {
tommi31fc21f2016-01-21 10:37:37 -08003170 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003171 playout_timestamp_rtp = playout_timestamp_rtp_;
3172 }
kwiberg55b97fe2016-01-28 05:22:45 -08003173 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003174 _engineStatisticsPtr->SetLastError(
3175 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3176 "GetPlayoutTimestamp() failed to retrieve timestamp");
3177 return -1;
3178 }
deadbeef74375882015-08-13 12:09:10 -07003179 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003180 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003181}
3182
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003183int Channel::SetInitTimestamp(unsigned int timestamp) {
3184 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003185 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003186 if (channel_state_.Get().sending) {
3187 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3188 "SetInitTimestamp() already sending");
3189 return -1;
3190 }
3191 _rtpRtcpModule->SetStartTimestamp(timestamp);
3192 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003193}
3194
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003195int Channel::SetInitSequenceNumber(short sequenceNumber) {
3196 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3197 "Channel::SetInitSequenceNumber()");
3198 if (channel_state_.Get().sending) {
3199 _engineStatisticsPtr->SetLastError(
3200 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3201 return -1;
3202 }
3203 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3204 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003205}
3206
kwiberg55b97fe2016-01-28 05:22:45 -08003207int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3208 RtpReceiver** rtp_receiver) const {
3209 *rtpRtcpModule = _rtpRtcpModule.get();
3210 *rtp_receiver = rtp_receiver_.get();
3211 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003212}
3213
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003214// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3215// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003216int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003217 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003218 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003219
kwiberg55b97fe2016-01-28 05:22:45 -08003220 {
3221 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003222
kwiberg55b97fe2016-01-28 05:22:45 -08003223 if (_inputFilePlayerPtr == NULL) {
3224 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3225 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3226 " doesnt exist");
3227 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003228 }
3229
kwiberg55b97fe2016-01-28 05:22:45 -08003230 if (_inputFilePlayerPtr->Get10msAudioFromFile(fileBuffer.get(), fileSamples,
3231 mixingFrequency) == -1) {
3232 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3233 "Channel::MixOrReplaceAudioWithFile() file mixing "
3234 "failed");
3235 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003236 }
kwiberg55b97fe2016-01-28 05:22:45 -08003237 if (fileSamples == 0) {
3238 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3239 "Channel::MixOrReplaceAudioWithFile() file is ended");
3240 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003241 }
kwiberg55b97fe2016-01-28 05:22:45 -08003242 }
3243
3244 assert(_audioFrame.samples_per_channel_ == fileSamples);
3245
3246 if (_mixFileWithMicrophone) {
3247 // Currently file stream is always mono.
3248 // TODO(xians): Change the code when FilePlayer supports real stereo.
3249 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3250 1, fileSamples);
3251 } else {
3252 // Replace ACM audio with file.
3253 // Currently file stream is always mono.
3254 // TODO(xians): Change the code when FilePlayer supports real stereo.
3255 _audioFrame.UpdateFrame(
3256 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3257 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3258 }
3259 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003260}
3261
kwiberg55b97fe2016-01-28 05:22:45 -08003262int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3263 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003264
kwibergb7f89d62016-02-17 10:04:18 -08003265 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003266 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003267
kwiberg55b97fe2016-01-28 05:22:45 -08003268 {
3269 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003270
kwiberg55b97fe2016-01-28 05:22:45 -08003271 if (_outputFilePlayerPtr == NULL) {
3272 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3273 "Channel::MixAudioWithFile() file mixing failed");
3274 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003275 }
3276
kwiberg55b97fe2016-01-28 05:22:45 -08003277 // We should get the frequency we ask for.
3278 if (_outputFilePlayerPtr->Get10msAudioFromFile(
3279 fileBuffer.get(), fileSamples, mixingFrequency) == -1) {
3280 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3281 "Channel::MixAudioWithFile() file mixing failed");
3282 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003283 }
kwiberg55b97fe2016-01-28 05:22:45 -08003284 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003285
kwiberg55b97fe2016-01-28 05:22:45 -08003286 if (audioFrame.samples_per_channel_ == fileSamples) {
3287 // Currently file stream is always mono.
3288 // TODO(xians): Change the code when FilePlayer supports real stereo.
3289 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3290 fileSamples);
3291 } else {
3292 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3293 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3294 ") != "
3295 "fileSamples(%" PRIuS ")",
3296 audioFrame.samples_per_channel_, fileSamples);
3297 return -1;
3298 }
3299
3300 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003301}
3302
deadbeef74375882015-08-13 12:09:10 -07003303void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003304 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003305
henrik.lundin96bd5022016-04-06 04:13:56 -07003306 if (!jitter_buffer_playout_timestamp_) {
3307 // This can happen if this channel has not received any RTP packets. In
3308 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003309 return;
3310 }
3311
3312 uint16_t delay_ms = 0;
3313 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003314 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003315 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3316 " delay from the ADM");
3317 _engineStatisticsPtr->SetLastError(
3318 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3319 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3320 return;
3321 }
3322
henrik.lundin96bd5022016-04-06 04:13:56 -07003323 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3324 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003325
3326 // Remove the playout delay.
henrik.lundin96bd5022016-04-06 04:13:56 -07003327 playout_timestamp -= (delay_ms * (GetPlayoutFrequency() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003328
kwiberg55b97fe2016-01-28 05:22:45 -08003329 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003330 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003331 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003332
3333 {
tommi31fc21f2016-01-21 10:37:37 -08003334 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003335 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003336 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003337 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003338 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003339 }
3340 playout_delay_ms_ = delay_ms;
3341 }
3342}
3343
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003344// Called for incoming RTP packets after successful RTP header parsing.
3345void Channel::UpdatePacketDelay(uint32_t rtp_timestamp,
3346 uint16_t sequence_number) {
kwiberg55b97fe2016-01-28 05:22:45 -08003347 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003348 "Channel::UpdatePacketDelay(timestamp=%lu, sequenceNumber=%u)",
3349 rtp_timestamp, sequence_number);
niklase@google.com470e71d2011-07-07 08:21:25 +00003350
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003351 // Get frequency of last received payload
wu@webrtc.org94454b72014-06-05 20:34:08 +00003352 int rtp_receive_frequency = GetPlayoutFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +00003353
turaj@webrtc.org167b6df2013-12-13 21:05:07 +00003354 // |jitter_buffer_playout_timestamp_| updated in UpdatePlayoutTimestamp for
henrik.lundin96bd5022016-04-06 04:13:56 -07003355 // every incoming packet. May be empty if no valid playout timestamp is
3356 // available.
3357 // If |rtp_timestamp| is newer than |jitter_buffer_playout_timestamp_|, the
3358 // resulting difference is positive and will be used. When the inverse is
3359 // true (can happen when a network glitch causes a packet to arrive late,
3360 // and during long comfort noise periods with clock drift), or when
3361 // |jitter_buffer_playout_timestamp_| has no value, the difference is not
3362 // changed from the initial 0.
3363 uint32_t timestamp_diff_ms = 0;
3364 if (jitter_buffer_playout_timestamp_ &&
3365 IsNewerTimestamp(rtp_timestamp, *jitter_buffer_playout_timestamp_)) {
3366 timestamp_diff_ms = (rtp_timestamp - *jitter_buffer_playout_timestamp_) /
3367 (rtp_receive_frequency / 1000);
3368 if (timestamp_diff_ms > (2 * kVoiceEngineMaxMinPlayoutDelayMs)) {
3369 // Diff is too large; set it to zero instead.
3370 timestamp_diff_ms = 0;
3371 }
henrik.lundin@webrtc.orgd6692992014-03-20 12:04:09 +00003372 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003373
kwiberg55b97fe2016-01-28 05:22:45 -08003374 uint16_t packet_delay_ms =
3375 (rtp_timestamp - _previousTimestamp) / (rtp_receive_frequency / 1000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003376
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003377 _previousTimestamp = rtp_timestamp;
niklase@google.com470e71d2011-07-07 08:21:25 +00003378
kwiberg55b97fe2016-01-28 05:22:45 -08003379 if (timestamp_diff_ms == 0)
3380 return;
niklase@google.com470e71d2011-07-07 08:21:25 +00003381
deadbeef74375882015-08-13 12:09:10 -07003382 {
tommi31fc21f2016-01-21 10:37:37 -08003383 rtc::CritScope lock(&video_sync_lock_);
niklase@google.com470e71d2011-07-07 08:21:25 +00003384
deadbeef74375882015-08-13 12:09:10 -07003385 if (packet_delay_ms >= 10 && packet_delay_ms <= 60) {
3386 _recPacketDelayMs = packet_delay_ms;
3387 }
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003388
deadbeef74375882015-08-13 12:09:10 -07003389 if (_average_jitter_buffer_delay_us == 0) {
3390 _average_jitter_buffer_delay_us = timestamp_diff_ms * 1000;
3391 return;
3392 }
3393
3394 // Filter average delay value using exponential filter (alpha is
3395 // 7/8). We derive 1000 *_average_jitter_buffer_delay_us here (reduces
3396 // risk of rounding error) and compensate for it in GetDelayEstimate()
3397 // later.
kwiberg55b97fe2016-01-28 05:22:45 -08003398 _average_jitter_buffer_delay_us =
3399 (_average_jitter_buffer_delay_us * 7 + 1000 * timestamp_diff_ms + 500) /
3400 8;
deadbeef74375882015-08-13 12:09:10 -07003401 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003402}
3403
kwiberg55b97fe2016-01-28 05:22:45 -08003404void Channel::RegisterReceiveCodecsToRTPModule() {
3405 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3406 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003407
kwiberg55b97fe2016-01-28 05:22:45 -08003408 CodecInst codec;
3409 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003410
kwiberg55b97fe2016-01-28 05:22:45 -08003411 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3412 // Open up the RTP/RTCP receiver for all supported codecs
3413 if ((audio_coding_->Codec(idx, &codec) == -1) ||
3414 (rtp_receiver_->RegisterReceivePayload(
3415 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3416 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
3417 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3418 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3419 " to register %s (%d/%d/%" PRIuS
3420 "/%d) to RTP/RTCP "
3421 "receiver",
3422 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3423 codec.rate);
3424 } else {
3425 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3426 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3427 "(%d/%d/%" PRIuS
3428 "/%d) has been added to the RTP/RTCP "
3429 "receiver",
3430 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3431 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003432 }
kwiberg55b97fe2016-01-28 05:22:45 -08003433 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003434}
3435
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00003436// Assuming this method is called with valid payload type.
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003437int Channel::SetRedPayloadType(int red_payload_type) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003438 CodecInst codec;
3439 bool found_red = false;
3440
3441 // Get default RED settings from the ACM database
3442 const int num_codecs = AudioCodingModule::NumberOfCodecs();
3443 for (int idx = 0; idx < num_codecs; idx++) {
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00003444 audio_coding_->Codec(idx, &codec);
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003445 if (!STR_CASE_CMP(codec.plname, "RED")) {
3446 found_red = true;
3447 break;
3448 }
3449 }
3450
3451 if (!found_red) {
3452 _engineStatisticsPtr->SetLastError(
3453 VE_CODEC_ERROR, kTraceError,
3454 "SetRedPayloadType() RED is not supported");
3455 return -1;
3456 }
3457
turaj@webrtc.org9d532fd2013-01-31 18:34:19 +00003458 codec.pltype = red_payload_type;
kwibergc8d071e2016-04-06 12:22:38 -07003459 if (!codec_manager_.RegisterEncoder(codec) ||
3460 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003461 _engineStatisticsPtr->SetLastError(
3462 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3463 "SetRedPayloadType() RED registration in ACM module failed");
3464 return -1;
3465 }
3466
3467 if (_rtpRtcpModule->SetSendREDPayloadType(red_payload_type) != 0) {
3468 _engineStatisticsPtr->SetLastError(
3469 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
3470 "SetRedPayloadType() RED registration in RTP/RTCP module failed");
3471 return -1;
3472 }
3473 return 0;
3474}
3475
kwiberg55b97fe2016-01-28 05:22:45 -08003476int Channel::SetSendRtpHeaderExtension(bool enable,
3477 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003478 unsigned char id) {
3479 int error = 0;
3480 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3481 if (enable) {
3482 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3483 }
3484 return error;
3485}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003486
wu@webrtc.org94454b72014-06-05 20:34:08 +00003487int32_t Channel::GetPlayoutFrequency() {
3488 int32_t playout_frequency = audio_coding_->PlayoutFrequency();
3489 CodecInst current_recive_codec;
3490 if (audio_coding_->ReceiveCodec(&current_recive_codec) == 0) {
3491 if (STR_CASE_CMP("G722", current_recive_codec.plname) == 0) {
3492 // Even though the actual sampling rate for G.722 audio is
3493 // 16,000 Hz, the RTP clock rate for the G722 payload format is
3494 // 8,000 Hz because that value was erroneously assigned in
3495 // RFC 1890 and must remain unchanged for backward compatibility.
3496 playout_frequency = 8000;
3497 } else if (STR_CASE_CMP("opus", current_recive_codec.plname) == 0) {
3498 // We are resampling Opus internally to 32,000 Hz until all our
3499 // DSP routines can operate at 48,000 Hz, but the RTP clock
3500 // rate for the Opus payload format is standardized to 48,000 Hz,
3501 // because that is the maximum supported decoding sampling rate.
3502 playout_frequency = 48000;
3503 }
3504 }
3505 return playout_frequency;
3506}
3507
Minyue2013aec2015-05-13 14:14:42 +02003508int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003509 RtcpMode method = _rtpRtcpModule->RTCP();
3510 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003511 return 0;
3512 }
3513 std::vector<RTCPReportBlock> report_blocks;
3514 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003515
3516 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003517 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003518 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003519 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003520 Channel* channel = associate_send_channel_.channel();
3521 // Tries to get RTT from an associated channel. This is important for
3522 // receive-only channels.
3523 if (channel) {
3524 // To prevent infinite recursion and deadlock, calling GetRTT of
3525 // associate channel should always use "false" for argument:
3526 // |allow_associate_channel|.
3527 rtt = channel->GetRTT(false);
3528 }
3529 }
3530 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003531 }
3532
3533 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3534 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3535 for (; it != report_blocks.end(); ++it) {
3536 if (it->remoteSSRC == remoteSSRC)
3537 break;
3538 }
3539 if (it == report_blocks.end()) {
3540 // We have not received packets with SSRC matching the report blocks.
3541 // To calculate RTT we try with the SSRC of the first report block.
3542 // This is very important for send-only channels where we don't know
3543 // the SSRC of the other end.
3544 remoteSSRC = report_blocks[0].remoteSSRC;
3545 }
Minyue2013aec2015-05-13 14:14:42 +02003546
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003547 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003548 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003549 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003550 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3551 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003552 return 0;
3553 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003554 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003555}
3556
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003557} // namespace voe
3558} // namespace webrtc