blob: d5f10bfdf8e95f8d9740763b03f474c0bd374a30 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
henrika@webrtc.org2919e952012-01-31 08:45:03 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000011#include "webrtc/voice_engine/channel.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Henrik Lundin64dad832015-05-11 12:44:23 +020013#include <algorithm>
Tommif888bb52015-12-12 01:37:01 +010014#include <utility>
Henrik Lundin64dad832015-05-11 12:44:23 +020015
Ivo Creusenae856f22015-09-17 16:30:16 +020016#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080017#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000018#include "webrtc/base/format_macros.h"
pbosad856222015-11-27 09:48:36 -080019#include "webrtc/base/logging.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010020#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000021#include "webrtc/base/timeutils.h"
minyue@webrtc.orge509f942013-09-12 17:03:00 +000022#include "webrtc/common.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020023#include "webrtc/config.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000024#include "webrtc/modules/audio_device/include/audio_device.h"
25#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010026#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010027#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010028#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
29#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
30#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000031#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010032#include "webrtc/modules/utility/include/audio_frame_operations.h"
33#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010034#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000035#include "webrtc/voice_engine/include/voe_base.h"
36#include "webrtc/voice_engine/include/voe_external_media.h"
37#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
38#include "webrtc/voice_engine/output_mixer.h"
39#include "webrtc/voice_engine/statistics.h"
40#include "webrtc/voice_engine/transmit_mixer.h"
41#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000042
43#if defined(_WIN32)
44#include <Qos.h>
45#endif
46
andrew@webrtc.org50419b02012-11-14 19:07:54 +000047namespace webrtc {
48namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000049
Stefan Holmerb86d4e42015-12-07 10:26:18 +010050class TransportFeedbackProxy : public TransportFeedbackObserver {
51 public:
52 TransportFeedbackProxy() : feedback_observer_(nullptr) {
53 pacer_thread_.DetachFromThread();
54 network_thread_.DetachFromThread();
55 }
56
57 void SetTransportFeedbackObserver(
58 TransportFeedbackObserver* feedback_observer) {
59 RTC_DCHECK(thread_checker_.CalledOnValidThread());
60 rtc::CritScope lock(&crit_);
61 feedback_observer_ = feedback_observer;
62 }
63
64 // Implements TransportFeedbackObserver.
65 void AddPacket(uint16_t sequence_number,
66 size_t length,
67 bool was_paced) override {
68 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
69 rtc::CritScope lock(&crit_);
70 if (feedback_observer_)
71 feedback_observer_->AddPacket(sequence_number, length, was_paced);
72 }
73 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
74 RTC_DCHECK(network_thread_.CalledOnValidThread());
75 rtc::CritScope lock(&crit_);
76 if (feedback_observer_)
77 feedback_observer_->OnTransportFeedback(feedback);
78 }
79
80 private:
81 rtc::CriticalSection crit_;
82 rtc::ThreadChecker thread_checker_;
83 rtc::ThreadChecker pacer_thread_;
84 rtc::ThreadChecker network_thread_;
85 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
86};
87
88class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
89 public:
90 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
91 pacer_thread_.DetachFromThread();
92 }
93
94 void SetSequenceNumberAllocator(
95 TransportSequenceNumberAllocator* seq_num_allocator) {
96 RTC_DCHECK(thread_checker_.CalledOnValidThread());
97 rtc::CritScope lock(&crit_);
98 seq_num_allocator_ = seq_num_allocator;
99 }
100
101 // Implements TransportSequenceNumberAllocator.
102 uint16_t AllocateSequenceNumber() override {
103 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
104 rtc::CritScope lock(&crit_);
105 if (!seq_num_allocator_)
106 return 0;
107 return seq_num_allocator_->AllocateSequenceNumber();
108 }
109
110 private:
111 rtc::CriticalSection crit_;
112 rtc::ThreadChecker thread_checker_;
113 rtc::ThreadChecker pacer_thread_;
114 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
115};
116
117class RtpPacketSenderProxy : public RtpPacketSender {
118 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800119 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100120
121 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
122 RTC_DCHECK(thread_checker_.CalledOnValidThread());
123 rtc::CritScope lock(&crit_);
124 rtp_packet_sender_ = rtp_packet_sender;
125 }
126
127 // Implements RtpPacketSender.
128 void InsertPacket(Priority priority,
129 uint32_t ssrc,
130 uint16_t sequence_number,
131 int64_t capture_time_ms,
132 size_t bytes,
133 bool retransmission) override {
134 rtc::CritScope lock(&crit_);
135 if (rtp_packet_sender_) {
136 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
137 capture_time_ms, bytes, retransmission);
138 }
139 }
140
141 private:
142 rtc::ThreadChecker thread_checker_;
143 rtc::CriticalSection crit_;
144 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
145};
146
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000147// Extend the default RTCP statistics struct with max_jitter, defined as the
148// maximum jitter value seen in an RTCP report block.
149struct ChannelStatistics : public RtcpStatistics {
150 ChannelStatistics() : rtcp(), max_jitter(0) {}
151
152 RtcpStatistics rtcp;
153 uint32_t max_jitter;
154};
155
156// Statistics callback, called at each generation of a new RTCP report block.
157class StatisticsProxy : public RtcpStatisticsCallback {
158 public:
tommi31fc21f2016-01-21 10:37:37 -0800159 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000160 virtual ~StatisticsProxy() {}
161
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000162 void StatisticsUpdated(const RtcpStatistics& statistics,
163 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000164 if (ssrc != ssrc_)
165 return;
166
tommi31fc21f2016-01-21 10:37:37 -0800167 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000168 stats_.rtcp = statistics;
169 if (statistics.jitter > stats_.max_jitter) {
170 stats_.max_jitter = statistics.jitter;
171 }
172 }
173
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000174 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000175
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000176 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800177 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000178 return stats_;
179 }
180
181 private:
182 // StatisticsUpdated calls are triggered from threads in the RTP module,
183 // while GetStats calls can be triggered from the public voice engine API,
184 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800185 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000186 const uint32_t ssrc_;
187 ChannelStatistics stats_;
188};
189
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000190class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000191 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000192 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
193 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000194
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000195 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
196 // Not used for Voice Engine.
197 }
198
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000199 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
200 int64_t rtt,
201 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000202 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
203 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
204 // report for VoiceEngine?
205 if (report_blocks.empty())
206 return;
207
208 int fraction_lost_aggregate = 0;
209 int total_number_of_packets = 0;
210
211 // If receiving multiple report blocks, calculate the weighted average based
212 // on the number of packets a report refers to.
213 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
214 block_it != report_blocks.end(); ++block_it) {
215 // Find the previous extended high sequence number for this remote SSRC,
216 // to calculate the number of RTP packets this report refers to. Ignore if
217 // we haven't seen this SSRC before.
218 std::map<uint32_t, uint32_t>::iterator seq_num_it =
219 extended_max_sequence_number_.find(block_it->sourceSSRC);
220 int number_of_packets = 0;
221 if (seq_num_it != extended_max_sequence_number_.end()) {
222 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
223 }
224 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
225 total_number_of_packets += number_of_packets;
226
227 extended_max_sequence_number_[block_it->sourceSSRC] =
228 block_it->extendedHighSeqNum;
229 }
230 int weighted_fraction_lost = 0;
231 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800232 weighted_fraction_lost =
233 (fraction_lost_aggregate + total_number_of_packets / 2) /
234 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000235 }
236 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000237 }
238
239 private:
240 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000241 // Maps remote side ssrc to extended highest sequence number received.
242 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000243};
244
kwiberg55b97fe2016-01-28 05:22:45 -0800245int32_t Channel::SendData(FrameType frameType,
246 uint8_t payloadType,
247 uint32_t timeStamp,
248 const uint8_t* payloadData,
249 size_t payloadSize,
250 const RTPFragmentationHeader* fragmentation) {
251 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
252 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
253 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
254 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000255
kwiberg55b97fe2016-01-28 05:22:45 -0800256 if (_includeAudioLevelIndication) {
257 // Store current audio level in the RTP/RTCP module.
258 // The level will be used in combination with voice-activity state
259 // (frameType) to add an RTP header extension
260 _rtpRtcpModule->SetAudioLevel(rms_level_.RMS());
261 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000262
kwiberg55b97fe2016-01-28 05:22:45 -0800263 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
264 // packetization.
265 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
266 if (_rtpRtcpModule->SendOutgoingData(
267 (FrameType&)frameType, payloadType, timeStamp,
268 // Leaving the time when this frame was
269 // received from the capture device as
270 // undefined for voice for now.
271 -1, payloadData, payloadSize, fragmentation) == -1) {
272 _engineStatisticsPtr->SetLastError(
273 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
274 "Channel::SendData() failed to send data to RTP/RTCP module");
275 return -1;
276 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000277
kwiberg55b97fe2016-01-28 05:22:45 -0800278 _lastLocalTimeStamp = timeStamp;
279 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000280
kwiberg55b97fe2016-01-28 05:22:45 -0800281 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000282}
283
kwiberg55b97fe2016-01-28 05:22:45 -0800284int32_t Channel::InFrameType(FrameType frame_type) {
285 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
286 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000287
kwiberg55b97fe2016-01-28 05:22:45 -0800288 rtc::CritScope cs(&_callbackCritSect);
289 _sendFrameType = (frame_type == kAudioFrameSpeech);
290 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000291}
292
kwiberg55b97fe2016-01-28 05:22:45 -0800293int32_t Channel::OnRxVadDetected(int vadDecision) {
294 rtc::CritScope cs(&_callbackCritSect);
295 if (_rxVadObserverPtr) {
296 _rxVadObserverPtr->OnRxVad(_channelId, vadDecision);
297 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000298
kwiberg55b97fe2016-01-28 05:22:45 -0800299 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000300}
301
stefan1d8a5062015-10-02 03:39:33 -0700302bool Channel::SendRtp(const uint8_t* data,
303 size_t len,
304 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800305 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
306 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000307
kwiberg55b97fe2016-01-28 05:22:45 -0800308 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000309
kwiberg55b97fe2016-01-28 05:22:45 -0800310 if (_transportPtr == NULL) {
311 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
312 "Channel::SendPacket() failed to send RTP packet due to"
313 " invalid transport object");
314 return false;
315 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000316
kwiberg55b97fe2016-01-28 05:22:45 -0800317 uint8_t* bufferToSendPtr = (uint8_t*)data;
318 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000319
kwiberg55b97fe2016-01-28 05:22:45 -0800320 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
321 std::string transport_name =
322 _externalTransport ? "external transport" : "WebRtc sockets";
323 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
324 "Channel::SendPacket() RTP transmission using %s failed",
325 transport_name.c_str());
326 return false;
327 }
328 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000329}
330
kwiberg55b97fe2016-01-28 05:22:45 -0800331bool Channel::SendRtcp(const uint8_t* data, size_t len) {
332 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
333 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000334
kwiberg55b97fe2016-01-28 05:22:45 -0800335 rtc::CritScope cs(&_callbackCritSect);
336 if (_transportPtr == NULL) {
337 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
338 "Channel::SendRtcp() failed to send RTCP packet"
339 " due to invalid transport object");
340 return false;
341 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000342
kwiberg55b97fe2016-01-28 05:22:45 -0800343 uint8_t* bufferToSendPtr = (uint8_t*)data;
344 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000345
kwiberg55b97fe2016-01-28 05:22:45 -0800346 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
347 if (n < 0) {
348 std::string transport_name =
349 _externalTransport ? "external transport" : "WebRtc sockets";
350 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
351 "Channel::SendRtcp() transmission using %s failed",
352 transport_name.c_str());
353 return false;
354 }
355 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000356}
357
Peter Boströmac547a62015-09-17 23:03:57 +0200358void Channel::OnPlayTelephoneEvent(uint8_t event,
359 uint16_t lengthMs,
360 uint8_t volume) {
kwiberg55b97fe2016-01-28 05:22:45 -0800361 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
362 "Channel::OnPlayTelephoneEvent(event=%u, lengthMs=%u,"
363 " volume=%u)",
364 event, lengthMs, volume);
niklase@google.com470e71d2011-07-07 08:21:25 +0000365
kwiberg55b97fe2016-01-28 05:22:45 -0800366 if (!_playOutbandDtmfEvent || (event > 15)) {
367 // Ignore callback since feedback is disabled or event is not a
368 // Dtmf tone event.
369 return;
370 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000371
kwiberg55b97fe2016-01-28 05:22:45 -0800372 assert(_outputMixerPtr != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000373
kwiberg55b97fe2016-01-28 05:22:45 -0800374 // Start playing out the Dtmf tone (if playout is enabled).
375 // Reduce length of tone with 80ms to the reduce risk of echo.
376 _outputMixerPtr->PlayDtmfTone(event, lengthMs - 80, volume);
niklase@google.com470e71d2011-07-07 08:21:25 +0000377}
378
kwiberg55b97fe2016-01-28 05:22:45 -0800379void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
380 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
381 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000382
kwiberg55b97fe2016-01-28 05:22:45 -0800383 // Update ssrc so that NTP for AV sync can be updated.
384 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000385}
386
Peter Boströmac547a62015-09-17 23:03:57 +0200387void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
388 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
389 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
390 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000391}
392
Peter Boströmac547a62015-09-17 23:03:57 +0200393int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000394 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000395 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000396 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800397 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200398 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800399 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
400 "Channel::OnInitializeDecoder(payloadType=%d, "
401 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
402 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000403
kwiberg55b97fe2016-01-28 05:22:45 -0800404 CodecInst receiveCodec = {0};
405 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000406
kwiberg55b97fe2016-01-28 05:22:45 -0800407 receiveCodec.pltype = payloadType;
408 receiveCodec.plfreq = frequency;
409 receiveCodec.channels = channels;
410 receiveCodec.rate = rate;
411 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000412
kwiberg55b97fe2016-01-28 05:22:45 -0800413 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
414 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000415
kwiberg55b97fe2016-01-28 05:22:45 -0800416 // Register the new codec to the ACM
417 if (audio_coding_->RegisterReceiveCodec(receiveCodec) == -1) {
418 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
419 "Channel::OnInitializeDecoder() invalid codec ("
420 "pt=%d, name=%s) received - 1",
421 payloadType, payloadName);
422 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
423 return -1;
424 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000425
kwiberg55b97fe2016-01-28 05:22:45 -0800426 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000427}
428
kwiberg55b97fe2016-01-28 05:22:45 -0800429int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
430 size_t payloadSize,
431 const WebRtcRTPHeader* rtpHeader) {
432 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
433 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
434 ","
435 " payloadType=%u, audioChannel=%" PRIuS ")",
436 payloadSize, rtpHeader->header.payloadType,
437 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000438
kwiberg55b97fe2016-01-28 05:22:45 -0800439 if (!channel_state_.Get().playing) {
440 // Avoid inserting into NetEQ when we are not playing. Count the
441 // packet as discarded.
442 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
443 "received packet is discarded since playing is not"
444 " activated");
445 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000446 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800447 }
448
449 // Push the incoming payload (parsed and ready for decoding) into the ACM
450 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
451 0) {
452 _engineStatisticsPtr->SetLastError(
453 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
454 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
455 return -1;
456 }
457
458 // Update the packet delay.
459 UpdatePacketDelay(rtpHeader->header.timestamp,
460 rtpHeader->header.sequenceNumber);
461
462 int64_t round_trip_time = 0;
463 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
464 NULL);
465
466 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
467 if (!nack_list.empty()) {
468 // Can't use nack_list.data() since it's not supported by all
469 // compilers.
470 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
471 }
472 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000473}
474
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000475bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000476 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000477 RTPHeader header;
478 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
479 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
480 "IncomingPacket invalid RTP header");
481 return false;
482 }
483 header.payload_type_frequency =
484 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
485 if (header.payload_type_frequency < 0)
486 return false;
487 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
488}
489
kwiberg55b97fe2016-01-28 05:22:45 -0800490int32_t Channel::GetAudioFrame(int32_t id, AudioFrame* audioFrame) {
491 if (event_log_) {
492 unsigned int ssrc;
493 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
494 event_log_->LogAudioPlayout(ssrc);
495 }
496 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
497 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame) ==
498 -1) {
499 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
500 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
501 // In all likelihood, the audio in this frame is garbage. We return an
502 // error so that the audio mixer module doesn't add it to the mix. As
503 // a result, it won't be played out and the actions skipped here are
504 // irrelevant.
505 return -1;
506 }
507
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_);
577 }
578
579 // External media
580 if (_outputExternalMedia) {
581 rtc::CritScope cs(&_callbackCritSect);
582 const bool isStereo = (audioFrame->num_channels_ == 2);
583 if (_outputExternalMediaCallbackPtr) {
584 _outputExternalMediaCallbackPtr->Process(
585 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
586 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
587 isStereo);
588 }
589 }
590
591 // Record playout if enabled
592 {
593 rtc::CritScope cs(&_fileCritSect);
594
595 if (_outputFileRecording && _outputFileRecorderPtr) {
596 _outputFileRecorderPtr->RecordAudioToFile(*audioFrame);
597 }
598 }
599
600 // Measure audio level (0-9)
601 _outputAudioLevel.ComputeLevel(*audioFrame);
602
603 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
604 // The first frame with a valid rtp timestamp.
605 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
606 }
607
608 if (capture_start_rtp_time_stamp_ >= 0) {
609 // audioFrame.timestamp_ should be valid from now on.
610
611 // Compute elapsed time.
612 int64_t unwrap_timestamp =
613 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
614 audioFrame->elapsed_time_ms_ =
615 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
616 (GetPlayoutFrequency() / 1000);
617
niklase@google.com470e71d2011-07-07 08:21:25 +0000618 {
kwiberg55b97fe2016-01-28 05:22:45 -0800619 rtc::CritScope lock(&ts_stats_lock_);
620 // Compute ntp time.
621 audioFrame->ntp_time_ms_ =
622 ntp_estimator_.Estimate(audioFrame->timestamp_);
623 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
624 if (audioFrame->ntp_time_ms_ > 0) {
625 // Compute |capture_start_ntp_time_ms_| so that
626 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
627 capture_start_ntp_time_ms_ =
628 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000629 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000630 }
kwiberg55b97fe2016-01-28 05:22:45 -0800631 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000632
kwiberg55b97fe2016-01-28 05:22:45 -0800633 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000634}
635
kwiberg55b97fe2016-01-28 05:22:45 -0800636int32_t Channel::NeededFrequency(int32_t id) const {
637 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
638 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000639
kwiberg55b97fe2016-01-28 05:22:45 -0800640 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000641
kwiberg55b97fe2016-01-28 05:22:45 -0800642 // Determine highest needed receive frequency
643 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000644
kwiberg55b97fe2016-01-28 05:22:45 -0800645 // Return the bigger of playout and receive frequency in the ACM.
646 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
647 highestNeeded = audio_coding_->PlayoutFrequency();
648 } else {
649 highestNeeded = receiveFrequency;
650 }
651
652 // Special case, if we're playing a file on the playout side
653 // we take that frequency into consideration as well
654 // This is not needed on sending side, since the codec will
655 // limit the spectrum anyway.
656 if (channel_state_.Get().output_file_playing) {
657 rtc::CritScope cs(&_fileCritSect);
658 if (_outputFilePlayerPtr) {
659 if (_outputFilePlayerPtr->Frequency() > highestNeeded) {
660 highestNeeded = _outputFilePlayerPtr->Frequency();
661 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000662 }
kwiberg55b97fe2016-01-28 05:22:45 -0800663 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000664
kwiberg55b97fe2016-01-28 05:22:45 -0800665 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000666}
667
ivocb04965c2015-09-09 00:09:43 -0700668int32_t Channel::CreateChannel(Channel*& channel,
669 int32_t channelId,
670 uint32_t instanceId,
671 RtcEventLog* const event_log,
672 const Config& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800673 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
674 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
675 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000676
kwiberg55b97fe2016-01-28 05:22:45 -0800677 channel = new Channel(channelId, instanceId, event_log, config);
678 if (channel == NULL) {
679 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
680 "Channel::CreateChannel() unable to allocate memory for"
681 " channel");
682 return -1;
683 }
684 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000685}
686
kwiberg55b97fe2016-01-28 05:22:45 -0800687void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
688 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
689 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
690 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000691
kwiberg55b97fe2016-01-28 05:22:45 -0800692 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000693}
694
kwiberg55b97fe2016-01-28 05:22:45 -0800695void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
696 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
697 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
698 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000699
kwiberg55b97fe2016-01-28 05:22:45 -0800700 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000701}
702
kwiberg55b97fe2016-01-28 05:22:45 -0800703void Channel::PlayFileEnded(int32_t id) {
704 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
705 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000706
kwiberg55b97fe2016-01-28 05:22:45 -0800707 if (id == _inputFilePlayerId) {
708 channel_state_.SetInputFilePlaying(false);
709 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
710 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000711 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800712 } else if (id == _outputFilePlayerId) {
713 channel_state_.SetOutputFilePlaying(false);
714 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
715 "Channel::PlayFileEnded() => output file player module is"
716 " shutdown");
717 }
718}
719
720void Channel::RecordFileEnded(int32_t id) {
721 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
722 "Channel::RecordFileEnded(id=%d)", id);
723
724 assert(id == _outputFileRecorderId);
725
726 rtc::CritScope cs(&_fileCritSect);
727
728 _outputFileRecording = false;
729 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
730 "Channel::RecordFileEnded() => output file recorder module is"
731 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000732}
733
pbos@webrtc.org92135212013-05-14 08:31:39 +0000734Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000735 uint32_t instanceId,
ivocb04965c2015-09-09 00:09:43 -0700736 RtcEventLog* const event_log,
737 const Config& config)
tommi31fc21f2016-01-21 10:37:37 -0800738 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100739 _channelId(channelId),
740 event_log_(event_log),
741 rtp_header_parser_(RtpHeaderParser::Create()),
742 rtp_payload_registry_(
743 new RTPPayloadRegistry(RTPPayloadStrategy::CreateStrategy(true))),
744 rtp_receive_statistics_(
745 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
746 rtp_receiver_(
747 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
748 this,
749 this,
750 this,
751 rtp_payload_registry_.get())),
752 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
753 _outputAudioLevel(),
754 _externalTransport(false),
755 _inputFilePlayerPtr(NULL),
756 _outputFilePlayerPtr(NULL),
757 _outputFileRecorderPtr(NULL),
758 // Avoid conflict with other channels by adding 1024 - 1026,
759 // won't use as much as 1024 channels.
760 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
761 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
762 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
763 _outputFileRecording(false),
764 _inbandDtmfQueue(VoEModuleId(instanceId, channelId)),
765 _inbandDtmfGenerator(VoEModuleId(instanceId, channelId)),
766 _outputExternalMedia(false),
767 _inputExternalMediaCallbackPtr(NULL),
768 _outputExternalMediaCallbackPtr(NULL),
769 _timeStamp(0), // This is just an offset, RTP module will add it's own
770 // random offset
771 _sendTelephoneEventPayloadType(106),
772 ntp_estimator_(Clock::GetRealTimeClock()),
773 jitter_buffer_playout_timestamp_(0),
774 playout_timestamp_rtp_(0),
775 playout_timestamp_rtcp_(0),
776 playout_delay_ms_(0),
777 _numberOfDiscardedPackets(0),
778 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100779 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
780 capture_start_rtp_time_stamp_(-1),
781 capture_start_ntp_time_ms_(-1),
782 _engineStatisticsPtr(NULL),
783 _outputMixerPtr(NULL),
784 _transmitMixerPtr(NULL),
785 _moduleProcessThreadPtr(NULL),
786 _audioDeviceModulePtr(NULL),
787 _voiceEngineObserverPtr(NULL),
788 _callbackCritSectPtr(NULL),
789 _transportPtr(NULL),
790 _rxVadObserverPtr(NULL),
791 _oldVadDecision(-1),
792 _sendFrameType(0),
793 _externalMixing(false),
794 _mixFileWithMicrophone(false),
795 _mute(false),
796 _panLeft(1.0f),
797 _panRight(1.0f),
798 _outputGain(1.0f),
799 _playOutbandDtmfEvent(false),
800 _playInbandDtmfEvent(false),
801 _lastLocalTimeStamp(0),
802 _lastPayloadType(0),
803 _includeAudioLevelIndication(false),
804 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100805 _average_jitter_buffer_delay_us(0),
806 _previousTimestamp(0),
807 _recPacketDelayMs(20),
808 _RxVadDetection(false),
809 _rxAgcIsEnabled(false),
810 _rxNsIsEnabled(false),
811 restored_packet_in_use_(false),
812 rtcp_observer_(new VoERtcpObserver(this)),
813 network_predictor_(new NetworkPredictor(Clock::GetRealTimeClock())),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100814 associate_send_channel_(ChannelOwner(nullptr)),
815 pacing_enabled_(config.Get<VoicePacing>().enabled),
816 feedback_observer_proxy_(pacing_enabled_ ? new TransportFeedbackProxy()
817 : nullptr),
818 seq_num_allocator_proxy_(
819 pacing_enabled_ ? new TransportSequenceNumberProxy() : nullptr),
820 rtp_packet_sender_proxy_(pacing_enabled_ ? new RtpPacketSenderProxy()
821 : nullptr) {
kwiberg55b97fe2016-01-28 05:22:45 -0800822 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
823 "Channel::Channel() - ctor");
824 AudioCodingModule::Config acm_config;
825 acm_config.id = VoEModuleId(instanceId, channelId);
826 if (config.Get<NetEqCapacityConfig>().enabled) {
827 // Clamping the buffer capacity at 20 packets. While going lower will
828 // probably work, it makes little sense.
829 acm_config.neteq_config.max_packets_in_buffer =
830 std::max(20, config.Get<NetEqCapacityConfig>().capacity);
831 }
832 acm_config.neteq_config.enable_fast_accelerate =
833 config.Get<NetEqFastAccelerate>().enabled;
834 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200835
kwiberg55b97fe2016-01-28 05:22:45 -0800836 _inbandDtmfQueue.ResetDtmf();
837 _inbandDtmfGenerator.Init();
838 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000839
kwiberg55b97fe2016-01-28 05:22:45 -0800840 RtpRtcp::Configuration configuration;
841 configuration.audio = true;
842 configuration.outgoing_transport = this;
843 configuration.audio_messages = this;
844 configuration.receive_statistics = rtp_receive_statistics_.get();
845 configuration.bandwidth_callback = rtcp_observer_.get();
846 configuration.paced_sender = rtp_packet_sender_proxy_.get();
847 configuration.transport_sequence_number_allocator =
848 seq_num_allocator_proxy_.get();
849 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
850 configuration.event_log = event_log;
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000851
kwiberg55b97fe2016-01-28 05:22:45 -0800852 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000853
kwiberg55b97fe2016-01-28 05:22:45 -0800854 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
855 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
856 statistics_proxy_.get());
aluebs@webrtc.orgf927fd62014-04-16 11:58:18 +0000857
kwiberg55b97fe2016-01-28 05:22:45 -0800858 Config audioproc_config;
859 audioproc_config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
860 rx_audioproc_.reset(AudioProcessing::Create(audioproc_config));
niklase@google.com470e71d2011-07-07 08:21:25 +0000861}
862
kwiberg55b97fe2016-01-28 05:22:45 -0800863Channel::~Channel() {
864 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
865 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
866 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000867
kwiberg55b97fe2016-01-28 05:22:45 -0800868 if (_outputExternalMedia) {
869 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
870 }
871 if (channel_state_.Get().input_external_media) {
872 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
873 }
874 StopSend();
875 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000876
kwiberg55b97fe2016-01-28 05:22:45 -0800877 {
878 rtc::CritScope cs(&_fileCritSect);
879 if (_inputFilePlayerPtr) {
880 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
881 _inputFilePlayerPtr->StopPlayingFile();
882 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
883 _inputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000884 }
kwiberg55b97fe2016-01-28 05:22:45 -0800885 if (_outputFilePlayerPtr) {
886 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
887 _outputFilePlayerPtr->StopPlayingFile();
888 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
889 _outputFilePlayerPtr = NULL;
890 }
891 if (_outputFileRecorderPtr) {
892 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
893 _outputFileRecorderPtr->StopRecording();
894 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
895 _outputFileRecorderPtr = NULL;
896 }
897 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000898
kwiberg55b97fe2016-01-28 05:22:45 -0800899 // The order to safely shutdown modules in a channel is:
900 // 1. De-register callbacks in modules
901 // 2. De-register modules in process thread
902 // 3. Destroy modules
903 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
904 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
905 "~Channel() failed to de-register transport callback"
906 " (Audio coding module)");
907 }
908 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
909 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
910 "~Channel() failed to de-register VAD callback"
911 " (Audio coding module)");
912 }
913 // De-register modules in process thread
914 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +0000915
kwiberg55b97fe2016-01-28 05:22:45 -0800916 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +0000917}
918
kwiberg55b97fe2016-01-28 05:22:45 -0800919int32_t Channel::Init() {
920 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
921 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000922
kwiberg55b97fe2016-01-28 05:22:45 -0800923 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000924
kwiberg55b97fe2016-01-28 05:22:45 -0800925 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000926
kwiberg55b97fe2016-01-28 05:22:45 -0800927 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
928 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
929 "Channel::Init() must call SetEngineInformation() first");
930 return -1;
931 }
932
933 // --- Add modules to process thread (for periodic schedulation)
934
935 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
936
937 // --- ACM initialization
938
939 if (audio_coding_->InitializeReceiver() == -1) {
940 _engineStatisticsPtr->SetLastError(
941 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
942 "Channel::Init() unable to initialize the ACM - 1");
943 return -1;
944 }
945
946 // --- RTP/RTCP module initialization
947
948 // Ensure that RTCP is enabled by default for the created channel.
949 // Note that, the module will keep generating RTCP until it is explicitly
950 // disabled by the user.
951 // After StopListen (when no sockets exists), RTCP packets will no longer
952 // be transmitted since the Transport object will then be invalid.
953 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
954 // RTCP is enabled by default.
955 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
956 // --- Register all permanent callbacks
957 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
958 (audio_coding_->RegisterVADCallback(this) == -1);
959
960 if (fail) {
961 _engineStatisticsPtr->SetLastError(
962 VE_CANNOT_INIT_CHANNEL, kTraceError,
963 "Channel::Init() callbacks not registered");
964 return -1;
965 }
966
967 // --- Register all supported codecs to the receiving side of the
968 // RTP/RTCP module
969
970 CodecInst codec;
971 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
972
973 for (int idx = 0; idx < nSupportedCodecs; idx++) {
974 // Open up the RTP/RTCP receiver for all supported codecs
975 if ((audio_coding_->Codec(idx, &codec) == -1) ||
976 (rtp_receiver_->RegisterReceivePayload(
977 codec.plname, codec.pltype, codec.plfreq, codec.channels,
978 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
979 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
980 "Channel::Init() unable to register %s "
981 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
982 codec.plname, codec.pltype, codec.plfreq, codec.channels,
983 codec.rate);
984 } else {
985 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
986 "Channel::Init() %s (%d/%d/%" PRIuS
987 "/%d) has been "
988 "added to the RTP/RTCP receiver",
989 codec.plname, codec.pltype, codec.plfreq, codec.channels,
990 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000991 }
992
kwiberg55b97fe2016-01-28 05:22:45 -0800993 // Ensure that PCMU is used as default codec on the sending side
994 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
995 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +0000996 }
997
kwiberg55b97fe2016-01-28 05:22:45 -0800998 // Register default PT for outband 'telephone-event'
999 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
1000 if ((_rtpRtcpModule->RegisterSendPayload(codec) == -1) ||
1001 (audio_coding_->RegisterReceiveCodec(codec) == -1)) {
1002 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1003 "Channel::Init() failed to register outband "
1004 "'telephone-event' (%d/%d) correctly",
1005 codec.pltype, codec.plfreq);
1006 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001007 }
1008
kwiberg55b97fe2016-01-28 05:22:45 -08001009 if (!STR_CASE_CMP(codec.plname, "CN")) {
1010 if ((audio_coding_->RegisterSendCodec(codec) == -1) ||
1011 (audio_coding_->RegisterReceiveCodec(codec) == -1) ||
1012 (_rtpRtcpModule->RegisterSendPayload(codec) == -1)) {
1013 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1014 "Channel::Init() failed to register CN (%d/%d) "
1015 "correctly - 1",
1016 codec.pltype, codec.plfreq);
1017 }
1018 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001019#ifdef WEBRTC_CODEC_RED
kwiberg55b97fe2016-01-28 05:22:45 -08001020 // Register RED to the receiving side of the ACM.
1021 // We will not receive an OnInitializeDecoder() callback for RED.
1022 if (!STR_CASE_CMP(codec.plname, "RED")) {
1023 if (audio_coding_->RegisterReceiveCodec(codec) == -1) {
1024 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1025 "Channel::Init() failed to register RED (%d/%d) "
1026 "correctly",
1027 codec.pltype, codec.plfreq);
1028 }
1029 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001030#endif
kwiberg55b97fe2016-01-28 05:22:45 -08001031 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001032
kwiberg55b97fe2016-01-28 05:22:45 -08001033 if (rx_audioproc_->noise_suppression()->set_level(kDefaultNsMode) != 0) {
1034 LOG(LS_ERROR) << "noise_suppression()->set_level(kDefaultNsMode) failed.";
1035 return -1;
1036 }
1037 if (rx_audioproc_->gain_control()->set_mode(kDefaultRxAgcMode) != 0) {
1038 LOG(LS_ERROR) << "gain_control()->set_mode(kDefaultRxAgcMode) failed.";
1039 return -1;
1040 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001041
kwiberg55b97fe2016-01-28 05:22:45 -08001042 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001043}
1044
kwiberg55b97fe2016-01-28 05:22:45 -08001045int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1046 OutputMixer& outputMixer,
1047 voe::TransmitMixer& transmitMixer,
1048 ProcessThread& moduleProcessThread,
1049 AudioDeviceModule& audioDeviceModule,
1050 VoiceEngineObserver* voiceEngineObserver,
1051 rtc::CriticalSection* callbackCritSect) {
1052 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1053 "Channel::SetEngineInformation()");
1054 _engineStatisticsPtr = &engineStatistics;
1055 _outputMixerPtr = &outputMixer;
1056 _transmitMixerPtr = &transmitMixer,
1057 _moduleProcessThreadPtr = &moduleProcessThread;
1058 _audioDeviceModulePtr = &audioDeviceModule;
1059 _voiceEngineObserverPtr = voiceEngineObserver;
1060 _callbackCritSectPtr = callbackCritSect;
1061 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001062}
1063
kwiberg55b97fe2016-01-28 05:22:45 -08001064int32_t Channel::UpdateLocalTimeStamp() {
1065 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1066 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001067}
1068
deadbeef2d110be2016-01-13 12:00:26 -08001069void Channel::SetSink(rtc::scoped_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001070 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001071 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001072}
1073
kwiberg55b97fe2016-01-28 05:22:45 -08001074int32_t Channel::StartPlayout() {
1075 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1076 "Channel::StartPlayout()");
1077 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001078 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001079 }
1080
1081 if (!_externalMixing) {
1082 // Add participant as candidates for mixing.
1083 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1084 _engineStatisticsPtr->SetLastError(
1085 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1086 "StartPlayout() failed to add participant to mixer");
1087 return -1;
1088 }
1089 }
1090
1091 channel_state_.SetPlaying(true);
1092 if (RegisterFilePlayingToMixer() != 0)
1093 return -1;
1094
1095 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001096}
1097
kwiberg55b97fe2016-01-28 05:22:45 -08001098int32_t Channel::StopPlayout() {
1099 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1100 "Channel::StopPlayout()");
1101 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001102 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001103 }
1104
1105 if (!_externalMixing) {
1106 // Remove participant as candidates for mixing
1107 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1108 _engineStatisticsPtr->SetLastError(
1109 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1110 "StopPlayout() failed to remove participant from mixer");
1111 return -1;
1112 }
1113 }
1114
1115 channel_state_.SetPlaying(false);
1116 _outputAudioLevel.Clear();
1117
1118 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001119}
1120
kwiberg55b97fe2016-01-28 05:22:45 -08001121int32_t Channel::StartSend() {
1122 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1123 "Channel::StartSend()");
1124 // Resume the previous sequence number which was reset by StopSend().
1125 // This needs to be done before |sending| is set to true.
1126 if (send_sequence_number_)
1127 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001128
kwiberg55b97fe2016-01-28 05:22:45 -08001129 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001130 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001131 }
1132 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001133
kwiberg55b97fe2016-01-28 05:22:45 -08001134 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1135 _engineStatisticsPtr->SetLastError(
1136 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1137 "StartSend() RTP/RTCP failed to start sending");
1138 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001139 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001140 return -1;
1141 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001142
kwiberg55b97fe2016-01-28 05:22:45 -08001143 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001144}
1145
kwiberg55b97fe2016-01-28 05:22:45 -08001146int32_t Channel::StopSend() {
1147 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1148 "Channel::StopSend()");
1149 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001150 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001151 }
1152 channel_state_.SetSending(false);
1153
1154 // Store the sequence number to be able to pick up the same sequence for
1155 // the next StartSend(). This is needed for restarting device, otherwise
1156 // it might cause libSRTP to complain about packets being replayed.
1157 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1158 // CL is landed. See issue
1159 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1160 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1161
1162 // Reset sending SSRC and sequence number and triggers direct transmission
1163 // of RTCP BYE
1164 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1165 _engineStatisticsPtr->SetLastError(
1166 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1167 "StartSend() RTP/RTCP failed to stop sending");
1168 }
1169
1170 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001171}
1172
kwiberg55b97fe2016-01-28 05:22:45 -08001173int32_t Channel::StartReceiving() {
1174 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1175 "Channel::StartReceiving()");
1176 if (channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001177 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001178 }
1179 channel_state_.SetReceiving(true);
1180 _numberOfDiscardedPackets = 0;
1181 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001182}
1183
kwiberg55b97fe2016-01-28 05:22:45 -08001184int32_t Channel::StopReceiving() {
1185 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1186 "Channel::StopReceiving()");
1187 if (!channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001188 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001189 }
1190
1191 channel_state_.SetReceiving(false);
1192 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001193}
1194
kwiberg55b97fe2016-01-28 05:22:45 -08001195int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1196 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1197 "Channel::RegisterVoiceEngineObserver()");
1198 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001199
kwiberg55b97fe2016-01-28 05:22:45 -08001200 if (_voiceEngineObserverPtr) {
1201 _engineStatisticsPtr->SetLastError(
1202 VE_INVALID_OPERATION, kTraceError,
1203 "RegisterVoiceEngineObserver() observer already enabled");
1204 return -1;
1205 }
1206 _voiceEngineObserverPtr = &observer;
1207 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001208}
1209
kwiberg55b97fe2016-01-28 05:22:45 -08001210int32_t Channel::DeRegisterVoiceEngineObserver() {
1211 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1212 "Channel::DeRegisterVoiceEngineObserver()");
1213 rtc::CritScope cs(&_callbackCritSect);
1214
1215 if (!_voiceEngineObserverPtr) {
1216 _engineStatisticsPtr->SetLastError(
1217 VE_INVALID_OPERATION, kTraceWarning,
1218 "DeRegisterVoiceEngineObserver() observer already disabled");
1219 return 0;
1220 }
1221 _voiceEngineObserverPtr = NULL;
1222 return 0;
1223}
1224
1225int32_t Channel::GetSendCodec(CodecInst& codec) {
kwiberg1fd4a4a2015-11-03 11:20:50 -08001226 auto send_codec = audio_coding_->SendCodec();
1227 if (send_codec) {
1228 codec = *send_codec;
1229 return 0;
1230 }
1231 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001232}
1233
kwiberg55b97fe2016-01-28 05:22:45 -08001234int32_t Channel::GetRecCodec(CodecInst& codec) {
1235 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001236}
1237
kwiberg55b97fe2016-01-28 05:22:45 -08001238int32_t Channel::SetSendCodec(const CodecInst& codec) {
1239 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1240 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001241
kwiberg55b97fe2016-01-28 05:22:45 -08001242 if (audio_coding_->RegisterSendCodec(codec) != 0) {
1243 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1244 "SetSendCodec() failed to register codec to ACM");
1245 return -1;
1246 }
1247
1248 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1249 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1250 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1251 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1252 "SetSendCodec() failed to register codec to"
1253 " RTP/RTCP module");
1254 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001255 }
kwiberg55b97fe2016-01-28 05:22:45 -08001256 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001257
kwiberg55b97fe2016-01-28 05:22:45 -08001258 if (_rtpRtcpModule->SetAudioPacketSize(codec.pacsize) != 0) {
1259 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1260 "SetSendCodec() failed to set audio packet size");
1261 return -1;
1262 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001263
kwiberg55b97fe2016-01-28 05:22:45 -08001264 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001265}
1266
Ivo Creusenadf89b72015-04-29 16:03:33 +02001267void Channel::SetBitRate(int bitrate_bps) {
1268 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1269 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
1270 audio_coding_->SetBitRate(bitrate_bps);
1271}
1272
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001273void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue@webrtc.org74aaf292014-07-16 21:28:26 +00001274 network_predictor_->UpdatePacketLossRate(fraction_lost);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001275 uint8_t average_fraction_loss = network_predictor_->GetLossRate();
1276
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001277 // Normalizes rate to 0 - 100.
kwiberg55b97fe2016-01-28 05:22:45 -08001278 if (audio_coding_->SetPacketLossRate(100 * average_fraction_loss / 255) !=
1279 0) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001280 assert(false); // This should not happen.
1281 }
1282}
1283
kwiberg55b97fe2016-01-28 05:22:45 -08001284int32_t Channel::SetVADStatus(bool enableVAD,
1285 ACMVADMode mode,
1286 bool disableDTX) {
1287 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1288 "Channel::SetVADStatus(mode=%d)", mode);
1289 assert(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1290 // To disable VAD, DTX must be disabled too
1291 disableDTX = ((enableVAD == false) ? true : disableDTX);
1292 if (audio_coding_->SetVAD(!disableDTX, enableVAD, mode) != 0) {
1293 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1294 kTraceError,
1295 "SetVADStatus() failed to set VAD");
1296 return -1;
1297 }
1298 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001299}
1300
kwiberg55b97fe2016-01-28 05:22:45 -08001301int32_t Channel::GetVADStatus(bool& enabledVAD,
1302 ACMVADMode& mode,
1303 bool& disabledDTX) {
1304 if (audio_coding_->VAD(&disabledDTX, &enabledVAD, &mode) != 0) {
1305 _engineStatisticsPtr->SetLastError(
1306 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1307 "GetVADStatus() failed to get VAD status");
1308 return -1;
1309 }
1310 disabledDTX = !disabledDTX;
1311 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001312}
1313
kwiberg55b97fe2016-01-28 05:22:45 -08001314int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1315 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1316 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001317
kwiberg55b97fe2016-01-28 05:22:45 -08001318 if (channel_state_.Get().playing) {
1319 _engineStatisticsPtr->SetLastError(
1320 VE_ALREADY_PLAYING, kTraceError,
1321 "SetRecPayloadType() unable to set PT while playing");
1322 return -1;
1323 }
1324 if (channel_state_.Get().receiving) {
1325 _engineStatisticsPtr->SetLastError(
1326 VE_ALREADY_LISTENING, kTraceError,
1327 "SetRecPayloadType() unable to set PT while listening");
1328 return -1;
1329 }
1330
1331 if (codec.pltype == -1) {
1332 // De-register the selected codec (RTP/RTCP module and ACM)
1333
1334 int8_t pltype(-1);
1335 CodecInst rxCodec = codec;
1336
1337 // Get payload type for the given codec
1338 rtp_payload_registry_->ReceivePayloadType(
1339 rxCodec.plname, rxCodec.plfreq, rxCodec.channels,
1340 (rxCodec.rate < 0) ? 0 : rxCodec.rate, &pltype);
1341 rxCodec.pltype = pltype;
1342
1343 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1344 _engineStatisticsPtr->SetLastError(
1345 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1346 "SetRecPayloadType() RTP/RTCP-module deregistration "
1347 "failed");
1348 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001349 }
kwiberg55b97fe2016-01-28 05:22:45 -08001350 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1351 _engineStatisticsPtr->SetLastError(
1352 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1353 "SetRecPayloadType() ACM deregistration failed - 1");
1354 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001355 }
kwiberg55b97fe2016-01-28 05:22:45 -08001356 return 0;
1357 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001358
kwiberg55b97fe2016-01-28 05:22:45 -08001359 if (rtp_receiver_->RegisterReceivePayload(
1360 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1361 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1362 // First attempt to register failed => de-register and try again
1363 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001364 if (rtp_receiver_->RegisterReceivePayload(
kwiberg55b97fe2016-01-28 05:22:45 -08001365 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1366 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1367 _engineStatisticsPtr->SetLastError(
1368 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1369 "SetRecPayloadType() RTP/RTCP-module registration failed");
1370 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001371 }
kwiberg55b97fe2016-01-28 05:22:45 -08001372 }
1373 if (audio_coding_->RegisterReceiveCodec(codec) != 0) {
1374 audio_coding_->UnregisterReceiveCodec(codec.pltype);
1375 if (audio_coding_->RegisterReceiveCodec(codec) != 0) {
1376 _engineStatisticsPtr->SetLastError(
1377 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1378 "SetRecPayloadType() ACM registration failed - 1");
1379 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001380 }
kwiberg55b97fe2016-01-28 05:22:45 -08001381 }
1382 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001383}
1384
kwiberg55b97fe2016-01-28 05:22:45 -08001385int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1386 int8_t payloadType(-1);
1387 if (rtp_payload_registry_->ReceivePayloadType(
1388 codec.plname, codec.plfreq, codec.channels,
1389 (codec.rate < 0) ? 0 : codec.rate, &payloadType) != 0) {
1390 _engineStatisticsPtr->SetLastError(
1391 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1392 "GetRecPayloadType() failed to retrieve RX payload type");
1393 return -1;
1394 }
1395 codec.pltype = payloadType;
1396 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001397}
1398
kwiberg55b97fe2016-01-28 05:22:45 -08001399int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1400 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1401 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001402
kwiberg55b97fe2016-01-28 05:22:45 -08001403 CodecInst codec;
1404 int32_t samplingFreqHz(-1);
1405 const size_t kMono = 1;
1406 if (frequency == kFreq32000Hz)
1407 samplingFreqHz = 32000;
1408 else if (frequency == kFreq16000Hz)
1409 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001410
kwiberg55b97fe2016-01-28 05:22:45 -08001411 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1412 _engineStatisticsPtr->SetLastError(
1413 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1414 "SetSendCNPayloadType() failed to retrieve default CN codec "
1415 "settings");
1416 return -1;
1417 }
1418
1419 // Modify the payload type (must be set to dynamic range)
1420 codec.pltype = type;
1421
1422 if (audio_coding_->RegisterSendCodec(codec) != 0) {
1423 _engineStatisticsPtr->SetLastError(
1424 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1425 "SetSendCNPayloadType() failed to register CN to ACM");
1426 return -1;
1427 }
1428
1429 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1430 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1431 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1432 _engineStatisticsPtr->SetLastError(
1433 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1434 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1435 "module");
1436 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001437 }
kwiberg55b97fe2016-01-28 05:22:45 -08001438 }
1439 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001440}
1441
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001442int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001443 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001444 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001445
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001446 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001447 _engineStatisticsPtr->SetLastError(
1448 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001449 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001450 return -1;
1451 }
1452 return 0;
1453}
1454
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001455int Channel::SetOpusDtx(bool enable_dtx) {
1456 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1457 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001458 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001459 : audio_coding_->DisableOpusDtx();
1460 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001461 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1462 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001463 return -1;
1464 }
1465 return 0;
1466}
1467
kwiberg55b97fe2016-01-28 05:22:45 -08001468int32_t Channel::RegisterExternalTransport(Transport& transport) {
1469 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001470 "Channel::RegisterExternalTransport()");
1471
kwiberg55b97fe2016-01-28 05:22:45 -08001472 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001473
kwiberg55b97fe2016-01-28 05:22:45 -08001474 if (_externalTransport) {
1475 _engineStatisticsPtr->SetLastError(
1476 VE_INVALID_OPERATION, kTraceError,
1477 "RegisterExternalTransport() external transport already enabled");
1478 return -1;
1479 }
1480 _externalTransport = true;
1481 _transportPtr = &transport;
1482 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001483}
1484
kwiberg55b97fe2016-01-28 05:22:45 -08001485int32_t Channel::DeRegisterExternalTransport() {
1486 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1487 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001488
kwiberg55b97fe2016-01-28 05:22:45 -08001489 rtc::CritScope cs(&_callbackCritSect);
xians@webrtc.org83661f52011-11-25 10:58:15 +00001490
kwiberg55b97fe2016-01-28 05:22:45 -08001491 if (!_transportPtr) {
1492 _engineStatisticsPtr->SetLastError(
1493 VE_INVALID_OPERATION, kTraceWarning,
1494 "DeRegisterExternalTransport() external transport already "
1495 "disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00001496 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001497 }
1498 _externalTransport = false;
1499 _transportPtr = NULL;
1500 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1501 "DeRegisterExternalTransport() all transport is disabled");
1502 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001503}
1504
kwiberg55b97fe2016-01-28 05:22:45 -08001505int32_t Channel::ReceivedRTPPacket(const int8_t* data,
1506 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001507 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001508 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001509 "Channel::ReceivedRTPPacket()");
1510
1511 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001512 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001513
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001514 const uint8_t* received_packet = reinterpret_cast<const uint8_t*>(data);
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001515 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001516 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1517 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1518 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001519 return -1;
1520 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001521 header.payload_type_frequency =
1522 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001523 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001524 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001525 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001526 rtp_receive_statistics_->IncomingPacket(
1527 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001528 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001529
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001530 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001531}
1532
1533bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001534 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001535 const RTPHeader& header,
1536 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001537 if (rtp_payload_registry_->IsRtx(header)) {
1538 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001539 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001540 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001541 assert(packet_length >= header.headerLength);
1542 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001543 PayloadUnion payload_specific;
1544 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001545 &payload_specific)) {
1546 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001547 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001548 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1549 payload_specific, in_order);
1550}
1551
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001552bool Channel::HandleRtxPacket(const uint8_t* packet,
1553 size_t packet_length,
1554 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001555 if (!rtp_payload_registry_->IsRtx(header))
1556 return false;
1557
1558 // Remove the RTX header and parse the original RTP header.
1559 if (packet_length < header.headerLength)
1560 return false;
1561 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1562 return false;
1563 if (restored_packet_in_use_) {
1564 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1565 "Multiple RTX headers detected, dropping packet");
1566 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001567 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001568 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001569 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1570 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001571 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1572 "Incoming RTX packet: invalid RTP header");
1573 return false;
1574 }
1575 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001576 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001577 restored_packet_in_use_ = false;
1578 return ret;
1579}
1580
1581bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1582 StreamStatistician* statistician =
1583 rtp_receive_statistics_->GetStatistician(header.ssrc);
1584 if (!statistician)
1585 return false;
1586 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001587}
1588
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001589bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1590 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001591 // Retransmissions are handled separately if RTX is enabled.
1592 if (rtp_payload_registry_->RtxEnabled())
1593 return false;
1594 StreamStatistician* statistician =
1595 rtp_receive_statistics_->GetStatistician(header.ssrc);
1596 if (!statistician)
1597 return false;
1598 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001599 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001600 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001601 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001602}
1603
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001604int32_t Channel::ReceivedRTCPPacket(const int8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001605 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001606 "Channel::ReceivedRTCPPacket()");
1607 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001608 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001609
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001610 // Deliver RTCP packet to RTP/RTCP module for parsing
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001611 if (_rtpRtcpModule->IncomingRtcpPacket((const uint8_t*)data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001612 _engineStatisticsPtr->SetLastError(
1613 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1614 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1615 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001616
Minyue2013aec2015-05-13 14:14:42 +02001617 int64_t rtt = GetRTT(true);
1618 if (rtt == 0) {
1619 // Waiting for valid RTT.
1620 return 0;
1621 }
1622 uint32_t ntp_secs = 0;
1623 uint32_t ntp_frac = 0;
1624 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001625 if (0 !=
1626 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1627 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001628 // Waiting for RTCP.
1629 return 0;
1630 }
1631
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001632 {
tommi31fc21f2016-01-21 10:37:37 -08001633 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001634 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001635 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001636 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001637}
1638
niklase@google.com470e71d2011-07-07 08:21:25 +00001639int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001640 bool loop,
1641 FileFormats format,
1642 int startPosition,
1643 float volumeScaling,
1644 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001645 const CodecInst* codecInst) {
1646 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1647 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1648 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1649 "stopPosition=%d)",
1650 fileName, loop, format, volumeScaling, startPosition,
1651 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001652
kwiberg55b97fe2016-01-28 05:22:45 -08001653 if (channel_state_.Get().output_file_playing) {
1654 _engineStatisticsPtr->SetLastError(
1655 VE_ALREADY_PLAYING, kTraceError,
1656 "StartPlayingFileLocally() is already playing");
1657 return -1;
1658 }
1659
1660 {
1661 rtc::CritScope cs(&_fileCritSect);
1662
1663 if (_outputFilePlayerPtr) {
1664 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1665 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1666 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001667 }
1668
kwiberg55b97fe2016-01-28 05:22:45 -08001669 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1670 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001671
kwiberg55b97fe2016-01-28 05:22:45 -08001672 if (_outputFilePlayerPtr == NULL) {
1673 _engineStatisticsPtr->SetLastError(
1674 VE_INVALID_ARGUMENT, kTraceError,
1675 "StartPlayingFileLocally() filePlayer format is not correct");
1676 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001677 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001678
kwiberg55b97fe2016-01-28 05:22:45 -08001679 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001680
kwiberg55b97fe2016-01-28 05:22:45 -08001681 if (_outputFilePlayerPtr->StartPlayingFile(
1682 fileName, loop, startPosition, volumeScaling, notificationTime,
1683 stopPosition, (const CodecInst*)codecInst) != 0) {
1684 _engineStatisticsPtr->SetLastError(
1685 VE_BAD_FILE, kTraceError,
1686 "StartPlayingFile() failed to start file playout");
1687 _outputFilePlayerPtr->StopPlayingFile();
1688 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1689 _outputFilePlayerPtr = NULL;
1690 return -1;
1691 }
1692 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1693 channel_state_.SetOutputFilePlaying(true);
1694 }
1695
1696 if (RegisterFilePlayingToMixer() != 0)
1697 return -1;
1698
1699 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001700}
1701
1702int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001703 FileFormats format,
1704 int startPosition,
1705 float volumeScaling,
1706 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001707 const CodecInst* codecInst) {
1708 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1709 "Channel::StartPlayingFileLocally(format=%d,"
1710 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1711 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001712
kwiberg55b97fe2016-01-28 05:22:45 -08001713 if (stream == NULL) {
1714 _engineStatisticsPtr->SetLastError(
1715 VE_BAD_FILE, kTraceError,
1716 "StartPlayingFileLocally() NULL as input stream");
1717 return -1;
1718 }
1719
1720 if (channel_state_.Get().output_file_playing) {
1721 _engineStatisticsPtr->SetLastError(
1722 VE_ALREADY_PLAYING, kTraceError,
1723 "StartPlayingFileLocally() is already playing");
1724 return -1;
1725 }
1726
1727 {
1728 rtc::CritScope cs(&_fileCritSect);
1729
1730 // Destroy the old instance
1731 if (_outputFilePlayerPtr) {
1732 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1733 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1734 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001735 }
1736
kwiberg55b97fe2016-01-28 05:22:45 -08001737 // Create the instance
1738 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1739 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001740
kwiberg55b97fe2016-01-28 05:22:45 -08001741 if (_outputFilePlayerPtr == NULL) {
1742 _engineStatisticsPtr->SetLastError(
1743 VE_INVALID_ARGUMENT, kTraceError,
1744 "StartPlayingFileLocally() filePlayer format isnot correct");
1745 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001746 }
1747
kwiberg55b97fe2016-01-28 05:22:45 -08001748 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001749
kwiberg55b97fe2016-01-28 05:22:45 -08001750 if (_outputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1751 volumeScaling, notificationTime,
1752 stopPosition, codecInst) != 0) {
1753 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1754 "StartPlayingFile() failed to "
1755 "start file playout");
1756 _outputFilePlayerPtr->StopPlayingFile();
1757 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1758 _outputFilePlayerPtr = NULL;
1759 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001760 }
kwiberg55b97fe2016-01-28 05:22:45 -08001761 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1762 channel_state_.SetOutputFilePlaying(true);
1763 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001764
kwiberg55b97fe2016-01-28 05:22:45 -08001765 if (RegisterFilePlayingToMixer() != 0)
1766 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001767
kwiberg55b97fe2016-01-28 05:22:45 -08001768 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001769}
1770
kwiberg55b97fe2016-01-28 05:22:45 -08001771int Channel::StopPlayingFileLocally() {
1772 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1773 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001774
kwiberg55b97fe2016-01-28 05:22:45 -08001775 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001776 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001777 }
1778
1779 {
1780 rtc::CritScope cs(&_fileCritSect);
1781
1782 if (_outputFilePlayerPtr->StopPlayingFile() != 0) {
1783 _engineStatisticsPtr->SetLastError(
1784 VE_STOP_RECORDING_FAILED, kTraceError,
1785 "StopPlayingFile() could not stop playing");
1786 return -1;
1787 }
1788 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1789 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1790 _outputFilePlayerPtr = NULL;
1791 channel_state_.SetOutputFilePlaying(false);
1792 }
1793 // _fileCritSect cannot be taken while calling
1794 // SetAnonymousMixibilityStatus. Refer to comments in
1795 // StartPlayingFileLocally(const char* ...) for more details.
1796 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1797 _engineStatisticsPtr->SetLastError(
1798 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1799 "StopPlayingFile() failed to stop participant from playing as"
1800 "file in the mixer");
1801 return -1;
1802 }
1803
1804 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001805}
1806
kwiberg55b97fe2016-01-28 05:22:45 -08001807int Channel::IsPlayingFileLocally() const {
1808 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001809}
1810
kwiberg55b97fe2016-01-28 05:22:45 -08001811int Channel::RegisterFilePlayingToMixer() {
1812 // Return success for not registering for file playing to mixer if:
1813 // 1. playing file before playout is started on that channel.
1814 // 2. starting playout without file playing on that channel.
1815 if (!channel_state_.Get().playing ||
1816 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001817 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001818 }
1819
1820 // |_fileCritSect| cannot be taken while calling
1821 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1822 // frames can be pulled by the mixer. Since the frames are generated from
1823 // the file, _fileCritSect will be taken. This would result in a deadlock.
1824 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1825 channel_state_.SetOutputFilePlaying(false);
1826 rtc::CritScope cs(&_fileCritSect);
1827 _engineStatisticsPtr->SetLastError(
1828 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1829 "StartPlayingFile() failed to add participant as file to mixer");
1830 _outputFilePlayerPtr->StopPlayingFile();
1831 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1832 _outputFilePlayerPtr = NULL;
1833 return -1;
1834 }
1835
1836 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001837}
1838
niklase@google.com470e71d2011-07-07 08:21:25 +00001839int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001840 bool loop,
1841 FileFormats format,
1842 int startPosition,
1843 float volumeScaling,
1844 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001845 const CodecInst* codecInst) {
1846 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1847 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1848 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1849 "stopPosition=%d)",
1850 fileName, loop, format, volumeScaling, startPosition,
1851 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001852
kwiberg55b97fe2016-01-28 05:22:45 -08001853 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001854
kwiberg55b97fe2016-01-28 05:22:45 -08001855 if (channel_state_.Get().input_file_playing) {
1856 _engineStatisticsPtr->SetLastError(
1857 VE_ALREADY_PLAYING, kTraceWarning,
1858 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001859 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001860 }
1861
1862 // Destroy the old instance
1863 if (_inputFilePlayerPtr) {
1864 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1865 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1866 _inputFilePlayerPtr = NULL;
1867 }
1868
1869 // Create the instance
1870 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1871 (const FileFormats)format);
1872
1873 if (_inputFilePlayerPtr == NULL) {
1874 _engineStatisticsPtr->SetLastError(
1875 VE_INVALID_ARGUMENT, kTraceError,
1876 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1877 return -1;
1878 }
1879
1880 const uint32_t notificationTime(0);
1881
1882 if (_inputFilePlayerPtr->StartPlayingFile(
1883 fileName, loop, startPosition, volumeScaling, notificationTime,
1884 stopPosition, (const CodecInst*)codecInst) != 0) {
1885 _engineStatisticsPtr->SetLastError(
1886 VE_BAD_FILE, kTraceError,
1887 "StartPlayingFile() failed to start file playout");
1888 _inputFilePlayerPtr->StopPlayingFile();
1889 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1890 _inputFilePlayerPtr = NULL;
1891 return -1;
1892 }
1893 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1894 channel_state_.SetInputFilePlaying(true);
1895
1896 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001897}
1898
1899int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001900 FileFormats format,
1901 int startPosition,
1902 float volumeScaling,
1903 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001904 const CodecInst* codecInst) {
1905 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1906 "Channel::StartPlayingFileAsMicrophone(format=%d, "
1907 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1908 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001909
kwiberg55b97fe2016-01-28 05:22:45 -08001910 if (stream == NULL) {
1911 _engineStatisticsPtr->SetLastError(
1912 VE_BAD_FILE, kTraceError,
1913 "StartPlayingFileAsMicrophone NULL as input stream");
1914 return -1;
1915 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001916
kwiberg55b97fe2016-01-28 05:22:45 -08001917 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001918
kwiberg55b97fe2016-01-28 05:22:45 -08001919 if (channel_state_.Get().input_file_playing) {
1920 _engineStatisticsPtr->SetLastError(
1921 VE_ALREADY_PLAYING, kTraceWarning,
1922 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001923 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001924 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001925
kwiberg55b97fe2016-01-28 05:22:45 -08001926 // Destroy the old instance
1927 if (_inputFilePlayerPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001928 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1929 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1930 _inputFilePlayerPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001931 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001932
kwiberg55b97fe2016-01-28 05:22:45 -08001933 // Create the instance
1934 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1935 (const FileFormats)format);
1936
1937 if (_inputFilePlayerPtr == NULL) {
1938 _engineStatisticsPtr->SetLastError(
1939 VE_INVALID_ARGUMENT, kTraceError,
1940 "StartPlayingInputFile() filePlayer format isnot correct");
1941 return -1;
1942 }
1943
1944 const uint32_t notificationTime(0);
1945
1946 if (_inputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1947 volumeScaling, notificationTime,
1948 stopPosition, codecInst) != 0) {
1949 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1950 "StartPlayingFile() failed to start "
1951 "file playout");
1952 _inputFilePlayerPtr->StopPlayingFile();
1953 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1954 _inputFilePlayerPtr = NULL;
1955 return -1;
1956 }
1957
1958 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1959 channel_state_.SetInputFilePlaying(true);
1960
1961 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001962}
1963
kwiberg55b97fe2016-01-28 05:22:45 -08001964int Channel::StopPlayingFileAsMicrophone() {
1965 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1966 "Channel::StopPlayingFileAsMicrophone()");
1967
1968 rtc::CritScope cs(&_fileCritSect);
1969
1970 if (!channel_state_.Get().input_file_playing) {
1971 return 0;
1972 }
1973
1974 if (_inputFilePlayerPtr->StopPlayingFile() != 0) {
1975 _engineStatisticsPtr->SetLastError(
1976 VE_STOP_RECORDING_FAILED, kTraceError,
1977 "StopPlayingFile() could not stop playing");
1978 return -1;
1979 }
1980 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1981 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1982 _inputFilePlayerPtr = NULL;
1983 channel_state_.SetInputFilePlaying(false);
1984
1985 return 0;
1986}
1987
1988int Channel::IsPlayingFileAsMicrophone() const {
1989 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001990}
1991
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00001992int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08001993 const CodecInst* codecInst) {
1994 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1995 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00001996
kwiberg55b97fe2016-01-28 05:22:45 -08001997 if (_outputFileRecording) {
1998 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
1999 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002000 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002001 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002002
kwiberg55b97fe2016-01-28 05:22:45 -08002003 FileFormats format;
2004 const uint32_t notificationTime(0); // Not supported in VoE
2005 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002006
kwiberg55b97fe2016-01-28 05:22:45 -08002007 if ((codecInst != NULL) &&
2008 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2009 _engineStatisticsPtr->SetLastError(
2010 VE_BAD_ARGUMENT, kTraceError,
2011 "StartRecordingPlayout() invalid compression");
2012 return (-1);
2013 }
2014 if (codecInst == NULL) {
2015 format = kFileFormatPcm16kHzFile;
2016 codecInst = &dummyCodec;
2017 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2018 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2019 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2020 format = kFileFormatWavFile;
2021 } else {
2022 format = kFileFormatCompressedFile;
2023 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002024
kwiberg55b97fe2016-01-28 05:22:45 -08002025 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002026
kwiberg55b97fe2016-01-28 05:22:45 -08002027 // Destroy the old instance
2028 if (_outputFileRecorderPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002029 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2030 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2031 _outputFileRecorderPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08002032 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002033
kwiberg55b97fe2016-01-28 05:22:45 -08002034 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2035 _outputFileRecorderId, (const FileFormats)format);
2036 if (_outputFileRecorderPtr == NULL) {
2037 _engineStatisticsPtr->SetLastError(
2038 VE_INVALID_ARGUMENT, kTraceError,
2039 "StartRecordingPlayout() fileRecorder format isnot correct");
2040 return -1;
2041 }
2042
2043 if (_outputFileRecorderPtr->StartRecordingAudioFile(
2044 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2045 _engineStatisticsPtr->SetLastError(
2046 VE_BAD_FILE, kTraceError,
2047 "StartRecordingAudioFile() failed to start file recording");
2048 _outputFileRecorderPtr->StopRecording();
2049 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2050 _outputFileRecorderPtr = NULL;
2051 return -1;
2052 }
2053 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2054 _outputFileRecording = true;
2055
2056 return 0;
2057}
2058
2059int Channel::StartRecordingPlayout(OutStream* stream,
2060 const CodecInst* codecInst) {
2061 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2062 "Channel::StartRecordingPlayout()");
2063
2064 if (_outputFileRecording) {
2065 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2066 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002067 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002068 }
2069
2070 FileFormats format;
2071 const uint32_t notificationTime(0); // Not supported in VoE
2072 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2073
2074 if (codecInst != NULL && codecInst->channels != 1) {
2075 _engineStatisticsPtr->SetLastError(
2076 VE_BAD_ARGUMENT, kTraceError,
2077 "StartRecordingPlayout() invalid compression");
2078 return (-1);
2079 }
2080 if (codecInst == NULL) {
2081 format = kFileFormatPcm16kHzFile;
2082 codecInst = &dummyCodec;
2083 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2084 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2085 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2086 format = kFileFormatWavFile;
2087 } else {
2088 format = kFileFormatCompressedFile;
2089 }
2090
2091 rtc::CritScope cs(&_fileCritSect);
2092
2093 // Destroy the old instance
2094 if (_outputFileRecorderPtr) {
2095 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2096 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2097 _outputFileRecorderPtr = NULL;
2098 }
2099
2100 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2101 _outputFileRecorderId, (const FileFormats)format);
2102 if (_outputFileRecorderPtr == NULL) {
2103 _engineStatisticsPtr->SetLastError(
2104 VE_INVALID_ARGUMENT, kTraceError,
2105 "StartRecordingPlayout() fileRecorder format isnot correct");
2106 return -1;
2107 }
2108
2109 if (_outputFileRecorderPtr->StartRecordingAudioFile(*stream, *codecInst,
2110 notificationTime) != 0) {
2111 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2112 "StartRecordingPlayout() failed to "
2113 "start file recording");
2114 _outputFileRecorderPtr->StopRecording();
2115 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2116 _outputFileRecorderPtr = NULL;
2117 return -1;
2118 }
2119
2120 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2121 _outputFileRecording = true;
2122
2123 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002124}
2125
kwiberg55b97fe2016-01-28 05:22:45 -08002126int Channel::StopRecordingPlayout() {
2127 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2128 "Channel::StopRecordingPlayout()");
2129
2130 if (!_outputFileRecording) {
2131 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2132 "StopRecordingPlayout() isnot recording");
2133 return -1;
2134 }
2135
2136 rtc::CritScope cs(&_fileCritSect);
2137
2138 if (_outputFileRecorderPtr->StopRecording() != 0) {
2139 _engineStatisticsPtr->SetLastError(
2140 VE_STOP_RECORDING_FAILED, kTraceError,
2141 "StopRecording() could not stop recording");
2142 return (-1);
2143 }
2144 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2145 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2146 _outputFileRecorderPtr = NULL;
2147 _outputFileRecording = false;
2148
2149 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002150}
2151
kwiberg55b97fe2016-01-28 05:22:45 -08002152void Channel::SetMixWithMicStatus(bool mix) {
2153 rtc::CritScope cs(&_fileCritSect);
2154 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002155}
2156
kwiberg55b97fe2016-01-28 05:22:45 -08002157int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2158 int8_t currentLevel = _outputAudioLevel.Level();
2159 level = static_cast<int32_t>(currentLevel);
2160 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002161}
2162
kwiberg55b97fe2016-01-28 05:22:45 -08002163int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2164 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2165 level = static_cast<int32_t>(currentLevel);
2166 return 0;
2167}
2168
2169int Channel::SetMute(bool enable) {
2170 rtc::CritScope cs(&volume_settings_critsect_);
2171 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002172 "Channel::SetMute(enable=%d)", enable);
kwiberg55b97fe2016-01-28 05:22:45 -08002173 _mute = enable;
2174 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002175}
2176
kwiberg55b97fe2016-01-28 05:22:45 -08002177bool Channel::Mute() const {
2178 rtc::CritScope cs(&volume_settings_critsect_);
2179 return _mute;
niklase@google.com470e71d2011-07-07 08:21:25 +00002180}
2181
kwiberg55b97fe2016-01-28 05:22:45 -08002182int Channel::SetOutputVolumePan(float left, float right) {
2183 rtc::CritScope cs(&volume_settings_critsect_);
2184 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002185 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002186 _panLeft = left;
2187 _panRight = right;
2188 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002189}
2190
kwiberg55b97fe2016-01-28 05:22:45 -08002191int Channel::GetOutputVolumePan(float& left, float& right) const {
2192 rtc::CritScope cs(&volume_settings_critsect_);
2193 left = _panLeft;
2194 right = _panRight;
2195 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002196}
2197
kwiberg55b97fe2016-01-28 05:22:45 -08002198int Channel::SetChannelOutputVolumeScaling(float scaling) {
2199 rtc::CritScope cs(&volume_settings_critsect_);
2200 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002201 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002202 _outputGain = scaling;
2203 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002204}
2205
kwiberg55b97fe2016-01-28 05:22:45 -08002206int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2207 rtc::CritScope cs(&volume_settings_critsect_);
2208 scaling = _outputGain;
2209 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002210}
2211
niklase@google.com470e71d2011-07-07 08:21:25 +00002212int Channel::SendTelephoneEventOutband(unsigned char eventCode,
kwiberg55b97fe2016-01-28 05:22:45 -08002213 int lengthMs,
2214 int attenuationDb,
2215 bool playDtmfEvent) {
2216 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002217 "Channel::SendTelephoneEventOutband(..., playDtmfEvent=%d)",
2218 playDtmfEvent);
kwiberg55b97fe2016-01-28 05:22:45 -08002219 if (!Sending()) {
2220 return -1;
2221 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002222
kwiberg55b97fe2016-01-28 05:22:45 -08002223 _playOutbandDtmfEvent = playDtmfEvent;
niklase@google.com470e71d2011-07-07 08:21:25 +00002224
kwiberg55b97fe2016-01-28 05:22:45 -08002225 if (_rtpRtcpModule->SendTelephoneEventOutband(eventCode, lengthMs,
2226 attenuationDb) != 0) {
2227 _engineStatisticsPtr->SetLastError(
2228 VE_SEND_DTMF_FAILED, kTraceWarning,
2229 "SendTelephoneEventOutband() failed to send event");
2230 return -1;
2231 }
2232 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002233}
2234
2235int Channel::SendTelephoneEventInband(unsigned char eventCode,
kwiberg55b97fe2016-01-28 05:22:45 -08002236 int lengthMs,
2237 int attenuationDb,
2238 bool playDtmfEvent) {
2239 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002240 "Channel::SendTelephoneEventInband(..., playDtmfEvent=%d)",
2241 playDtmfEvent);
2242
kwiberg55b97fe2016-01-28 05:22:45 -08002243 _playInbandDtmfEvent = playDtmfEvent;
2244 _inbandDtmfQueue.AddDtmf(eventCode, lengthMs, attenuationDb);
niklase@google.com470e71d2011-07-07 08:21:25 +00002245
kwiberg55b97fe2016-01-28 05:22:45 -08002246 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002247}
2248
kwiberg55b97fe2016-01-28 05:22:45 -08002249int Channel::SetSendTelephoneEventPayloadType(unsigned char type) {
2250 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002251 "Channel::SetSendTelephoneEventPayloadType()");
kwiberg55b97fe2016-01-28 05:22:45 -08002252 if (type > 127) {
2253 _engineStatisticsPtr->SetLastError(
2254 VE_INVALID_ARGUMENT, kTraceError,
2255 "SetSendTelephoneEventPayloadType() invalid type");
2256 return -1;
2257 }
2258 CodecInst codec = {};
2259 codec.plfreq = 8000;
2260 codec.pltype = type;
2261 memcpy(codec.plname, "telephone-event", 16);
2262 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2263 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2264 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2265 _engineStatisticsPtr->SetLastError(
2266 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2267 "SetSendTelephoneEventPayloadType() failed to register send"
2268 "payload type");
2269 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002270 }
kwiberg55b97fe2016-01-28 05:22:45 -08002271 }
2272 _sendTelephoneEventPayloadType = type;
2273 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002274}
2275
kwiberg55b97fe2016-01-28 05:22:45 -08002276int Channel::GetSendTelephoneEventPayloadType(unsigned char& type) {
2277 type = _sendTelephoneEventPayloadType;
2278 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002279}
2280
kwiberg55b97fe2016-01-28 05:22:45 -08002281int Channel::UpdateRxVadDetection(AudioFrame& audioFrame) {
2282 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2283 "Channel::UpdateRxVadDetection()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002284
kwiberg55b97fe2016-01-28 05:22:45 -08002285 int vadDecision = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002286
kwiberg55b97fe2016-01-28 05:22:45 -08002287 vadDecision = (audioFrame.vad_activity_ == AudioFrame::kVadActive) ? 1 : 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002288
kwiberg55b97fe2016-01-28 05:22:45 -08002289 if ((vadDecision != _oldVadDecision) && _rxVadObserverPtr) {
2290 OnRxVadDetected(vadDecision);
2291 _oldVadDecision = vadDecision;
2292 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002293
kwiberg55b97fe2016-01-28 05:22:45 -08002294 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2295 "Channel::UpdateRxVadDetection() => vadDecision=%d",
2296 vadDecision);
2297 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002298}
2299
kwiberg55b97fe2016-01-28 05:22:45 -08002300int Channel::RegisterRxVadObserver(VoERxVadCallback& observer) {
2301 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2302 "Channel::RegisterRxVadObserver()");
2303 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002304
kwiberg55b97fe2016-01-28 05:22:45 -08002305 if (_rxVadObserverPtr) {
2306 _engineStatisticsPtr->SetLastError(
2307 VE_INVALID_OPERATION, kTraceError,
2308 "RegisterRxVadObserver() observer already enabled");
2309 return -1;
2310 }
2311 _rxVadObserverPtr = &observer;
2312 _RxVadDetection = true;
2313 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002314}
2315
kwiberg55b97fe2016-01-28 05:22:45 -08002316int Channel::DeRegisterRxVadObserver() {
2317 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2318 "Channel::DeRegisterRxVadObserver()");
2319 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002320
kwiberg55b97fe2016-01-28 05:22:45 -08002321 if (!_rxVadObserverPtr) {
2322 _engineStatisticsPtr->SetLastError(
2323 VE_INVALID_OPERATION, kTraceWarning,
2324 "DeRegisterRxVadObserver() observer already disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00002325 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002326 }
2327 _rxVadObserverPtr = NULL;
2328 _RxVadDetection = false;
2329 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002330}
2331
kwiberg55b97fe2016-01-28 05:22:45 -08002332int Channel::VoiceActivityIndicator(int& activity) {
2333 activity = _sendFrameType;
2334 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002335}
2336
2337#ifdef WEBRTC_VOICE_ENGINE_AGC
2338
kwiberg55b97fe2016-01-28 05:22:45 -08002339int Channel::SetRxAgcStatus(bool enable, AgcModes mode) {
2340 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2341 "Channel::SetRxAgcStatus(enable=%d, mode=%d)", (int)enable,
2342 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002343
kwiberg55b97fe2016-01-28 05:22:45 -08002344 GainControl::Mode agcMode = kDefaultRxAgcMode;
2345 switch (mode) {
2346 case kAgcDefault:
2347 break;
2348 case kAgcUnchanged:
2349 agcMode = rx_audioproc_->gain_control()->mode();
2350 break;
2351 case kAgcFixedDigital:
2352 agcMode = GainControl::kFixedDigital;
2353 break;
2354 case kAgcAdaptiveDigital:
2355 agcMode = GainControl::kAdaptiveDigital;
2356 break;
2357 default:
2358 _engineStatisticsPtr->SetLastError(VE_INVALID_ARGUMENT, kTraceError,
2359 "SetRxAgcStatus() invalid Agc mode");
2360 return -1;
2361 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002362
kwiberg55b97fe2016-01-28 05:22:45 -08002363 if (rx_audioproc_->gain_control()->set_mode(agcMode) != 0) {
2364 _engineStatisticsPtr->SetLastError(
2365 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc mode");
2366 return -1;
2367 }
2368 if (rx_audioproc_->gain_control()->Enable(enable) != 0) {
2369 _engineStatisticsPtr->SetLastError(
2370 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc state");
2371 return -1;
2372 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002373
kwiberg55b97fe2016-01-28 05:22:45 -08002374 _rxAgcIsEnabled = enable;
2375 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002376
kwiberg55b97fe2016-01-28 05:22:45 -08002377 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002378}
2379
kwiberg55b97fe2016-01-28 05:22:45 -08002380int Channel::GetRxAgcStatus(bool& enabled, AgcModes& mode) {
2381 bool enable = rx_audioproc_->gain_control()->is_enabled();
2382 GainControl::Mode agcMode = rx_audioproc_->gain_control()->mode();
niklase@google.com470e71d2011-07-07 08:21:25 +00002383
kwiberg55b97fe2016-01-28 05:22:45 -08002384 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002385
kwiberg55b97fe2016-01-28 05:22:45 -08002386 switch (agcMode) {
2387 case GainControl::kFixedDigital:
2388 mode = kAgcFixedDigital;
2389 break;
2390 case GainControl::kAdaptiveDigital:
2391 mode = kAgcAdaptiveDigital;
2392 break;
2393 default:
2394 _engineStatisticsPtr->SetLastError(VE_APM_ERROR, kTraceError,
2395 "GetRxAgcStatus() invalid Agc mode");
2396 return -1;
2397 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002398
kwiberg55b97fe2016-01-28 05:22:45 -08002399 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002400}
2401
kwiberg55b97fe2016-01-28 05:22:45 -08002402int Channel::SetRxAgcConfig(AgcConfig config) {
2403 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2404 "Channel::SetRxAgcConfig()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002405
kwiberg55b97fe2016-01-28 05:22:45 -08002406 if (rx_audioproc_->gain_control()->set_target_level_dbfs(
2407 config.targetLeveldBOv) != 0) {
2408 _engineStatisticsPtr->SetLastError(
2409 VE_APM_ERROR, kTraceError,
2410 "SetRxAgcConfig() failed to set target peak |level|"
2411 "(or envelope) of the Agc");
2412 return -1;
2413 }
2414 if (rx_audioproc_->gain_control()->set_compression_gain_db(
2415 config.digitalCompressionGaindB) != 0) {
2416 _engineStatisticsPtr->SetLastError(
2417 VE_APM_ERROR, kTraceError,
2418 "SetRxAgcConfig() failed to set the range in |gain| the"
2419 " digital compression stage may apply");
2420 return -1;
2421 }
2422 if (rx_audioproc_->gain_control()->enable_limiter(config.limiterEnable) !=
2423 0) {
2424 _engineStatisticsPtr->SetLastError(
2425 VE_APM_ERROR, kTraceError,
2426 "SetRxAgcConfig() failed to set hard limiter to the signal");
2427 return -1;
2428 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002429
kwiberg55b97fe2016-01-28 05:22:45 -08002430 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002431}
2432
kwiberg55b97fe2016-01-28 05:22:45 -08002433int Channel::GetRxAgcConfig(AgcConfig& config) {
2434 config.targetLeveldBOv = rx_audioproc_->gain_control()->target_level_dbfs();
2435 config.digitalCompressionGaindB =
2436 rx_audioproc_->gain_control()->compression_gain_db();
2437 config.limiterEnable = rx_audioproc_->gain_control()->is_limiter_enabled();
niklase@google.com470e71d2011-07-07 08:21:25 +00002438
kwiberg55b97fe2016-01-28 05:22:45 -08002439 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002440}
2441
kwiberg55b97fe2016-01-28 05:22:45 -08002442#endif // #ifdef WEBRTC_VOICE_ENGINE_AGC
niklase@google.com470e71d2011-07-07 08:21:25 +00002443
2444#ifdef WEBRTC_VOICE_ENGINE_NR
2445
kwiberg55b97fe2016-01-28 05:22:45 -08002446int Channel::SetRxNsStatus(bool enable, NsModes mode) {
2447 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2448 "Channel::SetRxNsStatus(enable=%d, mode=%d)", (int)enable,
2449 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002450
kwiberg55b97fe2016-01-28 05:22:45 -08002451 NoiseSuppression::Level nsLevel = kDefaultNsMode;
2452 switch (mode) {
2453 case kNsDefault:
2454 break;
2455 case kNsUnchanged:
2456 nsLevel = rx_audioproc_->noise_suppression()->level();
2457 break;
2458 case kNsConference:
2459 nsLevel = NoiseSuppression::kHigh;
2460 break;
2461 case kNsLowSuppression:
2462 nsLevel = NoiseSuppression::kLow;
2463 break;
2464 case kNsModerateSuppression:
2465 nsLevel = NoiseSuppression::kModerate;
2466 break;
2467 case kNsHighSuppression:
2468 nsLevel = NoiseSuppression::kHigh;
2469 break;
2470 case kNsVeryHighSuppression:
2471 nsLevel = NoiseSuppression::kVeryHigh;
2472 break;
2473 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002474
kwiberg55b97fe2016-01-28 05:22:45 -08002475 if (rx_audioproc_->noise_suppression()->set_level(nsLevel) != 0) {
2476 _engineStatisticsPtr->SetLastError(
2477 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS level");
2478 return -1;
2479 }
2480 if (rx_audioproc_->noise_suppression()->Enable(enable) != 0) {
2481 _engineStatisticsPtr->SetLastError(
2482 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS state");
2483 return -1;
2484 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002485
kwiberg55b97fe2016-01-28 05:22:45 -08002486 _rxNsIsEnabled = enable;
2487 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002488
kwiberg55b97fe2016-01-28 05:22:45 -08002489 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002490}
2491
kwiberg55b97fe2016-01-28 05:22:45 -08002492int Channel::GetRxNsStatus(bool& enabled, NsModes& mode) {
2493 bool enable = rx_audioproc_->noise_suppression()->is_enabled();
2494 NoiseSuppression::Level ncLevel = rx_audioproc_->noise_suppression()->level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002495
kwiberg55b97fe2016-01-28 05:22:45 -08002496 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002497
kwiberg55b97fe2016-01-28 05:22:45 -08002498 switch (ncLevel) {
2499 case NoiseSuppression::kLow:
2500 mode = kNsLowSuppression;
2501 break;
2502 case NoiseSuppression::kModerate:
2503 mode = kNsModerateSuppression;
2504 break;
2505 case NoiseSuppression::kHigh:
2506 mode = kNsHighSuppression;
2507 break;
2508 case NoiseSuppression::kVeryHigh:
2509 mode = kNsVeryHighSuppression;
2510 break;
2511 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002512
kwiberg55b97fe2016-01-28 05:22:45 -08002513 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002514}
2515
kwiberg55b97fe2016-01-28 05:22:45 -08002516#endif // #ifdef WEBRTC_VOICE_ENGINE_NR
niklase@google.com470e71d2011-07-07 08:21:25 +00002517
kwiberg55b97fe2016-01-28 05:22:45 -08002518int Channel::SetLocalSSRC(unsigned int ssrc) {
2519 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2520 "Channel::SetLocalSSRC()");
2521 if (channel_state_.Get().sending) {
2522 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2523 "SetLocalSSRC() already sending");
2524 return -1;
2525 }
2526 _rtpRtcpModule->SetSSRC(ssrc);
2527 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002528}
2529
kwiberg55b97fe2016-01-28 05:22:45 -08002530int Channel::GetLocalSSRC(unsigned int& ssrc) {
2531 ssrc = _rtpRtcpModule->SSRC();
2532 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002533}
2534
kwiberg55b97fe2016-01-28 05:22:45 -08002535int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2536 ssrc = rtp_receiver_->SSRC();
2537 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002538}
2539
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002540int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002541 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002542 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002543}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002544
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002545int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2546 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002547 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2548 if (enable &&
2549 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2550 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002551 return -1;
2552 }
2553 return 0;
2554}
2555
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002556int Channel::SetSendAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2557 return SetSendRtpHeaderExtension(enable, kRtpExtensionAbsoluteSendTime, id);
2558}
2559
2560int Channel::SetReceiveAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2561 rtp_header_parser_->DeregisterRtpHeaderExtension(
2562 kRtpExtensionAbsoluteSendTime);
kwiberg55b97fe2016-01-28 05:22:45 -08002563 if (enable &&
2564 !rtp_header_parser_->RegisterRtpHeaderExtension(
2565 kRtpExtensionAbsoluteSendTime, id)) {
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00002566 return -1;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002567 }
2568 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002569}
2570
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002571void Channel::EnableSendTransportSequenceNumber(int id) {
2572 int ret =
2573 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2574 RTC_DCHECK_EQ(0, ret);
2575}
2576
stefan3313ec92016-01-21 06:32:43 -08002577void Channel::EnableReceiveTransportSequenceNumber(int id) {
2578 rtp_header_parser_->DeregisterRtpHeaderExtension(
2579 kRtpExtensionTransportSequenceNumber);
2580 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2581 kRtpExtensionTransportSequenceNumber, id);
2582 RTC_DCHECK(ret);
2583}
2584
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002585void Channel::SetCongestionControlObjects(
2586 RtpPacketSender* rtp_packet_sender,
2587 TransportFeedbackObserver* transport_feedback_observer,
2588 PacketRouter* packet_router) {
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002589 RTC_DCHECK(packet_router != nullptr || packet_router_ != nullptr);
Stefan Holmer3842c5c2016-01-12 13:55:00 +01002590 if (transport_feedback_observer) {
2591 RTC_DCHECK(feedback_observer_proxy_.get());
2592 feedback_observer_proxy_->SetTransportFeedbackObserver(
2593 transport_feedback_observer);
2594 }
2595 if (rtp_packet_sender) {
2596 RTC_DCHECK(rtp_packet_sender_proxy_.get());
2597 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2598 }
2599 if (seq_num_allocator_proxy_.get()) {
2600 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2601 }
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002602 _rtpRtcpModule->SetStorePacketsStatus(rtp_packet_sender != nullptr, 600);
2603 if (packet_router != nullptr) {
2604 packet_router->AddRtpModule(_rtpRtcpModule.get());
2605 } else {
2606 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
2607 }
2608 packet_router_ = packet_router;
2609}
2610
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002611void Channel::SetRTCPStatus(bool enable) {
2612 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2613 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002614 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002615}
2616
kwiberg55b97fe2016-01-28 05:22:45 -08002617int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002618 RtcpMode method = _rtpRtcpModule->RTCP();
2619 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002620 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002621}
2622
kwiberg55b97fe2016-01-28 05:22:45 -08002623int Channel::SetRTCP_CNAME(const char cName[256]) {
2624 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2625 "Channel::SetRTCP_CNAME()");
2626 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2627 _engineStatisticsPtr->SetLastError(
2628 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2629 "SetRTCP_CNAME() failed to set RTCP CNAME");
2630 return -1;
2631 }
2632 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002633}
2634
kwiberg55b97fe2016-01-28 05:22:45 -08002635int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2636 if (cName == NULL) {
2637 _engineStatisticsPtr->SetLastError(
2638 VE_INVALID_ARGUMENT, kTraceError,
2639 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2640 return -1;
2641 }
2642 char cname[RTCP_CNAME_SIZE];
2643 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2644 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2645 _engineStatisticsPtr->SetLastError(
2646 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2647 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2648 return -1;
2649 }
2650 strcpy(cName, cname);
2651 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002652}
2653
kwiberg55b97fe2016-01-28 05:22:45 -08002654int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2655 unsigned int& NTPLow,
2656 unsigned int& timestamp,
2657 unsigned int& playoutTimestamp,
2658 unsigned int* jitter,
2659 unsigned short* fractionLost) {
2660 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002661
kwiberg55b97fe2016-01-28 05:22:45 -08002662 RTCPSenderInfo senderInfo;
2663 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2664 _engineStatisticsPtr->SetLastError(
2665 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2666 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2667 "side");
2668 return -1;
2669 }
2670
2671 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2672 // and octet count)
2673 NTPHigh = senderInfo.NTPseconds;
2674 NTPLow = senderInfo.NTPfraction;
2675 timestamp = senderInfo.RTPtimeStamp;
2676
2677 // --- Locally derived information
2678
2679 // This value is updated on each incoming RTCP packet (0 when no packet
2680 // has been received)
2681 playoutTimestamp = playout_timestamp_rtcp_;
2682
2683 if (NULL != jitter || NULL != fractionLost) {
2684 // Get all RTCP receiver report blocks that have been received on this
2685 // channel. If we receive RTP packets from a remote source we know the
2686 // remote SSRC and use the report block from him.
2687 // Otherwise use the first report block.
2688 std::vector<RTCPReportBlock> remote_stats;
2689 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2690 remote_stats.empty()) {
2691 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2692 "GetRemoteRTCPData() failed to measure statistics due"
2693 " to lack of received RTP and/or RTCP packets");
2694 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002695 }
2696
kwiberg55b97fe2016-01-28 05:22:45 -08002697 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2698 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2699 for (; it != remote_stats.end(); ++it) {
2700 if (it->remoteSSRC == remoteSSRC)
2701 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002702 }
kwiberg55b97fe2016-01-28 05:22:45 -08002703
2704 if (it == remote_stats.end()) {
2705 // If we have not received any RTCP packets from this SSRC it probably
2706 // means that we have not received any RTP packets.
2707 // Use the first received report block instead.
2708 it = remote_stats.begin();
2709 remoteSSRC = it->remoteSSRC;
2710 }
2711
2712 if (jitter) {
2713 *jitter = it->jitter;
2714 }
2715
2716 if (fractionLost) {
2717 *fractionLost = it->fractionLost;
2718 }
2719 }
2720 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002721}
2722
kwiberg55b97fe2016-01-28 05:22:45 -08002723int Channel::SendApplicationDefinedRTCPPacket(
2724 unsigned char subType,
2725 unsigned int name,
2726 const char* data,
2727 unsigned short dataLengthInBytes) {
2728 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2729 "Channel::SendApplicationDefinedRTCPPacket()");
2730 if (!channel_state_.Get().sending) {
2731 _engineStatisticsPtr->SetLastError(
2732 VE_NOT_SENDING, kTraceError,
2733 "SendApplicationDefinedRTCPPacket() not sending");
2734 return -1;
2735 }
2736 if (NULL == data) {
2737 _engineStatisticsPtr->SetLastError(
2738 VE_INVALID_ARGUMENT, kTraceError,
2739 "SendApplicationDefinedRTCPPacket() invalid data value");
2740 return -1;
2741 }
2742 if (dataLengthInBytes % 4 != 0) {
2743 _engineStatisticsPtr->SetLastError(
2744 VE_INVALID_ARGUMENT, kTraceError,
2745 "SendApplicationDefinedRTCPPacket() invalid length value");
2746 return -1;
2747 }
2748 RtcpMode status = _rtpRtcpModule->RTCP();
2749 if (status == RtcpMode::kOff) {
2750 _engineStatisticsPtr->SetLastError(
2751 VE_RTCP_ERROR, kTraceError,
2752 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2753 return -1;
2754 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002755
kwiberg55b97fe2016-01-28 05:22:45 -08002756 // Create and schedule the RTCP APP packet for transmission
2757 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2758 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2759 _engineStatisticsPtr->SetLastError(
2760 VE_SEND_ERROR, kTraceError,
2761 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2762 return -1;
2763 }
2764 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002765}
2766
kwiberg55b97fe2016-01-28 05:22:45 -08002767int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2768 unsigned int& maxJitterMs,
2769 unsigned int& discardedPackets) {
2770 // The jitter statistics is updated for each received RTP packet and is
2771 // based on received packets.
2772 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2773 // If RTCP is off, there is no timed thread in the RTCP module regularly
2774 // generating new stats, trigger the update manually here instead.
2775 StreamStatistician* statistician =
2776 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2777 if (statistician) {
2778 // Don't use returned statistics, use data from proxy instead so that
2779 // max jitter can be fetched atomically.
2780 RtcpStatistics s;
2781 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002782 }
kwiberg55b97fe2016-01-28 05:22:45 -08002783 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002784
kwiberg55b97fe2016-01-28 05:22:45 -08002785 ChannelStatistics stats = statistics_proxy_->GetStats();
2786 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2787 if (playoutFrequency > 0) {
2788 // Scale RTP statistics given the current playout frequency
2789 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2790 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2791 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002792
kwiberg55b97fe2016-01-28 05:22:45 -08002793 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002794
kwiberg55b97fe2016-01-28 05:22:45 -08002795 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002796}
2797
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002798int Channel::GetRemoteRTCPReportBlocks(
2799 std::vector<ReportBlock>* report_blocks) {
2800 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002801 _engineStatisticsPtr->SetLastError(
2802 VE_INVALID_ARGUMENT, kTraceError,
2803 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002804 return -1;
2805 }
2806
2807 // Get the report blocks from the latest received RTCP Sender or Receiver
2808 // Report. Each element in the vector contains the sender's SSRC and a
2809 // report block according to RFC 3550.
2810 std::vector<RTCPReportBlock> rtcp_report_blocks;
2811 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002812 return -1;
2813 }
2814
2815 if (rtcp_report_blocks.empty())
2816 return 0;
2817
2818 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2819 for (; it != rtcp_report_blocks.end(); ++it) {
2820 ReportBlock report_block;
2821 report_block.sender_SSRC = it->remoteSSRC;
2822 report_block.source_SSRC = it->sourceSSRC;
2823 report_block.fraction_lost = it->fractionLost;
2824 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2825 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2826 report_block.interarrival_jitter = it->jitter;
2827 report_block.last_SR_timestamp = it->lastSR;
2828 report_block.delay_since_last_SR = it->delaySinceLastSR;
2829 report_blocks->push_back(report_block);
2830 }
2831 return 0;
2832}
2833
kwiberg55b97fe2016-01-28 05:22:45 -08002834int Channel::GetRTPStatistics(CallStatistics& stats) {
2835 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002836
kwiberg55b97fe2016-01-28 05:22:45 -08002837 // The jitter statistics is updated for each received RTP packet and is
2838 // based on received packets.
2839 RtcpStatistics statistics;
2840 StreamStatistician* statistician =
2841 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2842 if (!statistician ||
2843 !statistician->GetStatistics(&statistics,
2844 _rtpRtcpModule->RTCP() == RtcpMode::kOff)) {
2845 _engineStatisticsPtr->SetLastError(
2846 VE_CANNOT_RETRIEVE_RTP_STAT, kTraceWarning,
2847 "GetRTPStatistics() failed to read RTP statistics from the "
2848 "RTP/RTCP module");
2849 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002850
kwiberg55b97fe2016-01-28 05:22:45 -08002851 stats.fractionLost = statistics.fraction_lost;
2852 stats.cumulativeLost = statistics.cumulative_lost;
2853 stats.extendedMax = statistics.extended_max_sequence_number;
2854 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002855
kwiberg55b97fe2016-01-28 05:22:45 -08002856 // --- RTT
2857 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002858
kwiberg55b97fe2016-01-28 05:22:45 -08002859 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002860
kwiberg55b97fe2016-01-28 05:22:45 -08002861 size_t bytesSent(0);
2862 uint32_t packetsSent(0);
2863 size_t bytesReceived(0);
2864 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002865
kwiberg55b97fe2016-01-28 05:22:45 -08002866 if (statistician) {
2867 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2868 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002869
kwiberg55b97fe2016-01-28 05:22:45 -08002870 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2871 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2872 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2873 " output will not be complete");
2874 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002875
kwiberg55b97fe2016-01-28 05:22:45 -08002876 stats.bytesSent = bytesSent;
2877 stats.packetsSent = packetsSent;
2878 stats.bytesReceived = bytesReceived;
2879 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002880
kwiberg55b97fe2016-01-28 05:22:45 -08002881 // --- Timestamps
2882 {
2883 rtc::CritScope lock(&ts_stats_lock_);
2884 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2885 }
2886 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002887}
2888
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002889int Channel::SetREDStatus(bool enable, int redPayloadtype) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002890 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002891 "Channel::SetREDStatus()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002892
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002893 if (enable) {
2894 if (redPayloadtype < 0 || redPayloadtype > 127) {
2895 _engineStatisticsPtr->SetLastError(
2896 VE_PLTYPE_ERROR, kTraceError,
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002897 "SetREDStatus() invalid RED payload type");
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002898 return -1;
2899 }
2900
2901 if (SetRedPayloadType(redPayloadtype) < 0) {
2902 _engineStatisticsPtr->SetLastError(
2903 VE_CODEC_ERROR, kTraceError,
2904 "SetSecondarySendCodec() Failed to register RED ACM");
2905 return -1;
2906 }
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002907 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002908
minyue@webrtc.orgaa5ea1c2014-05-23 15:16:51 +00002909 if (audio_coding_->SetREDStatus(enable) != 0) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002910 _engineStatisticsPtr->SetLastError(
2911 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgaa5ea1c2014-05-23 15:16:51 +00002912 "SetREDStatus() failed to set RED state in the ACM");
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002913 return -1;
2914 }
2915 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002916}
2917
kwiberg55b97fe2016-01-28 05:22:45 -08002918int Channel::GetREDStatus(bool& enabled, int& redPayloadtype) {
2919 enabled = audio_coding_->REDStatus();
2920 if (enabled) {
2921 int8_t payloadType = 0;
2922 if (_rtpRtcpModule->SendREDPayloadType(&payloadType) != 0) {
2923 _engineStatisticsPtr->SetLastError(
2924 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2925 "GetREDStatus() failed to retrieve RED PT from RTP/RTCP "
2926 "module");
2927 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002928 }
kwiberg55b97fe2016-01-28 05:22:45 -08002929 redPayloadtype = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +00002930 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002931 }
2932 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002933}
2934
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002935int Channel::SetCodecFECStatus(bool enable) {
2936 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2937 "Channel::SetCodecFECStatus()");
2938
2939 if (audio_coding_->SetCodecFEC(enable) != 0) {
2940 _engineStatisticsPtr->SetLastError(
2941 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2942 "SetCodecFECStatus() failed to set FEC state");
2943 return -1;
2944 }
2945 return 0;
2946}
2947
2948bool Channel::GetCodecFECStatus() {
2949 bool enabled = audio_coding_->CodecFEC();
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002950 return enabled;
2951}
2952
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002953void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2954 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002955 // If pacing is enabled we always store packets.
2956 if (!pacing_enabled_)
2957 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002958 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
2959 rtp_receiver_->SetNACKStatus(enable ? kNackRtcp : kNackOff);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002960 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002961 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002962 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002963 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002964}
2965
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002966// Called when we are missing one or more packets.
2967int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002968 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2969}
2970
kwiberg55b97fe2016-01-28 05:22:45 -08002971uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2972 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2973 "Channel::Demultiplex()");
2974 _audioFrame.CopyFrom(audioFrame);
2975 _audioFrame.id_ = _channelId;
2976 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002977}
2978
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002979void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002980 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002981 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002982 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002983 CodecInst codec;
2984 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002985
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002986 // Never upsample or upmix the capture signal here. This should be done at the
2987 // end of the send chain.
2988 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2989 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2990 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2991 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002992}
2993
kwiberg55b97fe2016-01-28 05:22:45 -08002994uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2995 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2996 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002997
kwiberg55b97fe2016-01-28 05:22:45 -08002998 if (_audioFrame.samples_per_channel_ == 0) {
2999 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3000 "Channel::PrepareEncodeAndSend() invalid audio frame");
3001 return 0xFFFFFFFF;
3002 }
3003
3004 if (channel_state_.Get().input_file_playing) {
3005 MixOrReplaceAudioWithFile(mixingFrequency);
3006 }
3007
3008 bool is_muted = Mute(); // Cache locally as Mute() takes a lock.
3009 if (is_muted) {
3010 AudioFrameOperations::Mute(_audioFrame);
3011 }
3012
3013 if (channel_state_.Get().input_external_media) {
3014 rtc::CritScope cs(&_callbackCritSect);
3015 const bool isStereo = (_audioFrame.num_channels_ == 2);
3016 if (_inputExternalMediaCallbackPtr) {
3017 _inputExternalMediaCallbackPtr->Process(
3018 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
3019 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
3020 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00003021 }
kwiberg55b97fe2016-01-28 05:22:45 -08003022 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003023
kwiberg55b97fe2016-01-28 05:22:45 -08003024 InsertInbandDtmfTone();
niklase@google.com470e71d2011-07-07 08:21:25 +00003025
kwiberg55b97fe2016-01-28 05:22:45 -08003026 if (_includeAudioLevelIndication) {
3027 size_t length =
3028 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
andrew@webrtc.org21299d42014-05-14 19:00:59 +00003029 if (is_muted) {
kwiberg55b97fe2016-01-28 05:22:45 -08003030 rms_level_.ProcessMuted(length);
3031 } else {
3032 rms_level_.Process(_audioFrame.data_, length);
niklase@google.com470e71d2011-07-07 08:21:25 +00003033 }
kwiberg55b97fe2016-01-28 05:22:45 -08003034 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003035
kwiberg55b97fe2016-01-28 05:22:45 -08003036 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003037}
3038
kwiberg55b97fe2016-01-28 05:22:45 -08003039uint32_t Channel::EncodeAndSend() {
3040 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
3041 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003042
kwiberg55b97fe2016-01-28 05:22:45 -08003043 assert(_audioFrame.num_channels_ <= 2);
3044 if (_audioFrame.samples_per_channel_ == 0) {
3045 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3046 "Channel::EncodeAndSend() invalid audio frame");
3047 return 0xFFFFFFFF;
3048 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003049
kwiberg55b97fe2016-01-28 05:22:45 -08003050 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00003051
kwiberg55b97fe2016-01-28 05:22:45 -08003052 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00003053
kwiberg55b97fe2016-01-28 05:22:45 -08003054 // The ACM resamples internally.
3055 _audioFrame.timestamp_ = _timeStamp;
3056 // This call will trigger AudioPacketizationCallback::SendData if encoding
3057 // is done and payload is ready for packetization and transmission.
3058 // Otherwise, it will return without invoking the callback.
3059 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
3060 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
3061 "Channel::EncodeAndSend() ACM encoding failed");
3062 return 0xFFFFFFFF;
3063 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003064
kwiberg55b97fe2016-01-28 05:22:45 -08003065 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
3066 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003067}
3068
Minyue2013aec2015-05-13 14:14:42 +02003069void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08003070 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003071 Channel* channel = associate_send_channel_.channel();
3072 if (channel && channel->ChannelId() == channel_id) {
3073 // If this channel is associated with a send channel of the specified
3074 // Channel ID, disassociate with it.
3075 ChannelOwner ref(NULL);
3076 associate_send_channel_ = ref;
3077 }
3078}
3079
kwiberg55b97fe2016-01-28 05:22:45 -08003080int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
3081 VoEMediaProcess& processObject) {
3082 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3083 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003084
kwiberg55b97fe2016-01-28 05:22:45 -08003085 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003086
kwiberg55b97fe2016-01-28 05:22:45 -08003087 if (kPlaybackPerChannel == type) {
3088 if (_outputExternalMediaCallbackPtr) {
3089 _engineStatisticsPtr->SetLastError(
3090 VE_INVALID_OPERATION, kTraceError,
3091 "Channel::RegisterExternalMediaProcessing() "
3092 "output external media already enabled");
3093 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003094 }
kwiberg55b97fe2016-01-28 05:22:45 -08003095 _outputExternalMediaCallbackPtr = &processObject;
3096 _outputExternalMedia = true;
3097 } else if (kRecordingPerChannel == type) {
3098 if (_inputExternalMediaCallbackPtr) {
3099 _engineStatisticsPtr->SetLastError(
3100 VE_INVALID_OPERATION, kTraceError,
3101 "Channel::RegisterExternalMediaProcessing() "
3102 "output external media already enabled");
3103 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003104 }
kwiberg55b97fe2016-01-28 05:22:45 -08003105 _inputExternalMediaCallbackPtr = &processObject;
3106 channel_state_.SetInputExternalMedia(true);
3107 }
3108 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003109}
3110
kwiberg55b97fe2016-01-28 05:22:45 -08003111int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
3112 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3113 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003114
kwiberg55b97fe2016-01-28 05:22:45 -08003115 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003116
kwiberg55b97fe2016-01-28 05:22:45 -08003117 if (kPlaybackPerChannel == type) {
3118 if (!_outputExternalMediaCallbackPtr) {
3119 _engineStatisticsPtr->SetLastError(
3120 VE_INVALID_OPERATION, kTraceWarning,
3121 "Channel::DeRegisterExternalMediaProcessing() "
3122 "output external media already disabled");
3123 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003124 }
kwiberg55b97fe2016-01-28 05:22:45 -08003125 _outputExternalMedia = false;
3126 _outputExternalMediaCallbackPtr = NULL;
3127 } else if (kRecordingPerChannel == type) {
3128 if (!_inputExternalMediaCallbackPtr) {
3129 _engineStatisticsPtr->SetLastError(
3130 VE_INVALID_OPERATION, kTraceWarning,
3131 "Channel::DeRegisterExternalMediaProcessing() "
3132 "input external media already disabled");
3133 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003134 }
kwiberg55b97fe2016-01-28 05:22:45 -08003135 channel_state_.SetInputExternalMedia(false);
3136 _inputExternalMediaCallbackPtr = NULL;
3137 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003138
kwiberg55b97fe2016-01-28 05:22:45 -08003139 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003140}
3141
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003142int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08003143 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3144 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003145
kwiberg55b97fe2016-01-28 05:22:45 -08003146 if (channel_state_.Get().playing) {
3147 _engineStatisticsPtr->SetLastError(
3148 VE_INVALID_OPERATION, kTraceError,
3149 "Channel::SetExternalMixing() "
3150 "external mixing cannot be changed while playing.");
3151 return -1;
3152 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003153
kwiberg55b97fe2016-01-28 05:22:45 -08003154 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003155
kwiberg55b97fe2016-01-28 05:22:45 -08003156 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003157}
3158
kwiberg55b97fe2016-01-28 05:22:45 -08003159int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3160 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003161}
3162
wu@webrtc.org24301a62013-12-13 19:17:43 +00003163void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3164 audio_coding_->GetDecodingCallStatistics(stats);
3165}
3166
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003167bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3168 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003169 rtc::CritScope lock(&video_sync_lock_);
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003170 if (_average_jitter_buffer_delay_us == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003171 return false;
3172 }
kwiberg55b97fe2016-01-28 05:22:45 -08003173 *jitter_buffer_delay_ms =
3174 (_average_jitter_buffer_delay_us + 500) / 1000 + _recPacketDelayMs;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003175 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003176 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003177}
3178
solenberg358057b2015-11-27 10:46:42 -08003179uint32_t Channel::GetDelayEstimate() const {
3180 int jitter_buffer_delay_ms = 0;
3181 int playout_buffer_delay_ms = 0;
3182 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3183 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3184}
3185
deadbeef74375882015-08-13 12:09:10 -07003186int Channel::LeastRequiredDelayMs() const {
3187 return audio_coding_->LeastRequiredDelayMs();
3188}
3189
kwiberg55b97fe2016-01-28 05:22:45 -08003190int Channel::SetMinimumPlayoutDelay(int delayMs) {
3191 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3192 "Channel::SetMinimumPlayoutDelay()");
3193 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3194 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3195 _engineStatisticsPtr->SetLastError(
3196 VE_INVALID_ARGUMENT, kTraceError,
3197 "SetMinimumPlayoutDelay() invalid min delay");
3198 return -1;
3199 }
3200 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3201 _engineStatisticsPtr->SetLastError(
3202 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3203 "SetMinimumPlayoutDelay() failed to set min playout delay");
3204 return -1;
3205 }
3206 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003207}
3208
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003209int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003210 uint32_t playout_timestamp_rtp = 0;
3211 {
tommi31fc21f2016-01-21 10:37:37 -08003212 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003213 playout_timestamp_rtp = playout_timestamp_rtp_;
3214 }
kwiberg55b97fe2016-01-28 05:22:45 -08003215 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003216 _engineStatisticsPtr->SetLastError(
3217 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3218 "GetPlayoutTimestamp() failed to retrieve timestamp");
3219 return -1;
3220 }
deadbeef74375882015-08-13 12:09:10 -07003221 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003222 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003223}
3224
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003225int Channel::SetInitTimestamp(unsigned int timestamp) {
3226 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003227 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003228 if (channel_state_.Get().sending) {
3229 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3230 "SetInitTimestamp() already sending");
3231 return -1;
3232 }
3233 _rtpRtcpModule->SetStartTimestamp(timestamp);
3234 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003235}
3236
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003237int Channel::SetInitSequenceNumber(short sequenceNumber) {
3238 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3239 "Channel::SetInitSequenceNumber()");
3240 if (channel_state_.Get().sending) {
3241 _engineStatisticsPtr->SetLastError(
3242 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3243 return -1;
3244 }
3245 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3246 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003247}
3248
kwiberg55b97fe2016-01-28 05:22:45 -08003249int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3250 RtpReceiver** rtp_receiver) const {
3251 *rtpRtcpModule = _rtpRtcpModule.get();
3252 *rtp_receiver = rtp_receiver_.get();
3253 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003254}
3255
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003256// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3257// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003258int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwiberg@webrtc.org00b8f6b2015-02-26 14:34:55 +00003259 rtc::scoped_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003260 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003261
kwiberg55b97fe2016-01-28 05:22:45 -08003262 {
3263 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003264
kwiberg55b97fe2016-01-28 05:22:45 -08003265 if (_inputFilePlayerPtr == NULL) {
3266 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3267 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3268 " doesnt exist");
3269 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003270 }
3271
kwiberg55b97fe2016-01-28 05:22:45 -08003272 if (_inputFilePlayerPtr->Get10msAudioFromFile(fileBuffer.get(), fileSamples,
3273 mixingFrequency) == -1) {
3274 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3275 "Channel::MixOrReplaceAudioWithFile() file mixing "
3276 "failed");
3277 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003278 }
kwiberg55b97fe2016-01-28 05:22:45 -08003279 if (fileSamples == 0) {
3280 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3281 "Channel::MixOrReplaceAudioWithFile() file is ended");
3282 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003283 }
kwiberg55b97fe2016-01-28 05:22:45 -08003284 }
3285
3286 assert(_audioFrame.samples_per_channel_ == fileSamples);
3287
3288 if (_mixFileWithMicrophone) {
3289 // Currently file stream is always mono.
3290 // TODO(xians): Change the code when FilePlayer supports real stereo.
3291 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3292 1, fileSamples);
3293 } else {
3294 // Replace ACM audio with file.
3295 // Currently file stream is always mono.
3296 // TODO(xians): Change the code when FilePlayer supports real stereo.
3297 _audioFrame.UpdateFrame(
3298 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3299 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3300 }
3301 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003302}
3303
kwiberg55b97fe2016-01-28 05:22:45 -08003304int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3305 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003306
kwiberg55b97fe2016-01-28 05:22:45 -08003307 rtc::scoped_ptr<int16_t[]> fileBuffer(new int16_t[960]);
3308 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003309
kwiberg55b97fe2016-01-28 05:22:45 -08003310 {
3311 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003312
kwiberg55b97fe2016-01-28 05:22:45 -08003313 if (_outputFilePlayerPtr == NULL) {
3314 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3315 "Channel::MixAudioWithFile() file mixing failed");
3316 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003317 }
3318
kwiberg55b97fe2016-01-28 05:22:45 -08003319 // We should get the frequency we ask for.
3320 if (_outputFilePlayerPtr->Get10msAudioFromFile(
3321 fileBuffer.get(), fileSamples, mixingFrequency) == -1) {
3322 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3323 "Channel::MixAudioWithFile() file mixing failed");
3324 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003325 }
kwiberg55b97fe2016-01-28 05:22:45 -08003326 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003327
kwiberg55b97fe2016-01-28 05:22:45 -08003328 if (audioFrame.samples_per_channel_ == fileSamples) {
3329 // Currently file stream is always mono.
3330 // TODO(xians): Change the code when FilePlayer supports real stereo.
3331 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3332 fileSamples);
3333 } else {
3334 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3335 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3336 ") != "
3337 "fileSamples(%" PRIuS ")",
3338 audioFrame.samples_per_channel_, fileSamples);
3339 return -1;
3340 }
3341
3342 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003343}
3344
kwiberg55b97fe2016-01-28 05:22:45 -08003345int Channel::InsertInbandDtmfTone() {
3346 // Check if we should start a new tone.
3347 if (_inbandDtmfQueue.PendingDtmf() && !_inbandDtmfGenerator.IsAddingTone() &&
3348 _inbandDtmfGenerator.DelaySinceLastTone() >
3349 kMinTelephoneEventSeparationMs) {
3350 int8_t eventCode(0);
3351 uint16_t lengthMs(0);
3352 uint8_t attenuationDb(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003353
kwiberg55b97fe2016-01-28 05:22:45 -08003354 eventCode = _inbandDtmfQueue.NextDtmf(&lengthMs, &attenuationDb);
3355 _inbandDtmfGenerator.AddTone(eventCode, lengthMs, attenuationDb);
3356 if (_playInbandDtmfEvent) {
3357 // Add tone to output mixer using a reduced length to minimize
3358 // risk of echo.
3359 _outputMixerPtr->PlayDtmfTone(eventCode, lengthMs - 80, attenuationDb);
3360 }
3361 }
3362
3363 if (_inbandDtmfGenerator.IsAddingTone()) {
3364 uint16_t frequency(0);
3365 _inbandDtmfGenerator.GetSampleRate(frequency);
3366
3367 if (frequency != _audioFrame.sample_rate_hz_) {
3368 // Update sample rate of Dtmf tone since the mixing frequency
3369 // has changed.
3370 _inbandDtmfGenerator.SetSampleRate(
3371 (uint16_t)(_audioFrame.sample_rate_hz_));
3372 // Reset the tone to be added taking the new sample rate into
3373 // account.
3374 _inbandDtmfGenerator.ResetTone();
niklase@google.com470e71d2011-07-07 08:21:25 +00003375 }
3376
kwiberg55b97fe2016-01-28 05:22:45 -08003377 int16_t toneBuffer[320];
3378 uint16_t toneSamples(0);
3379 // Get 10ms tone segment and set time since last tone to zero
3380 if (_inbandDtmfGenerator.Get10msTone(toneBuffer, toneSamples) == -1) {
3381 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3382 "Channel::EncodeAndSend() inserting Dtmf failed");
3383 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003384 }
kwiberg55b97fe2016-01-28 05:22:45 -08003385
3386 // Replace mixed audio with DTMF tone.
3387 for (size_t sample = 0; sample < _audioFrame.samples_per_channel_;
3388 sample++) {
3389 for (size_t channel = 0; channel < _audioFrame.num_channels_; channel++) {
3390 const size_t index = sample * _audioFrame.num_channels_ + channel;
3391 _audioFrame.data_[index] = toneBuffer[sample];
3392 }
3393 }
3394
3395 assert(_audioFrame.samples_per_channel_ == toneSamples);
3396 } else {
3397 // Add 10ms to "delay-since-last-tone" counter
3398 _inbandDtmfGenerator.UpdateDelaySinceLastTone();
3399 }
3400 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003401}
3402
deadbeef74375882015-08-13 12:09:10 -07003403void Channel::UpdatePlayoutTimestamp(bool rtcp) {
3404 uint32_t playout_timestamp = 0;
3405
kwiberg55b97fe2016-01-28 05:22:45 -08003406 if (audio_coding_->PlayoutTimestamp(&playout_timestamp) == -1) {
deadbeef74375882015-08-13 12:09:10 -07003407 // This can happen if this channel has not been received any RTP packet. In
3408 // this case, NetEq is not capable of computing playout timestamp.
3409 return;
3410 }
3411
3412 uint16_t delay_ms = 0;
3413 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003414 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003415 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3416 " delay from the ADM");
3417 _engineStatisticsPtr->SetLastError(
3418 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3419 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3420 return;
3421 }
3422
3423 jitter_buffer_playout_timestamp_ = playout_timestamp;
3424
3425 // Remove the playout delay.
3426 playout_timestamp -= (delay_ms * (GetPlayoutFrequency() / 1000));
3427
kwiberg55b97fe2016-01-28 05:22:45 -08003428 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003429 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
3430 playout_timestamp);
3431
3432 {
tommi31fc21f2016-01-21 10:37:37 -08003433 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003434 if (rtcp) {
3435 playout_timestamp_rtcp_ = playout_timestamp;
3436 } else {
3437 playout_timestamp_rtp_ = playout_timestamp;
3438 }
3439 playout_delay_ms_ = delay_ms;
3440 }
3441}
3442
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003443// Called for incoming RTP packets after successful RTP header parsing.
3444void Channel::UpdatePacketDelay(uint32_t rtp_timestamp,
3445 uint16_t sequence_number) {
kwiberg55b97fe2016-01-28 05:22:45 -08003446 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003447 "Channel::UpdatePacketDelay(timestamp=%lu, sequenceNumber=%u)",
3448 rtp_timestamp, sequence_number);
niklase@google.com470e71d2011-07-07 08:21:25 +00003449
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003450 // Get frequency of last received payload
wu@webrtc.org94454b72014-06-05 20:34:08 +00003451 int rtp_receive_frequency = GetPlayoutFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +00003452
turaj@webrtc.org167b6df2013-12-13 21:05:07 +00003453 // |jitter_buffer_playout_timestamp_| updated in UpdatePlayoutTimestamp for
3454 // every incoming packet.
kwiberg55b97fe2016-01-28 05:22:45 -08003455 uint32_t timestamp_diff_ms =
3456 (rtp_timestamp - jitter_buffer_playout_timestamp_) /
3457 (rtp_receive_frequency / 1000);
henrik.lundin@webrtc.orgd6692992014-03-20 12:04:09 +00003458 if (!IsNewerTimestamp(rtp_timestamp, jitter_buffer_playout_timestamp_) ||
3459 timestamp_diff_ms > (2 * kVoiceEngineMaxMinPlayoutDelayMs)) {
3460 // If |jitter_buffer_playout_timestamp_| is newer than the incoming RTP
3461 // timestamp, the resulting difference is negative, but is set to zero.
3462 // This can happen when a network glitch causes a packet to arrive late,
3463 // and during long comfort noise periods with clock drift.
3464 timestamp_diff_ms = 0;
3465 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003466
kwiberg55b97fe2016-01-28 05:22:45 -08003467 uint16_t packet_delay_ms =
3468 (rtp_timestamp - _previousTimestamp) / (rtp_receive_frequency / 1000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003469
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003470 _previousTimestamp = rtp_timestamp;
niklase@google.com470e71d2011-07-07 08:21:25 +00003471
kwiberg55b97fe2016-01-28 05:22:45 -08003472 if (timestamp_diff_ms == 0)
3473 return;
niklase@google.com470e71d2011-07-07 08:21:25 +00003474
deadbeef74375882015-08-13 12:09:10 -07003475 {
tommi31fc21f2016-01-21 10:37:37 -08003476 rtc::CritScope lock(&video_sync_lock_);
niklase@google.com470e71d2011-07-07 08:21:25 +00003477
deadbeef74375882015-08-13 12:09:10 -07003478 if (packet_delay_ms >= 10 && packet_delay_ms <= 60) {
3479 _recPacketDelayMs = packet_delay_ms;
3480 }
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003481
deadbeef74375882015-08-13 12:09:10 -07003482 if (_average_jitter_buffer_delay_us == 0) {
3483 _average_jitter_buffer_delay_us = timestamp_diff_ms * 1000;
3484 return;
3485 }
3486
3487 // Filter average delay value using exponential filter (alpha is
3488 // 7/8). We derive 1000 *_average_jitter_buffer_delay_us here (reduces
3489 // risk of rounding error) and compensate for it in GetDelayEstimate()
3490 // later.
kwiberg55b97fe2016-01-28 05:22:45 -08003491 _average_jitter_buffer_delay_us =
3492 (_average_jitter_buffer_delay_us * 7 + 1000 * timestamp_diff_ms + 500) /
3493 8;
deadbeef74375882015-08-13 12:09:10 -07003494 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003495}
3496
kwiberg55b97fe2016-01-28 05:22:45 -08003497void Channel::RegisterReceiveCodecsToRTPModule() {
3498 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3499 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003500
kwiberg55b97fe2016-01-28 05:22:45 -08003501 CodecInst codec;
3502 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003503
kwiberg55b97fe2016-01-28 05:22:45 -08003504 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3505 // Open up the RTP/RTCP receiver for all supported codecs
3506 if ((audio_coding_->Codec(idx, &codec) == -1) ||
3507 (rtp_receiver_->RegisterReceivePayload(
3508 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3509 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
3510 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3511 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3512 " to register %s (%d/%d/%" PRIuS
3513 "/%d) to RTP/RTCP "
3514 "receiver",
3515 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3516 codec.rate);
3517 } else {
3518 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3519 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3520 "(%d/%d/%" PRIuS
3521 "/%d) has been added to the RTP/RTCP "
3522 "receiver",
3523 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3524 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003525 }
kwiberg55b97fe2016-01-28 05:22:45 -08003526 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003527}
3528
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00003529// Assuming this method is called with valid payload type.
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003530int Channel::SetRedPayloadType(int red_payload_type) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003531 CodecInst codec;
3532 bool found_red = false;
3533
3534 // Get default RED settings from the ACM database
3535 const int num_codecs = AudioCodingModule::NumberOfCodecs();
3536 for (int idx = 0; idx < num_codecs; idx++) {
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00003537 audio_coding_->Codec(idx, &codec);
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003538 if (!STR_CASE_CMP(codec.plname, "RED")) {
3539 found_red = true;
3540 break;
3541 }
3542 }
3543
3544 if (!found_red) {
3545 _engineStatisticsPtr->SetLastError(
3546 VE_CODEC_ERROR, kTraceError,
3547 "SetRedPayloadType() RED is not supported");
3548 return -1;
3549 }
3550
turaj@webrtc.org9d532fd2013-01-31 18:34:19 +00003551 codec.pltype = red_payload_type;
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00003552 if (audio_coding_->RegisterSendCodec(codec) < 0) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003553 _engineStatisticsPtr->SetLastError(
3554 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3555 "SetRedPayloadType() RED registration in ACM module failed");
3556 return -1;
3557 }
3558
3559 if (_rtpRtcpModule->SetSendREDPayloadType(red_payload_type) != 0) {
3560 _engineStatisticsPtr->SetLastError(
3561 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
3562 "SetRedPayloadType() RED registration in RTP/RTCP module failed");
3563 return -1;
3564 }
3565 return 0;
3566}
3567
kwiberg55b97fe2016-01-28 05:22:45 -08003568int Channel::SetSendRtpHeaderExtension(bool enable,
3569 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003570 unsigned char id) {
3571 int error = 0;
3572 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3573 if (enable) {
3574 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3575 }
3576 return error;
3577}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003578
wu@webrtc.org94454b72014-06-05 20:34:08 +00003579int32_t Channel::GetPlayoutFrequency() {
3580 int32_t playout_frequency = audio_coding_->PlayoutFrequency();
3581 CodecInst current_recive_codec;
3582 if (audio_coding_->ReceiveCodec(&current_recive_codec) == 0) {
3583 if (STR_CASE_CMP("G722", current_recive_codec.plname) == 0) {
3584 // Even though the actual sampling rate for G.722 audio is
3585 // 16,000 Hz, the RTP clock rate for the G722 payload format is
3586 // 8,000 Hz because that value was erroneously assigned in
3587 // RFC 1890 and must remain unchanged for backward compatibility.
3588 playout_frequency = 8000;
3589 } else if (STR_CASE_CMP("opus", current_recive_codec.plname) == 0) {
3590 // We are resampling Opus internally to 32,000 Hz until all our
3591 // DSP routines can operate at 48,000 Hz, but the RTP clock
3592 // rate for the Opus payload format is standardized to 48,000 Hz,
3593 // because that is the maximum supported decoding sampling rate.
3594 playout_frequency = 48000;
3595 }
3596 }
3597 return playout_frequency;
3598}
3599
Minyue2013aec2015-05-13 14:14:42 +02003600int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003601 RtcpMode method = _rtpRtcpModule->RTCP();
3602 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003603 return 0;
3604 }
3605 std::vector<RTCPReportBlock> report_blocks;
3606 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003607
3608 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003609 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003610 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003611 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003612 Channel* channel = associate_send_channel_.channel();
3613 // Tries to get RTT from an associated channel. This is important for
3614 // receive-only channels.
3615 if (channel) {
3616 // To prevent infinite recursion and deadlock, calling GetRTT of
3617 // associate channel should always use "false" for argument:
3618 // |allow_associate_channel|.
3619 rtt = channel->GetRTT(false);
3620 }
3621 }
3622 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003623 }
3624
3625 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3626 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3627 for (; it != report_blocks.end(); ++it) {
3628 if (it->remoteSSRC == remoteSSRC)
3629 break;
3630 }
3631 if (it == report_blocks.end()) {
3632 // We have not received packets with SSRC matching the report blocks.
3633 // To calculate RTT we try with the SSRC of the first report block.
3634 // This is very important for send-only channels where we don't know
3635 // the SSRC of the other end.
3636 remoteSSRC = report_blocks[0].remoteSSRC;
3637 }
Minyue2013aec2015-05-13 14:14:42 +02003638
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003639 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003640 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003641 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003642 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3643 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003644 return 0;
3645 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003646 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003647}
3648
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003649} // namespace voe
3650} // namespace webrtc