blob: 6b9de2976e92a5d41095346902181404a2060905 [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"
ossue3525782016-05-25 07:37:43 -070024#include "webrtc/modules/audio_coding/codecs/builtin_audio_decoder_factory.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000025#include "webrtc/modules/audio_device/include/audio_device.h"
26#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010027#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010028#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010029#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
30#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
31#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000032#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010033#include "webrtc/modules/utility/include/audio_frame_operations.h"
34#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010035#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000036#include "webrtc/voice_engine/include/voe_base.h"
37#include "webrtc/voice_engine/include/voe_external_media.h"
38#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
39#include "webrtc/voice_engine/output_mixer.h"
40#include "webrtc/voice_engine/statistics.h"
41#include "webrtc/voice_engine/transmit_mixer.h"
42#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000043
andrew@webrtc.org50419b02012-11-14 19:07:54 +000044namespace webrtc {
45namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000046
kwibergc8d071e2016-04-06 12:22:38 -070047namespace {
48
49bool RegisterReceiveCodec(std::unique_ptr<AudioCodingModule>* acm,
50 acm2::RentACodec* rac,
51 const CodecInst& ci) {
52 const int result =
53 (*acm)->RegisterReceiveCodec(ci, [&] { return rac->RentIsacDecoder(); });
54 return result == 0;
55}
56
57} // namespace
58
solenberg8842c3e2016-03-11 03:06:41 -080059const int kTelephoneEventAttenuationdB = 10;
60
Stefan Holmerb86d4e42015-12-07 10:26:18 +010061class TransportFeedbackProxy : public TransportFeedbackObserver {
62 public:
63 TransportFeedbackProxy() : feedback_observer_(nullptr) {
64 pacer_thread_.DetachFromThread();
65 network_thread_.DetachFromThread();
66 }
67
68 void SetTransportFeedbackObserver(
69 TransportFeedbackObserver* feedback_observer) {
70 RTC_DCHECK(thread_checker_.CalledOnValidThread());
71 rtc::CritScope lock(&crit_);
72 feedback_observer_ = feedback_observer;
73 }
74
75 // Implements TransportFeedbackObserver.
76 void AddPacket(uint16_t sequence_number,
77 size_t length,
philipel46948c12016-06-01 04:04:40 -070078 bool was_paced) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +010079 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
80 rtc::CritScope lock(&crit_);
81 if (feedback_observer_)
philipel46948c12016-06-01 04:04:40 -070082 feedback_observer_->AddPacket(sequence_number, length, was_paced);
Stefan Holmerb86d4e42015-12-07 10:26:18 +010083 }
84 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
85 RTC_DCHECK(network_thread_.CalledOnValidThread());
86 rtc::CritScope lock(&crit_);
87 if (feedback_observer_)
88 feedback_observer_->OnTransportFeedback(feedback);
89 }
90
91 private:
92 rtc::CriticalSection crit_;
93 rtc::ThreadChecker thread_checker_;
94 rtc::ThreadChecker pacer_thread_;
95 rtc::ThreadChecker network_thread_;
96 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
97};
98
99class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
100 public:
101 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
102 pacer_thread_.DetachFromThread();
103 }
104
105 void SetSequenceNumberAllocator(
106 TransportSequenceNumberAllocator* seq_num_allocator) {
107 RTC_DCHECK(thread_checker_.CalledOnValidThread());
108 rtc::CritScope lock(&crit_);
109 seq_num_allocator_ = seq_num_allocator;
110 }
111
112 // Implements TransportSequenceNumberAllocator.
113 uint16_t AllocateSequenceNumber() override {
114 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
115 rtc::CritScope lock(&crit_);
116 if (!seq_num_allocator_)
117 return 0;
118 return seq_num_allocator_->AllocateSequenceNumber();
119 }
120
121 private:
122 rtc::CriticalSection crit_;
123 rtc::ThreadChecker thread_checker_;
124 rtc::ThreadChecker pacer_thread_;
125 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
126};
127
128class RtpPacketSenderProxy : public RtpPacketSender {
129 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800130 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100131
132 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
133 RTC_DCHECK(thread_checker_.CalledOnValidThread());
134 rtc::CritScope lock(&crit_);
135 rtp_packet_sender_ = rtp_packet_sender;
136 }
137
138 // Implements RtpPacketSender.
139 void InsertPacket(Priority priority,
140 uint32_t ssrc,
141 uint16_t sequence_number,
142 int64_t capture_time_ms,
143 size_t bytes,
144 bool retransmission) override {
145 rtc::CritScope lock(&crit_);
146 if (rtp_packet_sender_) {
147 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
148 capture_time_ms, bytes, retransmission);
149 }
150 }
151
152 private:
153 rtc::ThreadChecker thread_checker_;
154 rtc::CriticalSection crit_;
155 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
156};
157
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000158// Extend the default RTCP statistics struct with max_jitter, defined as the
159// maximum jitter value seen in an RTCP report block.
160struct ChannelStatistics : public RtcpStatistics {
161 ChannelStatistics() : rtcp(), max_jitter(0) {}
162
163 RtcpStatistics rtcp;
164 uint32_t max_jitter;
165};
166
167// Statistics callback, called at each generation of a new RTCP report block.
168class StatisticsProxy : public RtcpStatisticsCallback {
169 public:
tommi31fc21f2016-01-21 10:37:37 -0800170 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000171 virtual ~StatisticsProxy() {}
172
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000173 void StatisticsUpdated(const RtcpStatistics& statistics,
174 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000175 if (ssrc != ssrc_)
176 return;
177
tommi31fc21f2016-01-21 10:37:37 -0800178 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000179 stats_.rtcp = statistics;
180 if (statistics.jitter > stats_.max_jitter) {
181 stats_.max_jitter = statistics.jitter;
182 }
183 }
184
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000185 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000186
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000187 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800188 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000189 return stats_;
190 }
191
192 private:
193 // StatisticsUpdated calls are triggered from threads in the RTP module,
194 // while GetStats calls can be triggered from the public voice engine API,
195 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800196 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000197 const uint32_t ssrc_;
198 ChannelStatistics stats_;
199};
200
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000201class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000202 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000203 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
204 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000205
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000206 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
207 // Not used for Voice Engine.
208 }
209
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000210 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
211 int64_t rtt,
212 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000213 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
214 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
215 // report for VoiceEngine?
216 if (report_blocks.empty())
217 return;
218
219 int fraction_lost_aggregate = 0;
220 int total_number_of_packets = 0;
221
222 // If receiving multiple report blocks, calculate the weighted average based
223 // on the number of packets a report refers to.
224 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
225 block_it != report_blocks.end(); ++block_it) {
226 // Find the previous extended high sequence number for this remote SSRC,
227 // to calculate the number of RTP packets this report refers to. Ignore if
228 // we haven't seen this SSRC before.
229 std::map<uint32_t, uint32_t>::iterator seq_num_it =
230 extended_max_sequence_number_.find(block_it->sourceSSRC);
231 int number_of_packets = 0;
232 if (seq_num_it != extended_max_sequence_number_.end()) {
233 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
234 }
235 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
236 total_number_of_packets += number_of_packets;
237
238 extended_max_sequence_number_[block_it->sourceSSRC] =
239 block_it->extendedHighSeqNum;
240 }
241 int weighted_fraction_lost = 0;
242 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800243 weighted_fraction_lost =
244 (fraction_lost_aggregate + total_number_of_packets / 2) /
245 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000246 }
247 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000248 }
249
250 private:
251 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000252 // Maps remote side ssrc to extended highest sequence number received.
253 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000254};
255
kwiberg55b97fe2016-01-28 05:22:45 -0800256int32_t Channel::SendData(FrameType frameType,
257 uint8_t payloadType,
258 uint32_t timeStamp,
259 const uint8_t* payloadData,
260 size_t payloadSize,
261 const RTPFragmentationHeader* fragmentation) {
262 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
263 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
264 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
265 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000266
kwiberg55b97fe2016-01-28 05:22:45 -0800267 if (_includeAudioLevelIndication) {
268 // Store current audio level in the RTP/RTCP module.
269 // The level will be used in combination with voice-activity state
270 // (frameType) to add an RTP header extension
271 _rtpRtcpModule->SetAudioLevel(rms_level_.RMS());
272 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000273
kwiberg55b97fe2016-01-28 05:22:45 -0800274 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
275 // packetization.
276 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
277 if (_rtpRtcpModule->SendOutgoingData(
278 (FrameType&)frameType, payloadType, timeStamp,
279 // Leaving the time when this frame was
280 // received from the capture device as
281 // undefined for voice for now.
282 -1, payloadData, payloadSize, fragmentation) == -1) {
283 _engineStatisticsPtr->SetLastError(
284 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
285 "Channel::SendData() failed to send data to RTP/RTCP module");
286 return -1;
287 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000288
kwiberg55b97fe2016-01-28 05:22:45 -0800289 _lastLocalTimeStamp = timeStamp;
290 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000291
kwiberg55b97fe2016-01-28 05:22:45 -0800292 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000293}
294
kwiberg55b97fe2016-01-28 05:22:45 -0800295int32_t Channel::InFrameType(FrameType frame_type) {
296 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
297 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000298
kwiberg55b97fe2016-01-28 05:22:45 -0800299 rtc::CritScope cs(&_callbackCritSect);
300 _sendFrameType = (frame_type == kAudioFrameSpeech);
301 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000302}
303
kwiberg55b97fe2016-01-28 05:22:45 -0800304int32_t Channel::OnRxVadDetected(int vadDecision) {
305 rtc::CritScope cs(&_callbackCritSect);
306 if (_rxVadObserverPtr) {
307 _rxVadObserverPtr->OnRxVad(_channelId, vadDecision);
308 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000309
kwiberg55b97fe2016-01-28 05:22:45 -0800310 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000311}
312
stefan1d8a5062015-10-02 03:39:33 -0700313bool Channel::SendRtp(const uint8_t* data,
314 size_t len,
315 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800316 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
317 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000318
kwiberg55b97fe2016-01-28 05:22:45 -0800319 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000320
kwiberg55b97fe2016-01-28 05:22:45 -0800321 if (_transportPtr == NULL) {
322 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
323 "Channel::SendPacket() failed to send RTP packet due to"
324 " invalid transport object");
325 return false;
326 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000327
kwiberg55b97fe2016-01-28 05:22:45 -0800328 uint8_t* bufferToSendPtr = (uint8_t*)data;
329 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000330
kwiberg55b97fe2016-01-28 05:22:45 -0800331 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
332 std::string transport_name =
333 _externalTransport ? "external transport" : "WebRtc sockets";
334 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
335 "Channel::SendPacket() RTP transmission using %s failed",
336 transport_name.c_str());
337 return false;
338 }
339 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000340}
341
kwiberg55b97fe2016-01-28 05:22:45 -0800342bool Channel::SendRtcp(const uint8_t* data, size_t len) {
343 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
344 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000345
kwiberg55b97fe2016-01-28 05:22:45 -0800346 rtc::CritScope cs(&_callbackCritSect);
347 if (_transportPtr == NULL) {
348 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
349 "Channel::SendRtcp() failed to send RTCP packet"
350 " due to invalid transport object");
351 return false;
352 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000353
kwiberg55b97fe2016-01-28 05:22:45 -0800354 uint8_t* bufferToSendPtr = (uint8_t*)data;
355 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000356
kwiberg55b97fe2016-01-28 05:22:45 -0800357 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
358 if (n < 0) {
359 std::string transport_name =
360 _externalTransport ? "external transport" : "WebRtc sockets";
361 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
362 "Channel::SendRtcp() transmission using %s failed",
363 transport_name.c_str());
364 return false;
365 }
366 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000367}
368
kwiberg55b97fe2016-01-28 05:22:45 -0800369void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
370 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
371 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000372
kwiberg55b97fe2016-01-28 05:22:45 -0800373 // Update ssrc so that NTP for AV sync can be updated.
374 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000375}
376
Peter Boströmac547a62015-09-17 23:03:57 +0200377void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
378 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
379 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
380 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000381}
382
Peter Boströmac547a62015-09-17 23:03:57 +0200383int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000384 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000385 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000386 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800387 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200388 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800389 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
390 "Channel::OnInitializeDecoder(payloadType=%d, "
391 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
392 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000393
kwiberg55b97fe2016-01-28 05:22:45 -0800394 CodecInst receiveCodec = {0};
395 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000396
kwiberg55b97fe2016-01-28 05:22:45 -0800397 receiveCodec.pltype = payloadType;
398 receiveCodec.plfreq = frequency;
399 receiveCodec.channels = channels;
400 receiveCodec.rate = rate;
401 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000402
kwiberg55b97fe2016-01-28 05:22:45 -0800403 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
404 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000405
kwiberg55b97fe2016-01-28 05:22:45 -0800406 // Register the new codec to the ACM
kwibergc8d071e2016-04-06 12:22:38 -0700407 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, receiveCodec)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800408 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
409 "Channel::OnInitializeDecoder() invalid codec ("
410 "pt=%d, name=%s) received - 1",
411 payloadType, payloadName);
412 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
413 return -1;
414 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000415
kwiberg55b97fe2016-01-28 05:22:45 -0800416 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000417}
418
kwiberg55b97fe2016-01-28 05:22:45 -0800419int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
420 size_t payloadSize,
421 const WebRtcRTPHeader* rtpHeader) {
422 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
423 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
424 ","
425 " payloadType=%u, audioChannel=%" PRIuS ")",
426 payloadSize, rtpHeader->header.payloadType,
427 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000428
kwiberg55b97fe2016-01-28 05:22:45 -0800429 if (!channel_state_.Get().playing) {
430 // Avoid inserting into NetEQ when we are not playing. Count the
431 // packet as discarded.
432 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
433 "received packet is discarded since playing is not"
434 " activated");
435 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000436 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800437 }
438
439 // Push the incoming payload (parsed and ready for decoding) into the ACM
440 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
441 0) {
442 _engineStatisticsPtr->SetLastError(
443 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
444 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
445 return -1;
446 }
447
448 // Update the packet delay.
449 UpdatePacketDelay(rtpHeader->header.timestamp,
450 rtpHeader->header.sequenceNumber);
451
452 int64_t round_trip_time = 0;
453 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
454 NULL);
455
456 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
457 if (!nack_list.empty()) {
458 // Can't use nack_list.data() since it's not supported by all
459 // compilers.
460 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
461 }
462 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000463}
464
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000465bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000466 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000467 RTPHeader header;
468 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
469 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
470 "IncomingPacket invalid RTP header");
471 return false;
472 }
473 header.payload_type_frequency =
474 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
475 if (header.payload_type_frequency < 0)
476 return false;
477 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
478}
479
henrik.lundin42dda502016-05-18 05:36:01 -0700480MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
481 int32_t id,
482 AudioFrame* audioFrame) {
kwiberg55b97fe2016-01-28 05:22:45 -0800483 if (event_log_) {
484 unsigned int ssrc;
485 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
486 event_log_->LogAudioPlayout(ssrc);
487 }
488 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700489 bool muted;
490 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
491 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800492 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
493 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
494 // In all likelihood, the audio in this frame is garbage. We return an
495 // error so that the audio mixer module doesn't add it to the mix. As
496 // a result, it won't be played out and the actions skipped here are
497 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700498 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800499 }
henrik.lundina89ab962016-05-18 08:52:45 -0700500
501 if (muted) {
502 // TODO(henrik.lundin): We should be able to do better than this. But we
503 // will have to go through all the cases below where the audio samples may
504 // be used, and handle the muted case in some way.
505 audioFrame->Mute();
506 }
kwiberg55b97fe2016-01-28 05:22:45 -0800507
508 if (_RxVadDetection) {
509 UpdateRxVadDetection(*audioFrame);
510 }
511
512 // Convert module ID to internal VoE channel ID
513 audioFrame->id_ = VoEChannelId(audioFrame->id_);
514 // Store speech type for dead-or-alive detection
515 _outputSpeechType = audioFrame->speech_type_;
516
517 ChannelState::State state = channel_state_.Get();
518
519 if (state.rx_apm_is_enabled) {
520 int err = rx_audioproc_->ProcessStream(audioFrame);
521 if (err) {
522 LOG(LS_ERROR) << "ProcessStream() error: " << err;
523 assert(false);
Ivo Creusenae856f22015-09-17 16:30:16 +0200524 }
kwiberg55b97fe2016-01-28 05:22:45 -0800525 }
526
527 {
528 // Pass the audio buffers to an optional sink callback, before applying
529 // scaling/panning, as that applies to the mix operation.
530 // External recipients of the audio (e.g. via AudioTrack), will do their
531 // own mixing/dynamic processing.
532 rtc::CritScope cs(&_callbackCritSect);
533 if (audio_sink_) {
534 AudioSinkInterface::Data data(
535 &audioFrame->data_[0], audioFrame->samples_per_channel_,
536 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
537 audioFrame->timestamp_);
538 audio_sink_->OnData(data);
539 }
540 }
541
542 float output_gain = 1.0f;
543 float left_pan = 1.0f;
544 float right_pan = 1.0f;
545 {
546 rtc::CritScope cs(&volume_settings_critsect_);
547 output_gain = _outputGain;
548 left_pan = _panLeft;
549 right_pan = _panRight;
550 }
551
552 // Output volume scaling
553 if (output_gain < 0.99f || output_gain > 1.01f) {
554 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
555 }
556
557 // Scale left and/or right channel(s) if stereo and master balance is
558 // active
559
560 if (left_pan != 1.0f || right_pan != 1.0f) {
561 if (audioFrame->num_channels_ == 1) {
562 // Emulate stereo mode since panning is active.
563 // The mono signal is copied to both left and right channels here.
564 AudioFrameOperations::MonoToStereo(audioFrame);
565 }
566 // For true stereo mode (when we are receiving a stereo signal), no
567 // action is needed.
568
569 // Do the panning operation (the audio frame contains stereo at this
570 // stage)
571 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
572 }
573
574 // Mix decoded PCM output with file if file mixing is enabled
575 if (state.output_file_playing) {
576 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700577 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800578 }
579
580 // External media
581 if (_outputExternalMedia) {
582 rtc::CritScope cs(&_callbackCritSect);
583 const bool isStereo = (audioFrame->num_channels_ == 2);
584 if (_outputExternalMediaCallbackPtr) {
585 _outputExternalMediaCallbackPtr->Process(
586 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
587 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
588 isStereo);
589 }
590 }
591
592 // Record playout if enabled
593 {
594 rtc::CritScope cs(&_fileCritSect);
595
596 if (_outputFileRecording && _outputFileRecorderPtr) {
597 _outputFileRecorderPtr->RecordAudioToFile(*audioFrame);
598 }
599 }
600
601 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700602 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800603 _outputAudioLevel.ComputeLevel(*audioFrame);
604
605 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
606 // The first frame with a valid rtp timestamp.
607 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
608 }
609
610 if (capture_start_rtp_time_stamp_ >= 0) {
611 // audioFrame.timestamp_ should be valid from now on.
612
613 // Compute elapsed time.
614 int64_t unwrap_timestamp =
615 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
616 audioFrame->elapsed_time_ms_ =
617 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
618 (GetPlayoutFrequency() / 1000);
619
niklase@google.com470e71d2011-07-07 08:21:25 +0000620 {
kwiberg55b97fe2016-01-28 05:22:45 -0800621 rtc::CritScope lock(&ts_stats_lock_);
622 // Compute ntp time.
623 audioFrame->ntp_time_ms_ =
624 ntp_estimator_.Estimate(audioFrame->timestamp_);
625 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
626 if (audioFrame->ntp_time_ms_ > 0) {
627 // Compute |capture_start_ntp_time_ms_| so that
628 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
629 capture_start_ntp_time_ms_ =
630 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000631 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000632 }
kwiberg55b97fe2016-01-28 05:22:45 -0800633 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000634
henrik.lundin42dda502016-05-18 05:36:01 -0700635 return muted ? MixerParticipant::AudioFrameInfo::kMuted
636 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000637}
638
kwiberg55b97fe2016-01-28 05:22:45 -0800639int32_t Channel::NeededFrequency(int32_t id) const {
640 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
641 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000642
kwiberg55b97fe2016-01-28 05:22:45 -0800643 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000644
kwiberg55b97fe2016-01-28 05:22:45 -0800645 // Determine highest needed receive frequency
646 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000647
kwiberg55b97fe2016-01-28 05:22:45 -0800648 // Return the bigger of playout and receive frequency in the ACM.
649 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
650 highestNeeded = audio_coding_->PlayoutFrequency();
651 } else {
652 highestNeeded = receiveFrequency;
653 }
654
655 // Special case, if we're playing a file on the playout side
656 // we take that frequency into consideration as well
657 // This is not needed on sending side, since the codec will
658 // limit the spectrum anyway.
659 if (channel_state_.Get().output_file_playing) {
660 rtc::CritScope cs(&_fileCritSect);
661 if (_outputFilePlayerPtr) {
662 if (_outputFilePlayerPtr->Frequency() > highestNeeded) {
663 highestNeeded = _outputFilePlayerPtr->Frequency();
664 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000665 }
kwiberg55b97fe2016-01-28 05:22:45 -0800666 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000667
kwiberg55b97fe2016-01-28 05:22:45 -0800668 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000669}
670
ivocb04965c2015-09-09 00:09:43 -0700671int32_t Channel::CreateChannel(Channel*& channel,
672 int32_t channelId,
673 uint32_t instanceId,
674 RtcEventLog* const event_log,
675 const Config& config) {
ossu5f7cfa52016-05-30 08:11:28 -0700676 return CreateChannel(channel, channelId, instanceId, event_log, config,
677 CreateBuiltinAudioDecoderFactory());
678}
679
680int32_t Channel::CreateChannel(
681 Channel*& channel,
682 int32_t channelId,
683 uint32_t instanceId,
684 RtcEventLog* const event_log,
685 const Config& config,
686 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory) {
kwiberg55b97fe2016-01-28 05:22:45 -0800687 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
688 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
689 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000690
ossu5f7cfa52016-05-30 08:11:28 -0700691 channel =
692 new Channel(channelId, instanceId, event_log, config, decoder_factory);
kwiberg55b97fe2016-01-28 05:22:45 -0800693 if (channel == NULL) {
694 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
695 "Channel::CreateChannel() unable to allocate memory for"
696 " channel");
697 return -1;
698 }
699 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000700}
701
kwiberg55b97fe2016-01-28 05:22:45 -0800702void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
703 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
704 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
705 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000706
kwiberg55b97fe2016-01-28 05:22:45 -0800707 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000708}
709
kwiberg55b97fe2016-01-28 05:22:45 -0800710void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
711 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
712 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
713 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000714
kwiberg55b97fe2016-01-28 05:22:45 -0800715 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000716}
717
kwiberg55b97fe2016-01-28 05:22:45 -0800718void Channel::PlayFileEnded(int32_t id) {
719 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
720 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000721
kwiberg55b97fe2016-01-28 05:22:45 -0800722 if (id == _inputFilePlayerId) {
723 channel_state_.SetInputFilePlaying(false);
724 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
725 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000726 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800727 } else if (id == _outputFilePlayerId) {
728 channel_state_.SetOutputFilePlaying(false);
729 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
730 "Channel::PlayFileEnded() => output file player module is"
731 " shutdown");
732 }
733}
734
735void Channel::RecordFileEnded(int32_t id) {
736 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
737 "Channel::RecordFileEnded(id=%d)", id);
738
739 assert(id == _outputFileRecorderId);
740
741 rtc::CritScope cs(&_fileCritSect);
742
743 _outputFileRecording = false;
744 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
745 "Channel::RecordFileEnded() => output file recorder module is"
746 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000747}
748
pbos@webrtc.org92135212013-05-14 08:31:39 +0000749Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000750 uint32_t instanceId,
ivocb04965c2015-09-09 00:09:43 -0700751 RtcEventLog* const event_log,
ossu5f7cfa52016-05-30 08:11:28 -0700752 const Config& config,
753 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
tommi31fc21f2016-01-21 10:37:37 -0800754 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100755 _channelId(channelId),
756 event_log_(event_log),
757 rtp_header_parser_(RtpHeaderParser::Create()),
758 rtp_payload_registry_(
759 new RTPPayloadRegistry(RTPPayloadStrategy::CreateStrategy(true))),
760 rtp_receive_statistics_(
761 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
762 rtp_receiver_(
763 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100764 this,
765 this,
766 rtp_payload_registry_.get())),
767 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
768 _outputAudioLevel(),
769 _externalTransport(false),
770 _inputFilePlayerPtr(NULL),
771 _outputFilePlayerPtr(NULL),
772 _outputFileRecorderPtr(NULL),
773 // Avoid conflict with other channels by adding 1024 - 1026,
774 // won't use as much as 1024 channels.
775 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
776 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
777 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
778 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100779 _outputExternalMedia(false),
780 _inputExternalMediaCallbackPtr(NULL),
781 _outputExternalMediaCallbackPtr(NULL),
782 _timeStamp(0), // This is just an offset, RTP module will add it's own
783 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100784 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100785 playout_timestamp_rtp_(0),
786 playout_timestamp_rtcp_(0),
787 playout_delay_ms_(0),
788 _numberOfDiscardedPackets(0),
789 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100790 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
791 capture_start_rtp_time_stamp_(-1),
792 capture_start_ntp_time_ms_(-1),
793 _engineStatisticsPtr(NULL),
794 _outputMixerPtr(NULL),
795 _transmitMixerPtr(NULL),
796 _moduleProcessThreadPtr(NULL),
797 _audioDeviceModulePtr(NULL),
798 _voiceEngineObserverPtr(NULL),
799 _callbackCritSectPtr(NULL),
800 _transportPtr(NULL),
801 _rxVadObserverPtr(NULL),
802 _oldVadDecision(-1),
803 _sendFrameType(0),
804 _externalMixing(false),
805 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700806 input_mute_(false),
807 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100808 _panLeft(1.0f),
809 _panRight(1.0f),
810 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100811 _lastLocalTimeStamp(0),
812 _lastPayloadType(0),
813 _includeAudioLevelIndication(false),
814 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100815 _average_jitter_buffer_delay_us(0),
816 _previousTimestamp(0),
817 _recPacketDelayMs(20),
818 _RxVadDetection(false),
819 _rxAgcIsEnabled(false),
820 _rxNsIsEnabled(false),
821 restored_packet_in_use_(false),
822 rtcp_observer_(new VoERtcpObserver(this)),
823 network_predictor_(new NetworkPredictor(Clock::GetRealTimeClock())),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100824 associate_send_channel_(ChannelOwner(nullptr)),
825 pacing_enabled_(config.Get<VoicePacing>().enabled),
stefanbba9dec2016-02-01 04:39:55 -0800826 feedback_observer_proxy_(new TransportFeedbackProxy()),
827 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
828 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()) {
kwiberg55b97fe2016-01-28 05:22:45 -0800829 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
830 "Channel::Channel() - ctor");
831 AudioCodingModule::Config acm_config;
832 acm_config.id = VoEModuleId(instanceId, channelId);
833 if (config.Get<NetEqCapacityConfig>().enabled) {
834 // Clamping the buffer capacity at 20 packets. While going lower will
835 // probably work, it makes little sense.
836 acm_config.neteq_config.max_packets_in_buffer =
837 std::max(20, config.Get<NetEqCapacityConfig>().capacity);
838 }
839 acm_config.neteq_config.enable_fast_accelerate =
840 config.Get<NetEqFastAccelerate>().enabled;
henrik.lundina89ab962016-05-18 08:52:45 -0700841 acm_config.neteq_config.enable_muted_state = true;
ossu5f7cfa52016-05-30 08:11:28 -0700842 acm_config.decoder_factory = decoder_factory;
kwiberg55b97fe2016-01-28 05:22:45 -0800843 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200844
kwiberg55b97fe2016-01-28 05:22:45 -0800845 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000846
kwiberg55b97fe2016-01-28 05:22:45 -0800847 RtpRtcp::Configuration configuration;
848 configuration.audio = true;
849 configuration.outgoing_transport = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800850 configuration.receive_statistics = rtp_receive_statistics_.get();
851 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800852 if (pacing_enabled_) {
853 configuration.paced_sender = rtp_packet_sender_proxy_.get();
854 configuration.transport_sequence_number_allocator =
855 seq_num_allocator_proxy_.get();
856 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
857 }
kwiberg55b97fe2016-01-28 05:22:45 -0800858 configuration.event_log = event_log;
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000859
kwiberg55b97fe2016-01-28 05:22:45 -0800860 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100861 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000862
kwiberg55b97fe2016-01-28 05:22:45 -0800863 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
864 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
865 statistics_proxy_.get());
aluebs@webrtc.orgf927fd62014-04-16 11:58:18 +0000866
kwiberg55b97fe2016-01-28 05:22:45 -0800867 Config audioproc_config;
868 audioproc_config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
869 rx_audioproc_.reset(AudioProcessing::Create(audioproc_config));
niklase@google.com470e71d2011-07-07 08:21:25 +0000870}
871
kwiberg55b97fe2016-01-28 05:22:45 -0800872Channel::~Channel() {
873 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
874 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
875 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000876
kwiberg55b97fe2016-01-28 05:22:45 -0800877 if (_outputExternalMedia) {
878 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
879 }
880 if (channel_state_.Get().input_external_media) {
881 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
882 }
883 StopSend();
884 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000885
kwiberg55b97fe2016-01-28 05:22:45 -0800886 {
887 rtc::CritScope cs(&_fileCritSect);
888 if (_inputFilePlayerPtr) {
889 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
890 _inputFilePlayerPtr->StopPlayingFile();
891 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
892 _inputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000893 }
kwiberg55b97fe2016-01-28 05:22:45 -0800894 if (_outputFilePlayerPtr) {
895 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
896 _outputFilePlayerPtr->StopPlayingFile();
897 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
898 _outputFilePlayerPtr = NULL;
899 }
900 if (_outputFileRecorderPtr) {
901 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
902 _outputFileRecorderPtr->StopRecording();
903 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
904 _outputFileRecorderPtr = NULL;
905 }
906 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000907
kwiberg55b97fe2016-01-28 05:22:45 -0800908 // The order to safely shutdown modules in a channel is:
909 // 1. De-register callbacks in modules
910 // 2. De-register modules in process thread
911 // 3. Destroy modules
912 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
913 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
914 "~Channel() failed to de-register transport callback"
915 " (Audio coding module)");
916 }
917 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
918 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
919 "~Channel() failed to de-register VAD callback"
920 " (Audio coding module)");
921 }
922 // De-register modules in process thread
923 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +0000924
kwiberg55b97fe2016-01-28 05:22:45 -0800925 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +0000926}
927
kwiberg55b97fe2016-01-28 05:22:45 -0800928int32_t Channel::Init() {
929 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
930 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000931
kwiberg55b97fe2016-01-28 05:22:45 -0800932 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000933
kwiberg55b97fe2016-01-28 05:22:45 -0800934 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000935
kwiberg55b97fe2016-01-28 05:22:45 -0800936 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
937 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
938 "Channel::Init() must call SetEngineInformation() first");
939 return -1;
940 }
941
942 // --- Add modules to process thread (for periodic schedulation)
943
944 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
945
946 // --- ACM initialization
947
948 if (audio_coding_->InitializeReceiver() == -1) {
949 _engineStatisticsPtr->SetLastError(
950 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
951 "Channel::Init() unable to initialize the ACM - 1");
952 return -1;
953 }
954
955 // --- RTP/RTCP module initialization
956
957 // Ensure that RTCP is enabled by default for the created channel.
958 // Note that, the module will keep generating RTCP until it is explicitly
959 // disabled by the user.
960 // After StopListen (when no sockets exists), RTCP packets will no longer
961 // be transmitted since the Transport object will then be invalid.
962 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
963 // RTCP is enabled by default.
964 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
965 // --- Register all permanent callbacks
966 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
967 (audio_coding_->RegisterVADCallback(this) == -1);
968
969 if (fail) {
970 _engineStatisticsPtr->SetLastError(
971 VE_CANNOT_INIT_CHANNEL, kTraceError,
972 "Channel::Init() callbacks not registered");
973 return -1;
974 }
975
976 // --- Register all supported codecs to the receiving side of the
977 // RTP/RTCP module
978
979 CodecInst codec;
980 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
981
982 for (int idx = 0; idx < nSupportedCodecs; idx++) {
983 // Open up the RTP/RTCP receiver for all supported codecs
984 if ((audio_coding_->Codec(idx, &codec) == -1) ||
985 (rtp_receiver_->RegisterReceivePayload(
986 codec.plname, codec.pltype, codec.plfreq, codec.channels,
987 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
988 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
989 "Channel::Init() unable to register %s "
990 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
991 codec.plname, codec.pltype, codec.plfreq, codec.channels,
992 codec.rate);
993 } else {
994 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
995 "Channel::Init() %s (%d/%d/%" PRIuS
996 "/%d) has been "
997 "added to the RTP/RTCP receiver",
998 codec.plname, codec.pltype, codec.plfreq, codec.channels,
999 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001000 }
1001
kwiberg55b97fe2016-01-28 05:22:45 -08001002 // Ensure that PCMU is used as default codec on the sending side
1003 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1004 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001005 }
1006
kwiberg55b97fe2016-01-28 05:22:45 -08001007 // Register default PT for outband 'telephone-event'
1008 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001009 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
1010 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001011 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1012 "Channel::Init() failed to register outband "
1013 "'telephone-event' (%d/%d) correctly",
1014 codec.pltype, codec.plfreq);
1015 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001016 }
1017
kwiberg55b97fe2016-01-28 05:22:45 -08001018 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001019 if (!codec_manager_.RegisterEncoder(codec) ||
1020 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1021 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec) ||
1022 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001023 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1024 "Channel::Init() failed to register CN (%d/%d) "
1025 "correctly - 1",
1026 codec.pltype, codec.plfreq);
1027 }
1028 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001029#ifdef WEBRTC_CODEC_RED
kwiberg55b97fe2016-01-28 05:22:45 -08001030 // Register RED to the receiving side of the ACM.
1031 // We will not receive an OnInitializeDecoder() callback for RED.
1032 if (!STR_CASE_CMP(codec.plname, "RED")) {
kwibergc8d071e2016-04-06 12:22:38 -07001033 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001034 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1035 "Channel::Init() failed to register RED (%d/%d) "
1036 "correctly",
1037 codec.pltype, codec.plfreq);
1038 }
1039 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001040#endif
kwiberg55b97fe2016-01-28 05:22:45 -08001041 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001042
kwiberg55b97fe2016-01-28 05:22:45 -08001043 if (rx_audioproc_->noise_suppression()->set_level(kDefaultNsMode) != 0) {
1044 LOG(LS_ERROR) << "noise_suppression()->set_level(kDefaultNsMode) failed.";
1045 return -1;
1046 }
1047 if (rx_audioproc_->gain_control()->set_mode(kDefaultRxAgcMode) != 0) {
1048 LOG(LS_ERROR) << "gain_control()->set_mode(kDefaultRxAgcMode) failed.";
1049 return -1;
1050 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001051
kwiberg55b97fe2016-01-28 05:22:45 -08001052 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001053}
1054
kwiberg55b97fe2016-01-28 05:22:45 -08001055int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1056 OutputMixer& outputMixer,
1057 voe::TransmitMixer& transmitMixer,
1058 ProcessThread& moduleProcessThread,
1059 AudioDeviceModule& audioDeviceModule,
1060 VoiceEngineObserver* voiceEngineObserver,
1061 rtc::CriticalSection* callbackCritSect) {
1062 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1063 "Channel::SetEngineInformation()");
1064 _engineStatisticsPtr = &engineStatistics;
1065 _outputMixerPtr = &outputMixer;
1066 _transmitMixerPtr = &transmitMixer,
1067 _moduleProcessThreadPtr = &moduleProcessThread;
1068 _audioDeviceModulePtr = &audioDeviceModule;
1069 _voiceEngineObserverPtr = voiceEngineObserver;
1070 _callbackCritSectPtr = callbackCritSect;
1071 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001072}
1073
kwiberg55b97fe2016-01-28 05:22:45 -08001074int32_t Channel::UpdateLocalTimeStamp() {
1075 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1076 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001077}
1078
kwibergb7f89d62016-02-17 10:04:18 -08001079void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001080 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001081 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001082}
1083
kwiberg55b97fe2016-01-28 05:22:45 -08001084int32_t Channel::StartPlayout() {
1085 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1086 "Channel::StartPlayout()");
1087 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001088 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001089 }
1090
1091 if (!_externalMixing) {
1092 // Add participant as candidates for mixing.
1093 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1094 _engineStatisticsPtr->SetLastError(
1095 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1096 "StartPlayout() failed to add participant to mixer");
1097 return -1;
1098 }
1099 }
1100
1101 channel_state_.SetPlaying(true);
1102 if (RegisterFilePlayingToMixer() != 0)
1103 return -1;
1104
1105 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001106}
1107
kwiberg55b97fe2016-01-28 05:22:45 -08001108int32_t Channel::StopPlayout() {
1109 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1110 "Channel::StopPlayout()");
1111 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001112 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001113 }
1114
1115 if (!_externalMixing) {
1116 // Remove participant as candidates for mixing
1117 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1118 _engineStatisticsPtr->SetLastError(
1119 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1120 "StopPlayout() failed to remove participant from mixer");
1121 return -1;
1122 }
1123 }
1124
1125 channel_state_.SetPlaying(false);
1126 _outputAudioLevel.Clear();
1127
1128 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001129}
1130
kwiberg55b97fe2016-01-28 05:22:45 -08001131int32_t Channel::StartSend() {
1132 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1133 "Channel::StartSend()");
1134 // Resume the previous sequence number which was reset by StopSend().
1135 // This needs to be done before |sending| is set to true.
1136 if (send_sequence_number_)
1137 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001138
kwiberg55b97fe2016-01-28 05:22:45 -08001139 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001140 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001141 }
1142 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001143
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001144 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001145 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1146 _engineStatisticsPtr->SetLastError(
1147 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1148 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001149 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001150 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001151 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001152 return -1;
1153 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001154
kwiberg55b97fe2016-01-28 05:22:45 -08001155 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001156}
1157
kwiberg55b97fe2016-01-28 05:22:45 -08001158int32_t Channel::StopSend() {
1159 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1160 "Channel::StopSend()");
1161 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001162 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001163 }
1164 channel_state_.SetSending(false);
1165
1166 // Store the sequence number to be able to pick up the same sequence for
1167 // the next StartSend(). This is needed for restarting device, otherwise
1168 // it might cause libSRTP to complain about packets being replayed.
1169 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1170 // CL is landed. See issue
1171 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1172 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1173
1174 // Reset sending SSRC and sequence number and triggers direct transmission
1175 // of RTCP BYE
1176 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1177 _engineStatisticsPtr->SetLastError(
1178 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1179 "StartSend() RTP/RTCP failed to stop sending");
1180 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001181 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001182
1183 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001184}
1185
kwiberg55b97fe2016-01-28 05:22:45 -08001186int32_t Channel::StartReceiving() {
1187 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1188 "Channel::StartReceiving()");
1189 if (channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001190 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001191 }
1192 channel_state_.SetReceiving(true);
1193 _numberOfDiscardedPackets = 0;
1194 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001195}
1196
kwiberg55b97fe2016-01-28 05:22:45 -08001197int32_t Channel::StopReceiving() {
1198 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1199 "Channel::StopReceiving()");
1200 if (!channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001201 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001202 }
1203
1204 channel_state_.SetReceiving(false);
1205 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001206}
1207
kwiberg55b97fe2016-01-28 05:22:45 -08001208int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1209 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1210 "Channel::RegisterVoiceEngineObserver()");
1211 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001212
kwiberg55b97fe2016-01-28 05:22:45 -08001213 if (_voiceEngineObserverPtr) {
1214 _engineStatisticsPtr->SetLastError(
1215 VE_INVALID_OPERATION, kTraceError,
1216 "RegisterVoiceEngineObserver() observer already enabled");
1217 return -1;
1218 }
1219 _voiceEngineObserverPtr = &observer;
1220 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001221}
1222
kwiberg55b97fe2016-01-28 05:22:45 -08001223int32_t Channel::DeRegisterVoiceEngineObserver() {
1224 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1225 "Channel::DeRegisterVoiceEngineObserver()");
1226 rtc::CritScope cs(&_callbackCritSect);
1227
1228 if (!_voiceEngineObserverPtr) {
1229 _engineStatisticsPtr->SetLastError(
1230 VE_INVALID_OPERATION, kTraceWarning,
1231 "DeRegisterVoiceEngineObserver() observer already disabled");
1232 return 0;
1233 }
1234 _voiceEngineObserverPtr = NULL;
1235 return 0;
1236}
1237
1238int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001239 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001240 if (send_codec) {
1241 codec = *send_codec;
1242 return 0;
1243 }
1244 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001245}
1246
kwiberg55b97fe2016-01-28 05:22:45 -08001247int32_t Channel::GetRecCodec(CodecInst& codec) {
1248 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001249}
1250
kwiberg55b97fe2016-01-28 05:22:45 -08001251int32_t Channel::SetSendCodec(const CodecInst& codec) {
1252 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1253 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001254
kwibergc8d071e2016-04-06 12:22:38 -07001255 if (!codec_manager_.RegisterEncoder(codec) ||
1256 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001257 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1258 "SetSendCodec() failed to register codec to ACM");
1259 return -1;
1260 }
1261
1262 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1263 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1264 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1265 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1266 "SetSendCodec() failed to register codec to"
1267 " RTP/RTCP module");
1268 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001269 }
kwiberg55b97fe2016-01-28 05:22:45 -08001270 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001271
kwiberg55b97fe2016-01-28 05:22:45 -08001272 if (_rtpRtcpModule->SetAudioPacketSize(codec.pacsize) != 0) {
1273 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1274 "SetSendCodec() failed to set audio packet size");
1275 return -1;
1276 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001277
kwiberg55b97fe2016-01-28 05:22:45 -08001278 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001279}
1280
Ivo Creusenadf89b72015-04-29 16:03:33 +02001281void Channel::SetBitRate(int bitrate_bps) {
1282 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1283 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
1284 audio_coding_->SetBitRate(bitrate_bps);
1285}
1286
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001287void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue@webrtc.org74aaf292014-07-16 21:28:26 +00001288 network_predictor_->UpdatePacketLossRate(fraction_lost);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001289 uint8_t average_fraction_loss = network_predictor_->GetLossRate();
1290
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001291 // Normalizes rate to 0 - 100.
kwiberg55b97fe2016-01-28 05:22:45 -08001292 if (audio_coding_->SetPacketLossRate(100 * average_fraction_loss / 255) !=
1293 0) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001294 assert(false); // This should not happen.
1295 }
1296}
1297
kwiberg55b97fe2016-01-28 05:22:45 -08001298int32_t Channel::SetVADStatus(bool enableVAD,
1299 ACMVADMode mode,
1300 bool disableDTX) {
1301 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1302 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001303 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1304 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1305 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001306 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1307 kTraceError,
1308 "SetVADStatus() failed to set VAD");
1309 return -1;
1310 }
1311 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001312}
1313
kwiberg55b97fe2016-01-28 05:22:45 -08001314int32_t Channel::GetVADStatus(bool& enabledVAD,
1315 ACMVADMode& mode,
1316 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001317 const auto* params = codec_manager_.GetStackParams();
1318 enabledVAD = params->use_cng;
1319 mode = params->vad_mode;
1320 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001321 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001322}
1323
kwiberg55b97fe2016-01-28 05:22:45 -08001324int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1325 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1326 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001327
kwiberg55b97fe2016-01-28 05:22:45 -08001328 if (channel_state_.Get().playing) {
1329 _engineStatisticsPtr->SetLastError(
1330 VE_ALREADY_PLAYING, kTraceError,
1331 "SetRecPayloadType() unable to set PT while playing");
1332 return -1;
1333 }
1334 if (channel_state_.Get().receiving) {
1335 _engineStatisticsPtr->SetLastError(
1336 VE_ALREADY_LISTENING, kTraceError,
1337 "SetRecPayloadType() unable to set PT while listening");
1338 return -1;
1339 }
1340
1341 if (codec.pltype == -1) {
1342 // De-register the selected codec (RTP/RTCP module and ACM)
1343
1344 int8_t pltype(-1);
1345 CodecInst rxCodec = codec;
1346
1347 // Get payload type for the given codec
1348 rtp_payload_registry_->ReceivePayloadType(
1349 rxCodec.plname, rxCodec.plfreq, rxCodec.channels,
1350 (rxCodec.rate < 0) ? 0 : rxCodec.rate, &pltype);
1351 rxCodec.pltype = pltype;
1352
1353 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1354 _engineStatisticsPtr->SetLastError(
1355 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1356 "SetRecPayloadType() RTP/RTCP-module deregistration "
1357 "failed");
1358 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001359 }
kwiberg55b97fe2016-01-28 05:22:45 -08001360 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1361 _engineStatisticsPtr->SetLastError(
1362 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1363 "SetRecPayloadType() ACM deregistration failed - 1");
1364 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001365 }
kwiberg55b97fe2016-01-28 05:22:45 -08001366 return 0;
1367 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001368
kwiberg55b97fe2016-01-28 05:22:45 -08001369 if (rtp_receiver_->RegisterReceivePayload(
1370 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1371 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1372 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001373 // TODO(kwiberg): Retrying is probably not necessary, since
1374 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001375 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001376 if (rtp_receiver_->RegisterReceivePayload(
kwiberg55b97fe2016-01-28 05:22:45 -08001377 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1378 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1379 _engineStatisticsPtr->SetLastError(
1380 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1381 "SetRecPayloadType() RTP/RTCP-module registration failed");
1382 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001383 }
kwiberg55b97fe2016-01-28 05:22:45 -08001384 }
kwibergc8d071e2016-04-06 12:22:38 -07001385 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001386 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergc8d071e2016-04-06 12:22:38 -07001387 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001388 _engineStatisticsPtr->SetLastError(
1389 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1390 "SetRecPayloadType() ACM registration failed - 1");
1391 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001392 }
kwiberg55b97fe2016-01-28 05:22:45 -08001393 }
1394 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001395}
1396
kwiberg55b97fe2016-01-28 05:22:45 -08001397int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1398 int8_t payloadType(-1);
1399 if (rtp_payload_registry_->ReceivePayloadType(
1400 codec.plname, codec.plfreq, codec.channels,
1401 (codec.rate < 0) ? 0 : codec.rate, &payloadType) != 0) {
1402 _engineStatisticsPtr->SetLastError(
1403 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1404 "GetRecPayloadType() failed to retrieve RX payload type");
1405 return -1;
1406 }
1407 codec.pltype = payloadType;
1408 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001409}
1410
kwiberg55b97fe2016-01-28 05:22:45 -08001411int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1412 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1413 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001414
kwiberg55b97fe2016-01-28 05:22:45 -08001415 CodecInst codec;
1416 int32_t samplingFreqHz(-1);
1417 const size_t kMono = 1;
1418 if (frequency == kFreq32000Hz)
1419 samplingFreqHz = 32000;
1420 else if (frequency == kFreq16000Hz)
1421 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001422
kwiberg55b97fe2016-01-28 05:22:45 -08001423 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1424 _engineStatisticsPtr->SetLastError(
1425 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1426 "SetSendCNPayloadType() failed to retrieve default CN codec "
1427 "settings");
1428 return -1;
1429 }
1430
1431 // Modify the payload type (must be set to dynamic range)
1432 codec.pltype = type;
1433
kwibergc8d071e2016-04-06 12:22:38 -07001434 if (!codec_manager_.RegisterEncoder(codec) ||
1435 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001436 _engineStatisticsPtr->SetLastError(
1437 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1438 "SetSendCNPayloadType() failed to register CN to ACM");
1439 return -1;
1440 }
1441
1442 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1443 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1444 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1445 _engineStatisticsPtr->SetLastError(
1446 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1447 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1448 "module");
1449 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001450 }
kwiberg55b97fe2016-01-28 05:22:45 -08001451 }
1452 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001453}
1454
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001455int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001456 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001457 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001458
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001459 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001460 _engineStatisticsPtr->SetLastError(
1461 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001462 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001463 return -1;
1464 }
1465 return 0;
1466}
1467
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001468int Channel::SetOpusDtx(bool enable_dtx) {
1469 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1470 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001471 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001472 : audio_coding_->DisableOpusDtx();
1473 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001474 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1475 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001476 return -1;
1477 }
1478 return 0;
1479}
1480
mflodman3d7db262016-04-29 00:57:13 -07001481int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001482 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001483 "Channel::RegisterExternalTransport()");
1484
kwiberg55b97fe2016-01-28 05:22:45 -08001485 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001486 if (_externalTransport) {
1487 _engineStatisticsPtr->SetLastError(
1488 VE_INVALID_OPERATION, kTraceError,
1489 "RegisterExternalTransport() external transport already enabled");
1490 return -1;
1491 }
1492 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001493 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001494 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001495}
1496
kwiberg55b97fe2016-01-28 05:22:45 -08001497int32_t Channel::DeRegisterExternalTransport() {
1498 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1499 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001500
kwiberg55b97fe2016-01-28 05:22:45 -08001501 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001502 if (_transportPtr) {
1503 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1504 "DeRegisterExternalTransport() all transport is disabled");
1505 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001506 _engineStatisticsPtr->SetLastError(
1507 VE_INVALID_OPERATION, kTraceWarning,
1508 "DeRegisterExternalTransport() external transport already "
1509 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001510 }
1511 _externalTransport = false;
1512 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001513 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001514}
1515
mflodman3d7db262016-04-29 00:57:13 -07001516int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001517 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001518 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001519 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001520 "Channel::ReceivedRTPPacket()");
1521
1522 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001523 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001524
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001525 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001526 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1527 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1528 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001529 return -1;
1530 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001531 header.payload_type_frequency =
1532 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001533 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001534 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001535 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001536 rtp_receive_statistics_->IncomingPacket(
1537 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001538 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001539
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001540 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001541}
1542
1543bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001544 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001545 const RTPHeader& header,
1546 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001547 if (rtp_payload_registry_->IsRtx(header)) {
1548 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001549 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001550 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001551 assert(packet_length >= header.headerLength);
1552 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001553 PayloadUnion payload_specific;
1554 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001555 &payload_specific)) {
1556 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001557 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001558 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1559 payload_specific, in_order);
1560}
1561
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001562bool Channel::HandleRtxPacket(const uint8_t* packet,
1563 size_t packet_length,
1564 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001565 if (!rtp_payload_registry_->IsRtx(header))
1566 return false;
1567
1568 // Remove the RTX header and parse the original RTP header.
1569 if (packet_length < header.headerLength)
1570 return false;
1571 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1572 return false;
1573 if (restored_packet_in_use_) {
1574 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1575 "Multiple RTX headers detected, dropping packet");
1576 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001577 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001578 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001579 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1580 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001581 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1582 "Incoming RTX packet: invalid RTP header");
1583 return false;
1584 }
1585 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001586 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001587 restored_packet_in_use_ = false;
1588 return ret;
1589}
1590
1591bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1592 StreamStatistician* statistician =
1593 rtp_receive_statistics_->GetStatistician(header.ssrc);
1594 if (!statistician)
1595 return false;
1596 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001597}
1598
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001599bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1600 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001601 // Retransmissions are handled separately if RTX is enabled.
1602 if (rtp_payload_registry_->RtxEnabled())
1603 return false;
1604 StreamStatistician* statistician =
1605 rtp_receive_statistics_->GetStatistician(header.ssrc);
1606 if (!statistician)
1607 return false;
1608 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001609 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001610 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001611 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001612}
1613
mflodman3d7db262016-04-29 00:57:13 -07001614int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001615 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001616 "Channel::ReceivedRTCPPacket()");
1617 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001618 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001619
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001620 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001621 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001622 _engineStatisticsPtr->SetLastError(
1623 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1624 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1625 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001626
Minyue2013aec2015-05-13 14:14:42 +02001627 int64_t rtt = GetRTT(true);
1628 if (rtt == 0) {
1629 // Waiting for valid RTT.
1630 return 0;
1631 }
1632 uint32_t ntp_secs = 0;
1633 uint32_t ntp_frac = 0;
1634 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001635 if (0 !=
1636 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1637 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001638 // Waiting for RTCP.
1639 return 0;
1640 }
1641
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001642 {
tommi31fc21f2016-01-21 10:37:37 -08001643 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001644 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001645 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001646 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001647}
1648
niklase@google.com470e71d2011-07-07 08:21:25 +00001649int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001650 bool loop,
1651 FileFormats format,
1652 int startPosition,
1653 float volumeScaling,
1654 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001655 const CodecInst* codecInst) {
1656 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1657 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1658 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1659 "stopPosition=%d)",
1660 fileName, loop, format, volumeScaling, startPosition,
1661 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001662
kwiberg55b97fe2016-01-28 05:22:45 -08001663 if (channel_state_.Get().output_file_playing) {
1664 _engineStatisticsPtr->SetLastError(
1665 VE_ALREADY_PLAYING, kTraceError,
1666 "StartPlayingFileLocally() is already playing");
1667 return -1;
1668 }
1669
1670 {
1671 rtc::CritScope cs(&_fileCritSect);
1672
1673 if (_outputFilePlayerPtr) {
1674 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1675 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1676 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001677 }
1678
kwiberg55b97fe2016-01-28 05:22:45 -08001679 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1680 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001681
kwiberg55b97fe2016-01-28 05:22:45 -08001682 if (_outputFilePlayerPtr == NULL) {
1683 _engineStatisticsPtr->SetLastError(
1684 VE_INVALID_ARGUMENT, kTraceError,
1685 "StartPlayingFileLocally() filePlayer format is not correct");
1686 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001687 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001688
kwiberg55b97fe2016-01-28 05:22:45 -08001689 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001690
kwiberg55b97fe2016-01-28 05:22:45 -08001691 if (_outputFilePlayerPtr->StartPlayingFile(
1692 fileName, loop, startPosition, volumeScaling, notificationTime,
1693 stopPosition, (const CodecInst*)codecInst) != 0) {
1694 _engineStatisticsPtr->SetLastError(
1695 VE_BAD_FILE, kTraceError,
1696 "StartPlayingFile() failed to start file playout");
1697 _outputFilePlayerPtr->StopPlayingFile();
1698 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1699 _outputFilePlayerPtr = NULL;
1700 return -1;
1701 }
1702 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1703 channel_state_.SetOutputFilePlaying(true);
1704 }
1705
1706 if (RegisterFilePlayingToMixer() != 0)
1707 return -1;
1708
1709 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001710}
1711
1712int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001713 FileFormats format,
1714 int startPosition,
1715 float volumeScaling,
1716 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001717 const CodecInst* codecInst) {
1718 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1719 "Channel::StartPlayingFileLocally(format=%d,"
1720 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1721 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001722
kwiberg55b97fe2016-01-28 05:22:45 -08001723 if (stream == NULL) {
1724 _engineStatisticsPtr->SetLastError(
1725 VE_BAD_FILE, kTraceError,
1726 "StartPlayingFileLocally() NULL as input stream");
1727 return -1;
1728 }
1729
1730 if (channel_state_.Get().output_file_playing) {
1731 _engineStatisticsPtr->SetLastError(
1732 VE_ALREADY_PLAYING, kTraceError,
1733 "StartPlayingFileLocally() is already playing");
1734 return -1;
1735 }
1736
1737 {
1738 rtc::CritScope cs(&_fileCritSect);
1739
1740 // Destroy the old instance
1741 if (_outputFilePlayerPtr) {
1742 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1743 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1744 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001745 }
1746
kwiberg55b97fe2016-01-28 05:22:45 -08001747 // Create the instance
1748 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1749 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001750
kwiberg55b97fe2016-01-28 05:22:45 -08001751 if (_outputFilePlayerPtr == NULL) {
1752 _engineStatisticsPtr->SetLastError(
1753 VE_INVALID_ARGUMENT, kTraceError,
1754 "StartPlayingFileLocally() filePlayer format isnot correct");
1755 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001756 }
1757
kwiberg55b97fe2016-01-28 05:22:45 -08001758 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001759
kwiberg55b97fe2016-01-28 05:22:45 -08001760 if (_outputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1761 volumeScaling, notificationTime,
1762 stopPosition, codecInst) != 0) {
1763 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1764 "StartPlayingFile() failed to "
1765 "start file playout");
1766 _outputFilePlayerPtr->StopPlayingFile();
1767 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1768 _outputFilePlayerPtr = NULL;
1769 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001770 }
kwiberg55b97fe2016-01-28 05:22:45 -08001771 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1772 channel_state_.SetOutputFilePlaying(true);
1773 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001774
kwiberg55b97fe2016-01-28 05:22:45 -08001775 if (RegisterFilePlayingToMixer() != 0)
1776 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001777
kwiberg55b97fe2016-01-28 05:22:45 -08001778 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001779}
1780
kwiberg55b97fe2016-01-28 05:22:45 -08001781int Channel::StopPlayingFileLocally() {
1782 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1783 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001784
kwiberg55b97fe2016-01-28 05:22:45 -08001785 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001786 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001787 }
1788
1789 {
1790 rtc::CritScope cs(&_fileCritSect);
1791
1792 if (_outputFilePlayerPtr->StopPlayingFile() != 0) {
1793 _engineStatisticsPtr->SetLastError(
1794 VE_STOP_RECORDING_FAILED, kTraceError,
1795 "StopPlayingFile() could not stop playing");
1796 return -1;
1797 }
1798 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1799 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1800 _outputFilePlayerPtr = NULL;
1801 channel_state_.SetOutputFilePlaying(false);
1802 }
1803 // _fileCritSect cannot be taken while calling
1804 // SetAnonymousMixibilityStatus. Refer to comments in
1805 // StartPlayingFileLocally(const char* ...) for more details.
1806 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1807 _engineStatisticsPtr->SetLastError(
1808 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1809 "StopPlayingFile() failed to stop participant from playing as"
1810 "file in the mixer");
1811 return -1;
1812 }
1813
1814 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001815}
1816
kwiberg55b97fe2016-01-28 05:22:45 -08001817int Channel::IsPlayingFileLocally() const {
1818 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001819}
1820
kwiberg55b97fe2016-01-28 05:22:45 -08001821int Channel::RegisterFilePlayingToMixer() {
1822 // Return success for not registering for file playing to mixer if:
1823 // 1. playing file before playout is started on that channel.
1824 // 2. starting playout without file playing on that channel.
1825 if (!channel_state_.Get().playing ||
1826 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001827 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001828 }
1829
1830 // |_fileCritSect| cannot be taken while calling
1831 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1832 // frames can be pulled by the mixer. Since the frames are generated from
1833 // the file, _fileCritSect will be taken. This would result in a deadlock.
1834 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1835 channel_state_.SetOutputFilePlaying(false);
1836 rtc::CritScope cs(&_fileCritSect);
1837 _engineStatisticsPtr->SetLastError(
1838 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1839 "StartPlayingFile() failed to add participant as file to mixer");
1840 _outputFilePlayerPtr->StopPlayingFile();
1841 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1842 _outputFilePlayerPtr = NULL;
1843 return -1;
1844 }
1845
1846 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001847}
1848
niklase@google.com470e71d2011-07-07 08:21:25 +00001849int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001850 bool loop,
1851 FileFormats format,
1852 int startPosition,
1853 float volumeScaling,
1854 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001855 const CodecInst* codecInst) {
1856 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1857 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1858 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1859 "stopPosition=%d)",
1860 fileName, loop, format, volumeScaling, startPosition,
1861 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001862
kwiberg55b97fe2016-01-28 05:22:45 -08001863 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001864
kwiberg55b97fe2016-01-28 05:22:45 -08001865 if (channel_state_.Get().input_file_playing) {
1866 _engineStatisticsPtr->SetLastError(
1867 VE_ALREADY_PLAYING, kTraceWarning,
1868 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001869 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001870 }
1871
1872 // Destroy the old instance
1873 if (_inputFilePlayerPtr) {
1874 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1875 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1876 _inputFilePlayerPtr = NULL;
1877 }
1878
1879 // Create the instance
1880 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1881 (const FileFormats)format);
1882
1883 if (_inputFilePlayerPtr == NULL) {
1884 _engineStatisticsPtr->SetLastError(
1885 VE_INVALID_ARGUMENT, kTraceError,
1886 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1887 return -1;
1888 }
1889
1890 const uint32_t notificationTime(0);
1891
1892 if (_inputFilePlayerPtr->StartPlayingFile(
1893 fileName, loop, startPosition, volumeScaling, notificationTime,
1894 stopPosition, (const CodecInst*)codecInst) != 0) {
1895 _engineStatisticsPtr->SetLastError(
1896 VE_BAD_FILE, kTraceError,
1897 "StartPlayingFile() failed to start file playout");
1898 _inputFilePlayerPtr->StopPlayingFile();
1899 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1900 _inputFilePlayerPtr = NULL;
1901 return -1;
1902 }
1903 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1904 channel_state_.SetInputFilePlaying(true);
1905
1906 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001907}
1908
1909int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001910 FileFormats format,
1911 int startPosition,
1912 float volumeScaling,
1913 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001914 const CodecInst* codecInst) {
1915 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1916 "Channel::StartPlayingFileAsMicrophone(format=%d, "
1917 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1918 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001919
kwiberg55b97fe2016-01-28 05:22:45 -08001920 if (stream == NULL) {
1921 _engineStatisticsPtr->SetLastError(
1922 VE_BAD_FILE, kTraceError,
1923 "StartPlayingFileAsMicrophone NULL as input stream");
1924 return -1;
1925 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001926
kwiberg55b97fe2016-01-28 05:22:45 -08001927 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001928
kwiberg55b97fe2016-01-28 05:22:45 -08001929 if (channel_state_.Get().input_file_playing) {
1930 _engineStatisticsPtr->SetLastError(
1931 VE_ALREADY_PLAYING, kTraceWarning,
1932 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001933 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001934 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001935
kwiberg55b97fe2016-01-28 05:22:45 -08001936 // Destroy the old instance
1937 if (_inputFilePlayerPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001938 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1939 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1940 _inputFilePlayerPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001941 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001942
kwiberg55b97fe2016-01-28 05:22:45 -08001943 // Create the instance
1944 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1945 (const FileFormats)format);
1946
1947 if (_inputFilePlayerPtr == NULL) {
1948 _engineStatisticsPtr->SetLastError(
1949 VE_INVALID_ARGUMENT, kTraceError,
1950 "StartPlayingInputFile() filePlayer format isnot correct");
1951 return -1;
1952 }
1953
1954 const uint32_t notificationTime(0);
1955
1956 if (_inputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1957 volumeScaling, notificationTime,
1958 stopPosition, codecInst) != 0) {
1959 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1960 "StartPlayingFile() failed to start "
1961 "file playout");
1962 _inputFilePlayerPtr->StopPlayingFile();
1963 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1964 _inputFilePlayerPtr = NULL;
1965 return -1;
1966 }
1967
1968 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1969 channel_state_.SetInputFilePlaying(true);
1970
1971 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001972}
1973
kwiberg55b97fe2016-01-28 05:22:45 -08001974int Channel::StopPlayingFileAsMicrophone() {
1975 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1976 "Channel::StopPlayingFileAsMicrophone()");
1977
1978 rtc::CritScope cs(&_fileCritSect);
1979
1980 if (!channel_state_.Get().input_file_playing) {
1981 return 0;
1982 }
1983
1984 if (_inputFilePlayerPtr->StopPlayingFile() != 0) {
1985 _engineStatisticsPtr->SetLastError(
1986 VE_STOP_RECORDING_FAILED, kTraceError,
1987 "StopPlayingFile() could not stop playing");
1988 return -1;
1989 }
1990 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1991 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1992 _inputFilePlayerPtr = NULL;
1993 channel_state_.SetInputFilePlaying(false);
1994
1995 return 0;
1996}
1997
1998int Channel::IsPlayingFileAsMicrophone() const {
1999 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002000}
2001
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002002int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002003 const CodecInst* codecInst) {
2004 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2005 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002006
kwiberg55b97fe2016-01-28 05:22:45 -08002007 if (_outputFileRecording) {
2008 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2009 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002010 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002011 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002012
kwiberg55b97fe2016-01-28 05:22:45 -08002013 FileFormats format;
2014 const uint32_t notificationTime(0); // Not supported in VoE
2015 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002016
kwiberg55b97fe2016-01-28 05:22:45 -08002017 if ((codecInst != NULL) &&
2018 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2019 _engineStatisticsPtr->SetLastError(
2020 VE_BAD_ARGUMENT, kTraceError,
2021 "StartRecordingPlayout() invalid compression");
2022 return (-1);
2023 }
2024 if (codecInst == NULL) {
2025 format = kFileFormatPcm16kHzFile;
2026 codecInst = &dummyCodec;
2027 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2028 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2029 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2030 format = kFileFormatWavFile;
2031 } else {
2032 format = kFileFormatCompressedFile;
2033 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002034
kwiberg55b97fe2016-01-28 05:22:45 -08002035 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002036
kwiberg55b97fe2016-01-28 05:22:45 -08002037 // Destroy the old instance
2038 if (_outputFileRecorderPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002039 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2040 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2041 _outputFileRecorderPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08002042 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002043
kwiberg55b97fe2016-01-28 05:22:45 -08002044 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2045 _outputFileRecorderId, (const FileFormats)format);
2046 if (_outputFileRecorderPtr == NULL) {
2047 _engineStatisticsPtr->SetLastError(
2048 VE_INVALID_ARGUMENT, kTraceError,
2049 "StartRecordingPlayout() fileRecorder format isnot correct");
2050 return -1;
2051 }
2052
2053 if (_outputFileRecorderPtr->StartRecordingAudioFile(
2054 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2055 _engineStatisticsPtr->SetLastError(
2056 VE_BAD_FILE, kTraceError,
2057 "StartRecordingAudioFile() failed to start file recording");
2058 _outputFileRecorderPtr->StopRecording();
2059 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2060 _outputFileRecorderPtr = NULL;
2061 return -1;
2062 }
2063 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2064 _outputFileRecording = true;
2065
2066 return 0;
2067}
2068
2069int Channel::StartRecordingPlayout(OutStream* stream,
2070 const CodecInst* codecInst) {
2071 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2072 "Channel::StartRecordingPlayout()");
2073
2074 if (_outputFileRecording) {
2075 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2076 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002077 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002078 }
2079
2080 FileFormats format;
2081 const uint32_t notificationTime(0); // Not supported in VoE
2082 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2083
2084 if (codecInst != NULL && codecInst->channels != 1) {
2085 _engineStatisticsPtr->SetLastError(
2086 VE_BAD_ARGUMENT, kTraceError,
2087 "StartRecordingPlayout() invalid compression");
2088 return (-1);
2089 }
2090 if (codecInst == NULL) {
2091 format = kFileFormatPcm16kHzFile;
2092 codecInst = &dummyCodec;
2093 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2094 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2095 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2096 format = kFileFormatWavFile;
2097 } else {
2098 format = kFileFormatCompressedFile;
2099 }
2100
2101 rtc::CritScope cs(&_fileCritSect);
2102
2103 // Destroy the old instance
2104 if (_outputFileRecorderPtr) {
2105 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2106 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2107 _outputFileRecorderPtr = NULL;
2108 }
2109
2110 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2111 _outputFileRecorderId, (const FileFormats)format);
2112 if (_outputFileRecorderPtr == NULL) {
2113 _engineStatisticsPtr->SetLastError(
2114 VE_INVALID_ARGUMENT, kTraceError,
2115 "StartRecordingPlayout() fileRecorder format isnot correct");
2116 return -1;
2117 }
2118
2119 if (_outputFileRecorderPtr->StartRecordingAudioFile(*stream, *codecInst,
2120 notificationTime) != 0) {
2121 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2122 "StartRecordingPlayout() failed to "
2123 "start file recording");
2124 _outputFileRecorderPtr->StopRecording();
2125 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2126 _outputFileRecorderPtr = NULL;
2127 return -1;
2128 }
2129
2130 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2131 _outputFileRecording = true;
2132
2133 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002134}
2135
kwiberg55b97fe2016-01-28 05:22:45 -08002136int Channel::StopRecordingPlayout() {
2137 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2138 "Channel::StopRecordingPlayout()");
2139
2140 if (!_outputFileRecording) {
2141 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2142 "StopRecordingPlayout() isnot recording");
2143 return -1;
2144 }
2145
2146 rtc::CritScope cs(&_fileCritSect);
2147
2148 if (_outputFileRecorderPtr->StopRecording() != 0) {
2149 _engineStatisticsPtr->SetLastError(
2150 VE_STOP_RECORDING_FAILED, kTraceError,
2151 "StopRecording() could not stop recording");
2152 return (-1);
2153 }
2154 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2155 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2156 _outputFileRecorderPtr = NULL;
2157 _outputFileRecording = false;
2158
2159 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002160}
2161
kwiberg55b97fe2016-01-28 05:22:45 -08002162void Channel::SetMixWithMicStatus(bool mix) {
2163 rtc::CritScope cs(&_fileCritSect);
2164 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002165}
2166
kwiberg55b97fe2016-01-28 05:22:45 -08002167int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2168 int8_t currentLevel = _outputAudioLevel.Level();
2169 level = static_cast<int32_t>(currentLevel);
2170 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002171}
2172
kwiberg55b97fe2016-01-28 05:22:45 -08002173int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2174 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2175 level = static_cast<int32_t>(currentLevel);
2176 return 0;
2177}
2178
solenberg1c2af8e2016-03-24 10:36:00 -07002179int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002180 rtc::CritScope cs(&volume_settings_critsect_);
2181 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002182 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002183 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002184 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002185}
2186
solenberg1c2af8e2016-03-24 10:36:00 -07002187bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002188 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002189 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002190}
2191
kwiberg55b97fe2016-01-28 05:22:45 -08002192int Channel::SetOutputVolumePan(float left, float right) {
2193 rtc::CritScope cs(&volume_settings_critsect_);
2194 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002195 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002196 _panLeft = left;
2197 _panRight = right;
2198 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002199}
2200
kwiberg55b97fe2016-01-28 05:22:45 -08002201int Channel::GetOutputVolumePan(float& left, float& right) const {
2202 rtc::CritScope cs(&volume_settings_critsect_);
2203 left = _panLeft;
2204 right = _panRight;
2205 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002206}
2207
kwiberg55b97fe2016-01-28 05:22:45 -08002208int Channel::SetChannelOutputVolumeScaling(float scaling) {
2209 rtc::CritScope cs(&volume_settings_critsect_);
2210 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002211 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002212 _outputGain = scaling;
2213 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002214}
2215
kwiberg55b97fe2016-01-28 05:22:45 -08002216int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2217 rtc::CritScope cs(&volume_settings_critsect_);
2218 scaling = _outputGain;
2219 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002220}
2221
solenberg8842c3e2016-03-11 03:06:41 -08002222int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002223 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002224 "Channel::SendTelephoneEventOutband(...)");
2225 RTC_DCHECK_LE(0, event);
2226 RTC_DCHECK_GE(255, event);
2227 RTC_DCHECK_LE(0, duration_ms);
2228 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002229 if (!Sending()) {
2230 return -1;
2231 }
solenberg8842c3e2016-03-11 03:06:41 -08002232 if (_rtpRtcpModule->SendTelephoneEventOutband(
2233 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002234 _engineStatisticsPtr->SetLastError(
2235 VE_SEND_DTMF_FAILED, kTraceWarning,
2236 "SendTelephoneEventOutband() failed to send event");
2237 return -1;
2238 }
2239 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002240}
2241
solenberg31642aa2016-03-14 08:00:37 -07002242int Channel::SetSendTelephoneEventPayloadType(int payload_type) {
kwiberg55b97fe2016-01-28 05:22:45 -08002243 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002244 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002245 RTC_DCHECK_LE(0, payload_type);
2246 RTC_DCHECK_GE(127, payload_type);
2247 CodecInst codec = {0};
kwiberg55b97fe2016-01-28 05:22:45 -08002248 codec.plfreq = 8000;
solenberg31642aa2016-03-14 08:00:37 -07002249 codec.pltype = payload_type;
kwiberg55b97fe2016-01-28 05:22:45 -08002250 memcpy(codec.plname, "telephone-event", 16);
2251 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2252 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2253 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2254 _engineStatisticsPtr->SetLastError(
2255 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2256 "SetSendTelephoneEventPayloadType() failed to register send"
2257 "payload type");
2258 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002259 }
kwiberg55b97fe2016-01-28 05:22:45 -08002260 }
kwiberg55b97fe2016-01-28 05:22:45 -08002261 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002262}
2263
kwiberg55b97fe2016-01-28 05:22:45 -08002264int Channel::UpdateRxVadDetection(AudioFrame& audioFrame) {
2265 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2266 "Channel::UpdateRxVadDetection()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002267
kwiberg55b97fe2016-01-28 05:22:45 -08002268 int vadDecision = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002269
kwiberg55b97fe2016-01-28 05:22:45 -08002270 vadDecision = (audioFrame.vad_activity_ == AudioFrame::kVadActive) ? 1 : 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002271
kwiberg55b97fe2016-01-28 05:22:45 -08002272 if ((vadDecision != _oldVadDecision) && _rxVadObserverPtr) {
2273 OnRxVadDetected(vadDecision);
2274 _oldVadDecision = vadDecision;
2275 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002276
kwiberg55b97fe2016-01-28 05:22:45 -08002277 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2278 "Channel::UpdateRxVadDetection() => vadDecision=%d",
2279 vadDecision);
2280 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002281}
2282
kwiberg55b97fe2016-01-28 05:22:45 -08002283int Channel::RegisterRxVadObserver(VoERxVadCallback& observer) {
2284 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2285 "Channel::RegisterRxVadObserver()");
2286 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002287
kwiberg55b97fe2016-01-28 05:22:45 -08002288 if (_rxVadObserverPtr) {
2289 _engineStatisticsPtr->SetLastError(
2290 VE_INVALID_OPERATION, kTraceError,
2291 "RegisterRxVadObserver() observer already enabled");
2292 return -1;
2293 }
2294 _rxVadObserverPtr = &observer;
2295 _RxVadDetection = true;
2296 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002297}
2298
kwiberg55b97fe2016-01-28 05:22:45 -08002299int Channel::DeRegisterRxVadObserver() {
2300 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2301 "Channel::DeRegisterRxVadObserver()");
2302 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002303
kwiberg55b97fe2016-01-28 05:22:45 -08002304 if (!_rxVadObserverPtr) {
2305 _engineStatisticsPtr->SetLastError(
2306 VE_INVALID_OPERATION, kTraceWarning,
2307 "DeRegisterRxVadObserver() observer already disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00002308 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002309 }
2310 _rxVadObserverPtr = NULL;
2311 _RxVadDetection = false;
2312 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002313}
2314
kwiberg55b97fe2016-01-28 05:22:45 -08002315int Channel::VoiceActivityIndicator(int& activity) {
2316 activity = _sendFrameType;
2317 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002318}
2319
2320#ifdef WEBRTC_VOICE_ENGINE_AGC
2321
kwiberg55b97fe2016-01-28 05:22:45 -08002322int Channel::SetRxAgcStatus(bool enable, AgcModes mode) {
2323 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2324 "Channel::SetRxAgcStatus(enable=%d, mode=%d)", (int)enable,
2325 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002326
kwiberg55b97fe2016-01-28 05:22:45 -08002327 GainControl::Mode agcMode = kDefaultRxAgcMode;
2328 switch (mode) {
2329 case kAgcDefault:
2330 break;
2331 case kAgcUnchanged:
2332 agcMode = rx_audioproc_->gain_control()->mode();
2333 break;
2334 case kAgcFixedDigital:
2335 agcMode = GainControl::kFixedDigital;
2336 break;
2337 case kAgcAdaptiveDigital:
2338 agcMode = GainControl::kAdaptiveDigital;
2339 break;
2340 default:
2341 _engineStatisticsPtr->SetLastError(VE_INVALID_ARGUMENT, kTraceError,
2342 "SetRxAgcStatus() invalid Agc mode");
2343 return -1;
2344 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002345
kwiberg55b97fe2016-01-28 05:22:45 -08002346 if (rx_audioproc_->gain_control()->set_mode(agcMode) != 0) {
2347 _engineStatisticsPtr->SetLastError(
2348 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc mode");
2349 return -1;
2350 }
2351 if (rx_audioproc_->gain_control()->Enable(enable) != 0) {
2352 _engineStatisticsPtr->SetLastError(
2353 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc state");
2354 return -1;
2355 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002356
kwiberg55b97fe2016-01-28 05:22:45 -08002357 _rxAgcIsEnabled = enable;
2358 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002359
kwiberg55b97fe2016-01-28 05:22:45 -08002360 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002361}
2362
kwiberg55b97fe2016-01-28 05:22:45 -08002363int Channel::GetRxAgcStatus(bool& enabled, AgcModes& mode) {
2364 bool enable = rx_audioproc_->gain_control()->is_enabled();
2365 GainControl::Mode agcMode = rx_audioproc_->gain_control()->mode();
niklase@google.com470e71d2011-07-07 08:21:25 +00002366
kwiberg55b97fe2016-01-28 05:22:45 -08002367 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002368
kwiberg55b97fe2016-01-28 05:22:45 -08002369 switch (agcMode) {
2370 case GainControl::kFixedDigital:
2371 mode = kAgcFixedDigital;
2372 break;
2373 case GainControl::kAdaptiveDigital:
2374 mode = kAgcAdaptiveDigital;
2375 break;
2376 default:
2377 _engineStatisticsPtr->SetLastError(VE_APM_ERROR, kTraceError,
2378 "GetRxAgcStatus() invalid Agc mode");
2379 return -1;
2380 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002381
kwiberg55b97fe2016-01-28 05:22:45 -08002382 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002383}
2384
kwiberg55b97fe2016-01-28 05:22:45 -08002385int Channel::SetRxAgcConfig(AgcConfig config) {
2386 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2387 "Channel::SetRxAgcConfig()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002388
kwiberg55b97fe2016-01-28 05:22:45 -08002389 if (rx_audioproc_->gain_control()->set_target_level_dbfs(
2390 config.targetLeveldBOv) != 0) {
2391 _engineStatisticsPtr->SetLastError(
2392 VE_APM_ERROR, kTraceError,
2393 "SetRxAgcConfig() failed to set target peak |level|"
2394 "(or envelope) of the Agc");
2395 return -1;
2396 }
2397 if (rx_audioproc_->gain_control()->set_compression_gain_db(
2398 config.digitalCompressionGaindB) != 0) {
2399 _engineStatisticsPtr->SetLastError(
2400 VE_APM_ERROR, kTraceError,
2401 "SetRxAgcConfig() failed to set the range in |gain| the"
2402 " digital compression stage may apply");
2403 return -1;
2404 }
2405 if (rx_audioproc_->gain_control()->enable_limiter(config.limiterEnable) !=
2406 0) {
2407 _engineStatisticsPtr->SetLastError(
2408 VE_APM_ERROR, kTraceError,
2409 "SetRxAgcConfig() failed to set hard limiter to the signal");
2410 return -1;
2411 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002412
kwiberg55b97fe2016-01-28 05:22:45 -08002413 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002414}
2415
kwiberg55b97fe2016-01-28 05:22:45 -08002416int Channel::GetRxAgcConfig(AgcConfig& config) {
2417 config.targetLeveldBOv = rx_audioproc_->gain_control()->target_level_dbfs();
2418 config.digitalCompressionGaindB =
2419 rx_audioproc_->gain_control()->compression_gain_db();
2420 config.limiterEnable = rx_audioproc_->gain_control()->is_limiter_enabled();
niklase@google.com470e71d2011-07-07 08:21:25 +00002421
kwiberg55b97fe2016-01-28 05:22:45 -08002422 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002423}
2424
kwiberg55b97fe2016-01-28 05:22:45 -08002425#endif // #ifdef WEBRTC_VOICE_ENGINE_AGC
niklase@google.com470e71d2011-07-07 08:21:25 +00002426
2427#ifdef WEBRTC_VOICE_ENGINE_NR
2428
kwiberg55b97fe2016-01-28 05:22:45 -08002429int Channel::SetRxNsStatus(bool enable, NsModes mode) {
2430 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2431 "Channel::SetRxNsStatus(enable=%d, mode=%d)", (int)enable,
2432 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002433
kwiberg55b97fe2016-01-28 05:22:45 -08002434 NoiseSuppression::Level nsLevel = kDefaultNsMode;
2435 switch (mode) {
2436 case kNsDefault:
2437 break;
2438 case kNsUnchanged:
2439 nsLevel = rx_audioproc_->noise_suppression()->level();
2440 break;
2441 case kNsConference:
2442 nsLevel = NoiseSuppression::kHigh;
2443 break;
2444 case kNsLowSuppression:
2445 nsLevel = NoiseSuppression::kLow;
2446 break;
2447 case kNsModerateSuppression:
2448 nsLevel = NoiseSuppression::kModerate;
2449 break;
2450 case kNsHighSuppression:
2451 nsLevel = NoiseSuppression::kHigh;
2452 break;
2453 case kNsVeryHighSuppression:
2454 nsLevel = NoiseSuppression::kVeryHigh;
2455 break;
2456 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002457
kwiberg55b97fe2016-01-28 05:22:45 -08002458 if (rx_audioproc_->noise_suppression()->set_level(nsLevel) != 0) {
2459 _engineStatisticsPtr->SetLastError(
2460 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS level");
2461 return -1;
2462 }
2463 if (rx_audioproc_->noise_suppression()->Enable(enable) != 0) {
2464 _engineStatisticsPtr->SetLastError(
2465 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS state");
2466 return -1;
2467 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002468
kwiberg55b97fe2016-01-28 05:22:45 -08002469 _rxNsIsEnabled = enable;
2470 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002471
kwiberg55b97fe2016-01-28 05:22:45 -08002472 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002473}
2474
kwiberg55b97fe2016-01-28 05:22:45 -08002475int Channel::GetRxNsStatus(bool& enabled, NsModes& mode) {
2476 bool enable = rx_audioproc_->noise_suppression()->is_enabled();
2477 NoiseSuppression::Level ncLevel = rx_audioproc_->noise_suppression()->level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002478
kwiberg55b97fe2016-01-28 05:22:45 -08002479 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002480
kwiberg55b97fe2016-01-28 05:22:45 -08002481 switch (ncLevel) {
2482 case NoiseSuppression::kLow:
2483 mode = kNsLowSuppression;
2484 break;
2485 case NoiseSuppression::kModerate:
2486 mode = kNsModerateSuppression;
2487 break;
2488 case NoiseSuppression::kHigh:
2489 mode = kNsHighSuppression;
2490 break;
2491 case NoiseSuppression::kVeryHigh:
2492 mode = kNsVeryHighSuppression;
2493 break;
2494 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002495
kwiberg55b97fe2016-01-28 05:22:45 -08002496 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002497}
2498
kwiberg55b97fe2016-01-28 05:22:45 -08002499#endif // #ifdef WEBRTC_VOICE_ENGINE_NR
niklase@google.com470e71d2011-07-07 08:21:25 +00002500
kwiberg55b97fe2016-01-28 05:22:45 -08002501int Channel::SetLocalSSRC(unsigned int ssrc) {
2502 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2503 "Channel::SetLocalSSRC()");
2504 if (channel_state_.Get().sending) {
2505 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2506 "SetLocalSSRC() already sending");
2507 return -1;
2508 }
2509 _rtpRtcpModule->SetSSRC(ssrc);
2510 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002511}
2512
kwiberg55b97fe2016-01-28 05:22:45 -08002513int Channel::GetLocalSSRC(unsigned int& ssrc) {
2514 ssrc = _rtpRtcpModule->SSRC();
2515 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002516}
2517
kwiberg55b97fe2016-01-28 05:22:45 -08002518int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2519 ssrc = rtp_receiver_->SSRC();
2520 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002521}
2522
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002523int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002524 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002525 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002526}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002527
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002528int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2529 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002530 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2531 if (enable &&
2532 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2533 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002534 return -1;
2535 }
2536 return 0;
2537}
2538
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002539int Channel::SetSendAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2540 return SetSendRtpHeaderExtension(enable, kRtpExtensionAbsoluteSendTime, id);
2541}
2542
2543int Channel::SetReceiveAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2544 rtp_header_parser_->DeregisterRtpHeaderExtension(
2545 kRtpExtensionAbsoluteSendTime);
kwiberg55b97fe2016-01-28 05:22:45 -08002546 if (enable &&
2547 !rtp_header_parser_->RegisterRtpHeaderExtension(
2548 kRtpExtensionAbsoluteSendTime, id)) {
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00002549 return -1;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002550 }
2551 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002552}
2553
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002554void Channel::EnableSendTransportSequenceNumber(int id) {
2555 int ret =
2556 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2557 RTC_DCHECK_EQ(0, ret);
2558}
2559
stefan3313ec92016-01-21 06:32:43 -08002560void Channel::EnableReceiveTransportSequenceNumber(int id) {
2561 rtp_header_parser_->DeregisterRtpHeaderExtension(
2562 kRtpExtensionTransportSequenceNumber);
2563 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2564 kRtpExtensionTransportSequenceNumber, id);
2565 RTC_DCHECK(ret);
2566}
2567
stefanbba9dec2016-02-01 04:39:55 -08002568void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002569 RtpPacketSender* rtp_packet_sender,
2570 TransportFeedbackObserver* transport_feedback_observer,
2571 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002572 RTC_DCHECK(rtp_packet_sender);
2573 RTC_DCHECK(transport_feedback_observer);
2574 RTC_DCHECK(packet_router && !packet_router_);
2575 feedback_observer_proxy_->SetTransportFeedbackObserver(
2576 transport_feedback_observer);
2577 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2578 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2579 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002580 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002581 packet_router_ = packet_router;
2582}
2583
stefanbba9dec2016-02-01 04:39:55 -08002584void Channel::RegisterReceiverCongestionControlObjects(
2585 PacketRouter* packet_router) {
2586 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002587 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002588 packet_router_ = packet_router;
2589}
2590
2591void Channel::ResetCongestionControlObjects() {
2592 RTC_DCHECK(packet_router_);
2593 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2594 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2595 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002596 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002597 packet_router_ = nullptr;
2598 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2599}
2600
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002601void Channel::SetRTCPStatus(bool enable) {
2602 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2603 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002604 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002605}
2606
kwiberg55b97fe2016-01-28 05:22:45 -08002607int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002608 RtcpMode method = _rtpRtcpModule->RTCP();
2609 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002610 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002611}
2612
kwiberg55b97fe2016-01-28 05:22:45 -08002613int Channel::SetRTCP_CNAME(const char cName[256]) {
2614 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2615 "Channel::SetRTCP_CNAME()");
2616 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2617 _engineStatisticsPtr->SetLastError(
2618 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2619 "SetRTCP_CNAME() failed to set RTCP CNAME");
2620 return -1;
2621 }
2622 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002623}
2624
kwiberg55b97fe2016-01-28 05:22:45 -08002625int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2626 if (cName == NULL) {
2627 _engineStatisticsPtr->SetLastError(
2628 VE_INVALID_ARGUMENT, kTraceError,
2629 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2630 return -1;
2631 }
2632 char cname[RTCP_CNAME_SIZE];
2633 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2634 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2635 _engineStatisticsPtr->SetLastError(
2636 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2637 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2638 return -1;
2639 }
2640 strcpy(cName, cname);
2641 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002642}
2643
kwiberg55b97fe2016-01-28 05:22:45 -08002644int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2645 unsigned int& NTPLow,
2646 unsigned int& timestamp,
2647 unsigned int& playoutTimestamp,
2648 unsigned int* jitter,
2649 unsigned short* fractionLost) {
2650 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002651
kwiberg55b97fe2016-01-28 05:22:45 -08002652 RTCPSenderInfo senderInfo;
2653 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2654 _engineStatisticsPtr->SetLastError(
2655 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2656 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2657 "side");
2658 return -1;
2659 }
2660
2661 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2662 // and octet count)
2663 NTPHigh = senderInfo.NTPseconds;
2664 NTPLow = senderInfo.NTPfraction;
2665 timestamp = senderInfo.RTPtimeStamp;
2666
2667 // --- Locally derived information
2668
2669 // This value is updated on each incoming RTCP packet (0 when no packet
2670 // has been received)
2671 playoutTimestamp = playout_timestamp_rtcp_;
2672
2673 if (NULL != jitter || NULL != fractionLost) {
2674 // Get all RTCP receiver report blocks that have been received on this
2675 // channel. If we receive RTP packets from a remote source we know the
2676 // remote SSRC and use the report block from him.
2677 // Otherwise use the first report block.
2678 std::vector<RTCPReportBlock> remote_stats;
2679 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2680 remote_stats.empty()) {
2681 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2682 "GetRemoteRTCPData() failed to measure statistics due"
2683 " to lack of received RTP and/or RTCP packets");
2684 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002685 }
2686
kwiberg55b97fe2016-01-28 05:22:45 -08002687 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2688 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2689 for (; it != remote_stats.end(); ++it) {
2690 if (it->remoteSSRC == remoteSSRC)
2691 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002692 }
kwiberg55b97fe2016-01-28 05:22:45 -08002693
2694 if (it == remote_stats.end()) {
2695 // If we have not received any RTCP packets from this SSRC it probably
2696 // means that we have not received any RTP packets.
2697 // Use the first received report block instead.
2698 it = remote_stats.begin();
2699 remoteSSRC = it->remoteSSRC;
2700 }
2701
2702 if (jitter) {
2703 *jitter = it->jitter;
2704 }
2705
2706 if (fractionLost) {
2707 *fractionLost = it->fractionLost;
2708 }
2709 }
2710 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002711}
2712
kwiberg55b97fe2016-01-28 05:22:45 -08002713int Channel::SendApplicationDefinedRTCPPacket(
2714 unsigned char subType,
2715 unsigned int name,
2716 const char* data,
2717 unsigned short dataLengthInBytes) {
2718 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2719 "Channel::SendApplicationDefinedRTCPPacket()");
2720 if (!channel_state_.Get().sending) {
2721 _engineStatisticsPtr->SetLastError(
2722 VE_NOT_SENDING, kTraceError,
2723 "SendApplicationDefinedRTCPPacket() not sending");
2724 return -1;
2725 }
2726 if (NULL == data) {
2727 _engineStatisticsPtr->SetLastError(
2728 VE_INVALID_ARGUMENT, kTraceError,
2729 "SendApplicationDefinedRTCPPacket() invalid data value");
2730 return -1;
2731 }
2732 if (dataLengthInBytes % 4 != 0) {
2733 _engineStatisticsPtr->SetLastError(
2734 VE_INVALID_ARGUMENT, kTraceError,
2735 "SendApplicationDefinedRTCPPacket() invalid length value");
2736 return -1;
2737 }
2738 RtcpMode status = _rtpRtcpModule->RTCP();
2739 if (status == RtcpMode::kOff) {
2740 _engineStatisticsPtr->SetLastError(
2741 VE_RTCP_ERROR, kTraceError,
2742 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2743 return -1;
2744 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002745
kwiberg55b97fe2016-01-28 05:22:45 -08002746 // Create and schedule the RTCP APP packet for transmission
2747 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2748 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2749 _engineStatisticsPtr->SetLastError(
2750 VE_SEND_ERROR, kTraceError,
2751 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2752 return -1;
2753 }
2754 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002755}
2756
kwiberg55b97fe2016-01-28 05:22:45 -08002757int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2758 unsigned int& maxJitterMs,
2759 unsigned int& discardedPackets) {
2760 // The jitter statistics is updated for each received RTP packet and is
2761 // based on received packets.
2762 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2763 // If RTCP is off, there is no timed thread in the RTCP module regularly
2764 // generating new stats, trigger the update manually here instead.
2765 StreamStatistician* statistician =
2766 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2767 if (statistician) {
2768 // Don't use returned statistics, use data from proxy instead so that
2769 // max jitter can be fetched atomically.
2770 RtcpStatistics s;
2771 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002772 }
kwiberg55b97fe2016-01-28 05:22:45 -08002773 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002774
kwiberg55b97fe2016-01-28 05:22:45 -08002775 ChannelStatistics stats = statistics_proxy_->GetStats();
2776 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2777 if (playoutFrequency > 0) {
2778 // Scale RTP statistics given the current playout frequency
2779 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2780 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2781 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002782
kwiberg55b97fe2016-01-28 05:22:45 -08002783 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002784
kwiberg55b97fe2016-01-28 05:22:45 -08002785 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002786}
2787
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002788int Channel::GetRemoteRTCPReportBlocks(
2789 std::vector<ReportBlock>* report_blocks) {
2790 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002791 _engineStatisticsPtr->SetLastError(
2792 VE_INVALID_ARGUMENT, kTraceError,
2793 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002794 return -1;
2795 }
2796
2797 // Get the report blocks from the latest received RTCP Sender or Receiver
2798 // Report. Each element in the vector contains the sender's SSRC and a
2799 // report block according to RFC 3550.
2800 std::vector<RTCPReportBlock> rtcp_report_blocks;
2801 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002802 return -1;
2803 }
2804
2805 if (rtcp_report_blocks.empty())
2806 return 0;
2807
2808 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2809 for (; it != rtcp_report_blocks.end(); ++it) {
2810 ReportBlock report_block;
2811 report_block.sender_SSRC = it->remoteSSRC;
2812 report_block.source_SSRC = it->sourceSSRC;
2813 report_block.fraction_lost = it->fractionLost;
2814 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2815 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2816 report_block.interarrival_jitter = it->jitter;
2817 report_block.last_SR_timestamp = it->lastSR;
2818 report_block.delay_since_last_SR = it->delaySinceLastSR;
2819 report_blocks->push_back(report_block);
2820 }
2821 return 0;
2822}
2823
kwiberg55b97fe2016-01-28 05:22:45 -08002824int Channel::GetRTPStatistics(CallStatistics& stats) {
2825 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002826
kwiberg55b97fe2016-01-28 05:22:45 -08002827 // The jitter statistics is updated for each received RTP packet and is
2828 // based on received packets.
2829 RtcpStatistics statistics;
2830 StreamStatistician* statistician =
2831 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002832 if (statistician) {
2833 statistician->GetStatistics(&statistics,
2834 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002835 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002836
kwiberg55b97fe2016-01-28 05:22:45 -08002837 stats.fractionLost = statistics.fraction_lost;
2838 stats.cumulativeLost = statistics.cumulative_lost;
2839 stats.extendedMax = statistics.extended_max_sequence_number;
2840 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002841
kwiberg55b97fe2016-01-28 05:22:45 -08002842 // --- RTT
2843 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002844
kwiberg55b97fe2016-01-28 05:22:45 -08002845 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002846
kwiberg55b97fe2016-01-28 05:22:45 -08002847 size_t bytesSent(0);
2848 uint32_t packetsSent(0);
2849 size_t bytesReceived(0);
2850 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002851
kwiberg55b97fe2016-01-28 05:22:45 -08002852 if (statistician) {
2853 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2854 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002855
kwiberg55b97fe2016-01-28 05:22:45 -08002856 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2857 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2858 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2859 " output will not be complete");
2860 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002861
kwiberg55b97fe2016-01-28 05:22:45 -08002862 stats.bytesSent = bytesSent;
2863 stats.packetsSent = packetsSent;
2864 stats.bytesReceived = bytesReceived;
2865 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002866
kwiberg55b97fe2016-01-28 05:22:45 -08002867 // --- Timestamps
2868 {
2869 rtc::CritScope lock(&ts_stats_lock_);
2870 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2871 }
2872 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002873}
2874
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002875int Channel::SetREDStatus(bool enable, int redPayloadtype) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002876 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002877 "Channel::SetREDStatus()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002878
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002879 if (enable) {
2880 if (redPayloadtype < 0 || redPayloadtype > 127) {
2881 _engineStatisticsPtr->SetLastError(
2882 VE_PLTYPE_ERROR, kTraceError,
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002883 "SetREDStatus() invalid RED payload type");
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002884 return -1;
2885 }
2886
2887 if (SetRedPayloadType(redPayloadtype) < 0) {
2888 _engineStatisticsPtr->SetLastError(
2889 VE_CODEC_ERROR, kTraceError,
2890 "SetSecondarySendCodec() Failed to register RED ACM");
2891 return -1;
2892 }
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002893 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002894
kwibergc8d071e2016-04-06 12:22:38 -07002895 if (!codec_manager_.SetCopyRed(enable) ||
2896 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002897 _engineStatisticsPtr->SetLastError(
2898 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgaa5ea1c2014-05-23 15:16:51 +00002899 "SetREDStatus() failed to set RED state in the ACM");
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002900 return -1;
2901 }
2902 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002903}
2904
kwiberg55b97fe2016-01-28 05:22:45 -08002905int Channel::GetREDStatus(bool& enabled, int& redPayloadtype) {
kwibergc8d071e2016-04-06 12:22:38 -07002906 enabled = codec_manager_.GetStackParams()->use_red;
kwiberg55b97fe2016-01-28 05:22:45 -08002907 if (enabled) {
2908 int8_t payloadType = 0;
2909 if (_rtpRtcpModule->SendREDPayloadType(&payloadType) != 0) {
2910 _engineStatisticsPtr->SetLastError(
2911 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2912 "GetREDStatus() failed to retrieve RED PT from RTP/RTCP "
2913 "module");
2914 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002915 }
kwiberg55b97fe2016-01-28 05:22:45 -08002916 redPayloadtype = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +00002917 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002918 }
2919 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002920}
2921
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002922int Channel::SetCodecFECStatus(bool enable) {
2923 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2924 "Channel::SetCodecFECStatus()");
2925
kwibergc8d071e2016-04-06 12:22:38 -07002926 if (!codec_manager_.SetCodecFEC(enable) ||
2927 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002928 _engineStatisticsPtr->SetLastError(
2929 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2930 "SetCodecFECStatus() failed to set FEC state");
2931 return -1;
2932 }
2933 return 0;
2934}
2935
2936bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002937 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002938}
2939
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002940void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2941 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002942 // If pacing is enabled we always store packets.
2943 if (!pacing_enabled_)
2944 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002945 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002946 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002947 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002948 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002949 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002950}
2951
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002952// Called when we are missing one or more packets.
2953int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002954 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2955}
2956
kwiberg55b97fe2016-01-28 05:22:45 -08002957uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2958 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2959 "Channel::Demultiplex()");
2960 _audioFrame.CopyFrom(audioFrame);
2961 _audioFrame.id_ = _channelId;
2962 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002963}
2964
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002965void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002966 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002967 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002968 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002969 CodecInst codec;
2970 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002971
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002972 // Never upsample or upmix the capture signal here. This should be done at the
2973 // end of the send chain.
2974 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2975 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2976 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2977 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002978}
2979
kwiberg55b97fe2016-01-28 05:22:45 -08002980uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2981 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2982 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002983
kwiberg55b97fe2016-01-28 05:22:45 -08002984 if (_audioFrame.samples_per_channel_ == 0) {
2985 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2986 "Channel::PrepareEncodeAndSend() invalid audio frame");
2987 return 0xFFFFFFFF;
2988 }
2989
2990 if (channel_state_.Get().input_file_playing) {
2991 MixOrReplaceAudioWithFile(mixingFrequency);
2992 }
2993
solenberg1c2af8e2016-03-24 10:36:00 -07002994 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2995 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002996
2997 if (channel_state_.Get().input_external_media) {
2998 rtc::CritScope cs(&_callbackCritSect);
2999 const bool isStereo = (_audioFrame.num_channels_ == 2);
3000 if (_inputExternalMediaCallbackPtr) {
3001 _inputExternalMediaCallbackPtr->Process(
3002 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
3003 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
3004 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00003005 }
kwiberg55b97fe2016-01-28 05:22:45 -08003006 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003007
kwiberg55b97fe2016-01-28 05:22:45 -08003008 if (_includeAudioLevelIndication) {
3009 size_t length =
3010 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02003011 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07003012 if (is_muted && previous_frame_muted_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003013 rms_level_.ProcessMuted(length);
3014 } else {
3015 rms_level_.Process(_audioFrame.data_, length);
niklase@google.com470e71d2011-07-07 08:21:25 +00003016 }
kwiberg55b97fe2016-01-28 05:22:45 -08003017 }
solenberg1c2af8e2016-03-24 10:36:00 -07003018 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00003019
kwiberg55b97fe2016-01-28 05:22:45 -08003020 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003021}
3022
kwiberg55b97fe2016-01-28 05:22:45 -08003023uint32_t Channel::EncodeAndSend() {
3024 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
3025 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003026
kwiberg55b97fe2016-01-28 05:22:45 -08003027 assert(_audioFrame.num_channels_ <= 2);
3028 if (_audioFrame.samples_per_channel_ == 0) {
3029 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3030 "Channel::EncodeAndSend() invalid audio frame");
3031 return 0xFFFFFFFF;
3032 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003033
kwiberg55b97fe2016-01-28 05:22:45 -08003034 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00003035
kwiberg55b97fe2016-01-28 05:22:45 -08003036 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00003037
kwiberg55b97fe2016-01-28 05:22:45 -08003038 // The ACM resamples internally.
3039 _audioFrame.timestamp_ = _timeStamp;
3040 // This call will trigger AudioPacketizationCallback::SendData if encoding
3041 // is done and payload is ready for packetization and transmission.
3042 // Otherwise, it will return without invoking the callback.
3043 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
3044 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
3045 "Channel::EncodeAndSend() ACM encoding failed");
3046 return 0xFFFFFFFF;
3047 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003048
kwiberg55b97fe2016-01-28 05:22:45 -08003049 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
3050 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003051}
3052
Minyue2013aec2015-05-13 14:14:42 +02003053void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08003054 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003055 Channel* channel = associate_send_channel_.channel();
3056 if (channel && channel->ChannelId() == channel_id) {
3057 // If this channel is associated with a send channel of the specified
3058 // Channel ID, disassociate with it.
3059 ChannelOwner ref(NULL);
3060 associate_send_channel_ = ref;
3061 }
3062}
3063
kwiberg55b97fe2016-01-28 05:22:45 -08003064int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
3065 VoEMediaProcess& processObject) {
3066 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3067 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003068
kwiberg55b97fe2016-01-28 05:22:45 -08003069 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003070
kwiberg55b97fe2016-01-28 05:22:45 -08003071 if (kPlaybackPerChannel == type) {
3072 if (_outputExternalMediaCallbackPtr) {
3073 _engineStatisticsPtr->SetLastError(
3074 VE_INVALID_OPERATION, kTraceError,
3075 "Channel::RegisterExternalMediaProcessing() "
3076 "output external media already enabled");
3077 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003078 }
kwiberg55b97fe2016-01-28 05:22:45 -08003079 _outputExternalMediaCallbackPtr = &processObject;
3080 _outputExternalMedia = true;
3081 } else if (kRecordingPerChannel == type) {
3082 if (_inputExternalMediaCallbackPtr) {
3083 _engineStatisticsPtr->SetLastError(
3084 VE_INVALID_OPERATION, kTraceError,
3085 "Channel::RegisterExternalMediaProcessing() "
3086 "output external media already enabled");
3087 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003088 }
kwiberg55b97fe2016-01-28 05:22:45 -08003089 _inputExternalMediaCallbackPtr = &processObject;
3090 channel_state_.SetInputExternalMedia(true);
3091 }
3092 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003093}
3094
kwiberg55b97fe2016-01-28 05:22:45 -08003095int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
3096 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3097 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003098
kwiberg55b97fe2016-01-28 05:22:45 -08003099 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003100
kwiberg55b97fe2016-01-28 05:22:45 -08003101 if (kPlaybackPerChannel == type) {
3102 if (!_outputExternalMediaCallbackPtr) {
3103 _engineStatisticsPtr->SetLastError(
3104 VE_INVALID_OPERATION, kTraceWarning,
3105 "Channel::DeRegisterExternalMediaProcessing() "
3106 "output external media already disabled");
3107 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003108 }
kwiberg55b97fe2016-01-28 05:22:45 -08003109 _outputExternalMedia = false;
3110 _outputExternalMediaCallbackPtr = NULL;
3111 } else if (kRecordingPerChannel == type) {
3112 if (!_inputExternalMediaCallbackPtr) {
3113 _engineStatisticsPtr->SetLastError(
3114 VE_INVALID_OPERATION, kTraceWarning,
3115 "Channel::DeRegisterExternalMediaProcessing() "
3116 "input external media already disabled");
3117 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003118 }
kwiberg55b97fe2016-01-28 05:22:45 -08003119 channel_state_.SetInputExternalMedia(false);
3120 _inputExternalMediaCallbackPtr = NULL;
3121 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003122
kwiberg55b97fe2016-01-28 05:22:45 -08003123 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003124}
3125
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003126int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08003127 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3128 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003129
kwiberg55b97fe2016-01-28 05:22:45 -08003130 if (channel_state_.Get().playing) {
3131 _engineStatisticsPtr->SetLastError(
3132 VE_INVALID_OPERATION, kTraceError,
3133 "Channel::SetExternalMixing() "
3134 "external mixing cannot be changed while playing.");
3135 return -1;
3136 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003137
kwiberg55b97fe2016-01-28 05:22:45 -08003138 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003139
kwiberg55b97fe2016-01-28 05:22:45 -08003140 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003141}
3142
kwiberg55b97fe2016-01-28 05:22:45 -08003143int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3144 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003145}
3146
wu@webrtc.org24301a62013-12-13 19:17:43 +00003147void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3148 audio_coding_->GetDecodingCallStatistics(stats);
3149}
3150
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003151bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3152 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003153 rtc::CritScope lock(&video_sync_lock_);
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003154 if (_average_jitter_buffer_delay_us == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003155 return false;
3156 }
kwiberg55b97fe2016-01-28 05:22:45 -08003157 *jitter_buffer_delay_ms =
3158 (_average_jitter_buffer_delay_us + 500) / 1000 + _recPacketDelayMs;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003159 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003160 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003161}
3162
solenberg358057b2015-11-27 10:46:42 -08003163uint32_t Channel::GetDelayEstimate() const {
3164 int jitter_buffer_delay_ms = 0;
3165 int playout_buffer_delay_ms = 0;
3166 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3167 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3168}
3169
deadbeef74375882015-08-13 12:09:10 -07003170int Channel::LeastRequiredDelayMs() const {
3171 return audio_coding_->LeastRequiredDelayMs();
3172}
3173
kwiberg55b97fe2016-01-28 05:22:45 -08003174int Channel::SetMinimumPlayoutDelay(int delayMs) {
3175 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3176 "Channel::SetMinimumPlayoutDelay()");
3177 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3178 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3179 _engineStatisticsPtr->SetLastError(
3180 VE_INVALID_ARGUMENT, kTraceError,
3181 "SetMinimumPlayoutDelay() invalid min delay");
3182 return -1;
3183 }
3184 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3185 _engineStatisticsPtr->SetLastError(
3186 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3187 "SetMinimumPlayoutDelay() failed to set min playout delay");
3188 return -1;
3189 }
3190 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003191}
3192
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003193int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003194 uint32_t playout_timestamp_rtp = 0;
3195 {
tommi31fc21f2016-01-21 10:37:37 -08003196 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003197 playout_timestamp_rtp = playout_timestamp_rtp_;
3198 }
kwiberg55b97fe2016-01-28 05:22:45 -08003199 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003200 _engineStatisticsPtr->SetLastError(
3201 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3202 "GetPlayoutTimestamp() failed to retrieve timestamp");
3203 return -1;
3204 }
deadbeef74375882015-08-13 12:09:10 -07003205 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003206 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003207}
3208
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003209int Channel::SetInitTimestamp(unsigned int timestamp) {
3210 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003211 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003212 if (channel_state_.Get().sending) {
3213 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3214 "SetInitTimestamp() already sending");
3215 return -1;
3216 }
3217 _rtpRtcpModule->SetStartTimestamp(timestamp);
3218 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003219}
3220
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003221int Channel::SetInitSequenceNumber(short sequenceNumber) {
3222 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3223 "Channel::SetInitSequenceNumber()");
3224 if (channel_state_.Get().sending) {
3225 _engineStatisticsPtr->SetLastError(
3226 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3227 return -1;
3228 }
3229 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3230 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003231}
3232
kwiberg55b97fe2016-01-28 05:22:45 -08003233int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3234 RtpReceiver** rtp_receiver) const {
3235 *rtpRtcpModule = _rtpRtcpModule.get();
3236 *rtp_receiver = rtp_receiver_.get();
3237 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003238}
3239
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003240// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3241// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003242int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003243 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003244 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003245
kwiberg55b97fe2016-01-28 05:22:45 -08003246 {
3247 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003248
kwiberg55b97fe2016-01-28 05:22:45 -08003249 if (_inputFilePlayerPtr == NULL) {
3250 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3251 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3252 " doesnt exist");
3253 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003254 }
3255
kwiberg55b97fe2016-01-28 05:22:45 -08003256 if (_inputFilePlayerPtr->Get10msAudioFromFile(fileBuffer.get(), fileSamples,
3257 mixingFrequency) == -1) {
3258 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3259 "Channel::MixOrReplaceAudioWithFile() file mixing "
3260 "failed");
3261 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003262 }
kwiberg55b97fe2016-01-28 05:22:45 -08003263 if (fileSamples == 0) {
3264 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3265 "Channel::MixOrReplaceAudioWithFile() file is ended");
3266 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003267 }
kwiberg55b97fe2016-01-28 05:22:45 -08003268 }
3269
3270 assert(_audioFrame.samples_per_channel_ == fileSamples);
3271
3272 if (_mixFileWithMicrophone) {
3273 // Currently file stream is always mono.
3274 // TODO(xians): Change the code when FilePlayer supports real stereo.
3275 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3276 1, fileSamples);
3277 } else {
3278 // Replace ACM audio with file.
3279 // Currently file stream is always mono.
3280 // TODO(xians): Change the code when FilePlayer supports real stereo.
3281 _audioFrame.UpdateFrame(
3282 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3283 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3284 }
3285 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003286}
3287
kwiberg55b97fe2016-01-28 05:22:45 -08003288int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3289 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003290
kwibergb7f89d62016-02-17 10:04:18 -08003291 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003292 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003293
kwiberg55b97fe2016-01-28 05:22:45 -08003294 {
3295 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003296
kwiberg55b97fe2016-01-28 05:22:45 -08003297 if (_outputFilePlayerPtr == NULL) {
3298 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3299 "Channel::MixAudioWithFile() file mixing failed");
3300 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003301 }
3302
kwiberg55b97fe2016-01-28 05:22:45 -08003303 // We should get the frequency we ask for.
3304 if (_outputFilePlayerPtr->Get10msAudioFromFile(
3305 fileBuffer.get(), fileSamples, mixingFrequency) == -1) {
3306 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3307 "Channel::MixAudioWithFile() file mixing failed");
3308 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003309 }
kwiberg55b97fe2016-01-28 05:22:45 -08003310 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003311
kwiberg55b97fe2016-01-28 05:22:45 -08003312 if (audioFrame.samples_per_channel_ == fileSamples) {
3313 // Currently file stream is always mono.
3314 // TODO(xians): Change the code when FilePlayer supports real stereo.
3315 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3316 fileSamples);
3317 } else {
3318 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3319 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3320 ") != "
3321 "fileSamples(%" PRIuS ")",
3322 audioFrame.samples_per_channel_, fileSamples);
3323 return -1;
3324 }
3325
3326 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003327}
3328
deadbeef74375882015-08-13 12:09:10 -07003329void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003330 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003331
henrik.lundin96bd5022016-04-06 04:13:56 -07003332 if (!jitter_buffer_playout_timestamp_) {
3333 // This can happen if this channel has not received any RTP packets. In
3334 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003335 return;
3336 }
3337
3338 uint16_t delay_ms = 0;
3339 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003340 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003341 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3342 " delay from the ADM");
3343 _engineStatisticsPtr->SetLastError(
3344 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3345 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3346 return;
3347 }
3348
henrik.lundin96bd5022016-04-06 04:13:56 -07003349 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3350 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003351
3352 // Remove the playout delay.
henrik.lundin96bd5022016-04-06 04:13:56 -07003353 playout_timestamp -= (delay_ms * (GetPlayoutFrequency() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003354
kwiberg55b97fe2016-01-28 05:22:45 -08003355 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003356 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003357 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003358
3359 {
tommi31fc21f2016-01-21 10:37:37 -08003360 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003361 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003362 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003363 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003364 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003365 }
3366 playout_delay_ms_ = delay_ms;
3367 }
3368}
3369
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003370// Called for incoming RTP packets after successful RTP header parsing.
3371void Channel::UpdatePacketDelay(uint32_t rtp_timestamp,
3372 uint16_t sequence_number) {
kwiberg55b97fe2016-01-28 05:22:45 -08003373 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003374 "Channel::UpdatePacketDelay(timestamp=%lu, sequenceNumber=%u)",
3375 rtp_timestamp, sequence_number);
niklase@google.com470e71d2011-07-07 08:21:25 +00003376
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003377 // Get frequency of last received payload
wu@webrtc.org94454b72014-06-05 20:34:08 +00003378 int rtp_receive_frequency = GetPlayoutFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +00003379
turaj@webrtc.org167b6df2013-12-13 21:05:07 +00003380 // |jitter_buffer_playout_timestamp_| updated in UpdatePlayoutTimestamp for
henrik.lundin96bd5022016-04-06 04:13:56 -07003381 // every incoming packet. May be empty if no valid playout timestamp is
3382 // available.
3383 // If |rtp_timestamp| is newer than |jitter_buffer_playout_timestamp_|, the
3384 // resulting difference is positive and will be used. When the inverse is
3385 // true (can happen when a network glitch causes a packet to arrive late,
3386 // and during long comfort noise periods with clock drift), or when
3387 // |jitter_buffer_playout_timestamp_| has no value, the difference is not
3388 // changed from the initial 0.
3389 uint32_t timestamp_diff_ms = 0;
3390 if (jitter_buffer_playout_timestamp_ &&
3391 IsNewerTimestamp(rtp_timestamp, *jitter_buffer_playout_timestamp_)) {
3392 timestamp_diff_ms = (rtp_timestamp - *jitter_buffer_playout_timestamp_) /
3393 (rtp_receive_frequency / 1000);
3394 if (timestamp_diff_ms > (2 * kVoiceEngineMaxMinPlayoutDelayMs)) {
3395 // Diff is too large; set it to zero instead.
3396 timestamp_diff_ms = 0;
3397 }
henrik.lundin@webrtc.orgd6692992014-03-20 12:04:09 +00003398 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003399
kwiberg55b97fe2016-01-28 05:22:45 -08003400 uint16_t packet_delay_ms =
3401 (rtp_timestamp - _previousTimestamp) / (rtp_receive_frequency / 1000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003402
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003403 _previousTimestamp = rtp_timestamp;
niklase@google.com470e71d2011-07-07 08:21:25 +00003404
kwiberg55b97fe2016-01-28 05:22:45 -08003405 if (timestamp_diff_ms == 0)
3406 return;
niklase@google.com470e71d2011-07-07 08:21:25 +00003407
deadbeef74375882015-08-13 12:09:10 -07003408 {
tommi31fc21f2016-01-21 10:37:37 -08003409 rtc::CritScope lock(&video_sync_lock_);
niklase@google.com470e71d2011-07-07 08:21:25 +00003410
deadbeef74375882015-08-13 12:09:10 -07003411 if (packet_delay_ms >= 10 && packet_delay_ms <= 60) {
3412 _recPacketDelayMs = packet_delay_ms;
3413 }
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003414
deadbeef74375882015-08-13 12:09:10 -07003415 if (_average_jitter_buffer_delay_us == 0) {
3416 _average_jitter_buffer_delay_us = timestamp_diff_ms * 1000;
3417 return;
3418 }
3419
3420 // Filter average delay value using exponential filter (alpha is
3421 // 7/8). We derive 1000 *_average_jitter_buffer_delay_us here (reduces
3422 // risk of rounding error) and compensate for it in GetDelayEstimate()
3423 // later.
kwiberg55b97fe2016-01-28 05:22:45 -08003424 _average_jitter_buffer_delay_us =
3425 (_average_jitter_buffer_delay_us * 7 + 1000 * timestamp_diff_ms + 500) /
3426 8;
deadbeef74375882015-08-13 12:09:10 -07003427 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003428}
3429
kwiberg55b97fe2016-01-28 05:22:45 -08003430void Channel::RegisterReceiveCodecsToRTPModule() {
3431 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3432 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003433
kwiberg55b97fe2016-01-28 05:22:45 -08003434 CodecInst codec;
3435 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003436
kwiberg55b97fe2016-01-28 05:22:45 -08003437 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3438 // Open up the RTP/RTCP receiver for all supported codecs
3439 if ((audio_coding_->Codec(idx, &codec) == -1) ||
3440 (rtp_receiver_->RegisterReceivePayload(
3441 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3442 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
3443 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3444 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3445 " to register %s (%d/%d/%" PRIuS
3446 "/%d) to RTP/RTCP "
3447 "receiver",
3448 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3449 codec.rate);
3450 } else {
3451 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3452 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3453 "(%d/%d/%" PRIuS
3454 "/%d) has been added to the RTP/RTCP "
3455 "receiver",
3456 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3457 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003458 }
kwiberg55b97fe2016-01-28 05:22:45 -08003459 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003460}
3461
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00003462// Assuming this method is called with valid payload type.
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003463int Channel::SetRedPayloadType(int red_payload_type) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003464 CodecInst codec;
3465 bool found_red = false;
3466
3467 // Get default RED settings from the ACM database
3468 const int num_codecs = AudioCodingModule::NumberOfCodecs();
3469 for (int idx = 0; idx < num_codecs; idx++) {
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00003470 audio_coding_->Codec(idx, &codec);
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003471 if (!STR_CASE_CMP(codec.plname, "RED")) {
3472 found_red = true;
3473 break;
3474 }
3475 }
3476
3477 if (!found_red) {
3478 _engineStatisticsPtr->SetLastError(
3479 VE_CODEC_ERROR, kTraceError,
3480 "SetRedPayloadType() RED is not supported");
3481 return -1;
3482 }
3483
turaj@webrtc.org9d532fd2013-01-31 18:34:19 +00003484 codec.pltype = red_payload_type;
kwibergc8d071e2016-04-06 12:22:38 -07003485 if (!codec_manager_.RegisterEncoder(codec) ||
3486 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003487 _engineStatisticsPtr->SetLastError(
3488 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3489 "SetRedPayloadType() RED registration in ACM module failed");
3490 return -1;
3491 }
3492
3493 if (_rtpRtcpModule->SetSendREDPayloadType(red_payload_type) != 0) {
3494 _engineStatisticsPtr->SetLastError(
3495 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
3496 "SetRedPayloadType() RED registration in RTP/RTCP module failed");
3497 return -1;
3498 }
3499 return 0;
3500}
3501
kwiberg55b97fe2016-01-28 05:22:45 -08003502int Channel::SetSendRtpHeaderExtension(bool enable,
3503 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003504 unsigned char id) {
3505 int error = 0;
3506 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3507 if (enable) {
3508 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3509 }
3510 return error;
3511}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003512
wu@webrtc.org94454b72014-06-05 20:34:08 +00003513int32_t Channel::GetPlayoutFrequency() {
3514 int32_t playout_frequency = audio_coding_->PlayoutFrequency();
3515 CodecInst current_recive_codec;
3516 if (audio_coding_->ReceiveCodec(&current_recive_codec) == 0) {
3517 if (STR_CASE_CMP("G722", current_recive_codec.plname) == 0) {
3518 // Even though the actual sampling rate for G.722 audio is
3519 // 16,000 Hz, the RTP clock rate for the G722 payload format is
3520 // 8,000 Hz because that value was erroneously assigned in
3521 // RFC 1890 and must remain unchanged for backward compatibility.
3522 playout_frequency = 8000;
3523 } else if (STR_CASE_CMP("opus", current_recive_codec.plname) == 0) {
3524 // We are resampling Opus internally to 32,000 Hz until all our
3525 // DSP routines can operate at 48,000 Hz, but the RTP clock
3526 // rate for the Opus payload format is standardized to 48,000 Hz,
3527 // because that is the maximum supported decoding sampling rate.
3528 playout_frequency = 48000;
3529 }
3530 }
3531 return playout_frequency;
3532}
3533
Minyue2013aec2015-05-13 14:14:42 +02003534int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003535 RtcpMode method = _rtpRtcpModule->RTCP();
3536 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003537 return 0;
3538 }
3539 std::vector<RTCPReportBlock> report_blocks;
3540 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003541
3542 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003543 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003544 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003545 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003546 Channel* channel = associate_send_channel_.channel();
3547 // Tries to get RTT from an associated channel. This is important for
3548 // receive-only channels.
3549 if (channel) {
3550 // To prevent infinite recursion and deadlock, calling GetRTT of
3551 // associate channel should always use "false" for argument:
3552 // |allow_associate_channel|.
3553 rtt = channel->GetRTT(false);
3554 }
3555 }
3556 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003557 }
3558
3559 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3560 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3561 for (; it != report_blocks.end(); ++it) {
3562 if (it->remoteSSRC == remoteSSRC)
3563 break;
3564 }
3565 if (it == report_blocks.end()) {
3566 // We have not received packets with SSRC matching the report blocks.
3567 // To calculate RTT we try with the SSRC of the first report block.
3568 // This is very important for send-only channels where we don't know
3569 // the SSRC of the other end.
3570 remoteSSRC = report_blocks[0].remoteSSRC;
3571 }
Minyue2013aec2015-05-13 14:14:42 +02003572
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003573 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003574 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003575 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003576 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3577 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003578 return 0;
3579 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003580 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003581}
3582
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003583} // namespace voe
3584} // namespace webrtc