blob: 7c9c7c0fd0fa427bd44086a1d949be49d15b0b65 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
henrika@webrtc.org2919e952012-01-31 08:45:03 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000011#include "webrtc/voice_engine/channel.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Henrik Lundin64dad832015-05-11 12:44:23 +020013#include <algorithm>
Tommif888bb52015-12-12 01:37:01 +010014#include <utility>
Henrik Lundin64dad832015-05-11 12:44:23 +020015
Ivo Creusenae856f22015-09-17 16:30:16 +020016#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080017#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000018#include "webrtc/base/format_macros.h"
pbosad856222015-11-27 09:48:36 -080019#include "webrtc/base/logging.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010020#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000021#include "webrtc/base/timeutils.h"
minyue@webrtc.orge509f942013-09-12 17:03:00 +000022#include "webrtc/common.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020023#include "webrtc/config.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000024#include "webrtc/modules/audio_device/include/audio_device.h"
25#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010026#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010027#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010028#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
29#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
30#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000031#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010032#include "webrtc/modules/utility/include/audio_frame_operations.h"
33#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010034#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000035#include "webrtc/voice_engine/include/voe_base.h"
36#include "webrtc/voice_engine/include/voe_external_media.h"
37#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
38#include "webrtc/voice_engine/output_mixer.h"
39#include "webrtc/voice_engine/statistics.h"
40#include "webrtc/voice_engine/transmit_mixer.h"
41#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000042
andrew@webrtc.org50419b02012-11-14 19:07:54 +000043namespace webrtc {
44namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000045
solenberg8842c3e2016-03-11 03:06:41 -080046const int kTelephoneEventAttenuationdB = 10;
47
Stefan Holmerb86d4e42015-12-07 10:26:18 +010048class TransportFeedbackProxy : public TransportFeedbackObserver {
49 public:
50 TransportFeedbackProxy() : feedback_observer_(nullptr) {
51 pacer_thread_.DetachFromThread();
52 network_thread_.DetachFromThread();
53 }
54
55 void SetTransportFeedbackObserver(
56 TransportFeedbackObserver* feedback_observer) {
57 RTC_DCHECK(thread_checker_.CalledOnValidThread());
58 rtc::CritScope lock(&crit_);
59 feedback_observer_ = feedback_observer;
60 }
61
62 // Implements TransportFeedbackObserver.
63 void AddPacket(uint16_t sequence_number,
64 size_t length,
65 bool was_paced) override {
66 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
67 rtc::CritScope lock(&crit_);
68 if (feedback_observer_)
69 feedback_observer_->AddPacket(sequence_number, length, was_paced);
70 }
71 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
72 RTC_DCHECK(network_thread_.CalledOnValidThread());
73 rtc::CritScope lock(&crit_);
74 if (feedback_observer_)
75 feedback_observer_->OnTransportFeedback(feedback);
76 }
77
78 private:
79 rtc::CriticalSection crit_;
80 rtc::ThreadChecker thread_checker_;
81 rtc::ThreadChecker pacer_thread_;
82 rtc::ThreadChecker network_thread_;
83 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
84};
85
86class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
87 public:
88 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
89 pacer_thread_.DetachFromThread();
90 }
91
92 void SetSequenceNumberAllocator(
93 TransportSequenceNumberAllocator* seq_num_allocator) {
94 RTC_DCHECK(thread_checker_.CalledOnValidThread());
95 rtc::CritScope lock(&crit_);
96 seq_num_allocator_ = seq_num_allocator;
97 }
98
99 // Implements TransportSequenceNumberAllocator.
100 uint16_t AllocateSequenceNumber() override {
101 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
102 rtc::CritScope lock(&crit_);
103 if (!seq_num_allocator_)
104 return 0;
105 return seq_num_allocator_->AllocateSequenceNumber();
106 }
107
108 private:
109 rtc::CriticalSection crit_;
110 rtc::ThreadChecker thread_checker_;
111 rtc::ThreadChecker pacer_thread_;
112 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
113};
114
115class RtpPacketSenderProxy : public RtpPacketSender {
116 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800117 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100118
119 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
120 RTC_DCHECK(thread_checker_.CalledOnValidThread());
121 rtc::CritScope lock(&crit_);
122 rtp_packet_sender_ = rtp_packet_sender;
123 }
124
125 // Implements RtpPacketSender.
126 void InsertPacket(Priority priority,
127 uint32_t ssrc,
128 uint16_t sequence_number,
129 int64_t capture_time_ms,
130 size_t bytes,
131 bool retransmission) override {
132 rtc::CritScope lock(&crit_);
133 if (rtp_packet_sender_) {
134 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
135 capture_time_ms, bytes, retransmission);
136 }
137 }
138
139 private:
140 rtc::ThreadChecker thread_checker_;
141 rtc::CriticalSection crit_;
142 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
143};
144
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000145// Extend the default RTCP statistics struct with max_jitter, defined as the
146// maximum jitter value seen in an RTCP report block.
147struct ChannelStatistics : public RtcpStatistics {
148 ChannelStatistics() : rtcp(), max_jitter(0) {}
149
150 RtcpStatistics rtcp;
151 uint32_t max_jitter;
152};
153
154// Statistics callback, called at each generation of a new RTCP report block.
155class StatisticsProxy : public RtcpStatisticsCallback {
156 public:
tommi31fc21f2016-01-21 10:37:37 -0800157 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000158 virtual ~StatisticsProxy() {}
159
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000160 void StatisticsUpdated(const RtcpStatistics& statistics,
161 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000162 if (ssrc != ssrc_)
163 return;
164
tommi31fc21f2016-01-21 10:37:37 -0800165 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000166 stats_.rtcp = statistics;
167 if (statistics.jitter > stats_.max_jitter) {
168 stats_.max_jitter = statistics.jitter;
169 }
170 }
171
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000172 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000173
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000174 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800175 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000176 return stats_;
177 }
178
179 private:
180 // StatisticsUpdated calls are triggered from threads in the RTP module,
181 // while GetStats calls can be triggered from the public voice engine API,
182 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800183 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000184 const uint32_t ssrc_;
185 ChannelStatistics stats_;
186};
187
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000188class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000189 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000190 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
191 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000192
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000193 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
194 // Not used for Voice Engine.
195 }
196
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000197 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
198 int64_t rtt,
199 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000200 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
201 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
202 // report for VoiceEngine?
203 if (report_blocks.empty())
204 return;
205
206 int fraction_lost_aggregate = 0;
207 int total_number_of_packets = 0;
208
209 // If receiving multiple report blocks, calculate the weighted average based
210 // on the number of packets a report refers to.
211 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
212 block_it != report_blocks.end(); ++block_it) {
213 // Find the previous extended high sequence number for this remote SSRC,
214 // to calculate the number of RTP packets this report refers to. Ignore if
215 // we haven't seen this SSRC before.
216 std::map<uint32_t, uint32_t>::iterator seq_num_it =
217 extended_max_sequence_number_.find(block_it->sourceSSRC);
218 int number_of_packets = 0;
219 if (seq_num_it != extended_max_sequence_number_.end()) {
220 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
221 }
222 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
223 total_number_of_packets += number_of_packets;
224
225 extended_max_sequence_number_[block_it->sourceSSRC] =
226 block_it->extendedHighSeqNum;
227 }
228 int weighted_fraction_lost = 0;
229 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800230 weighted_fraction_lost =
231 (fraction_lost_aggregate + total_number_of_packets / 2) /
232 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000233 }
234 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000235 }
236
237 private:
238 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000239 // Maps remote side ssrc to extended highest sequence number received.
240 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000241};
242
kwiberg55b97fe2016-01-28 05:22:45 -0800243int32_t Channel::SendData(FrameType frameType,
244 uint8_t payloadType,
245 uint32_t timeStamp,
246 const uint8_t* payloadData,
247 size_t payloadSize,
248 const RTPFragmentationHeader* fragmentation) {
249 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
250 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
251 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
252 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000253
kwiberg55b97fe2016-01-28 05:22:45 -0800254 if (_includeAudioLevelIndication) {
255 // Store current audio level in the RTP/RTCP module.
256 // The level will be used in combination with voice-activity state
257 // (frameType) to add an RTP header extension
258 _rtpRtcpModule->SetAudioLevel(rms_level_.RMS());
259 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000260
kwiberg55b97fe2016-01-28 05:22:45 -0800261 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
262 // packetization.
263 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
264 if (_rtpRtcpModule->SendOutgoingData(
265 (FrameType&)frameType, payloadType, timeStamp,
266 // Leaving the time when this frame was
267 // received from the capture device as
268 // undefined for voice for now.
269 -1, payloadData, payloadSize, fragmentation) == -1) {
270 _engineStatisticsPtr->SetLastError(
271 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
272 "Channel::SendData() failed to send data to RTP/RTCP module");
273 return -1;
274 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000275
kwiberg55b97fe2016-01-28 05:22:45 -0800276 _lastLocalTimeStamp = timeStamp;
277 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000278
kwiberg55b97fe2016-01-28 05:22:45 -0800279 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000280}
281
kwiberg55b97fe2016-01-28 05:22:45 -0800282int32_t Channel::InFrameType(FrameType frame_type) {
283 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
284 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000285
kwiberg55b97fe2016-01-28 05:22:45 -0800286 rtc::CritScope cs(&_callbackCritSect);
287 _sendFrameType = (frame_type == kAudioFrameSpeech);
288 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000289}
290
kwiberg55b97fe2016-01-28 05:22:45 -0800291int32_t Channel::OnRxVadDetected(int vadDecision) {
292 rtc::CritScope cs(&_callbackCritSect);
293 if (_rxVadObserverPtr) {
294 _rxVadObserverPtr->OnRxVad(_channelId, vadDecision);
295 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000296
kwiberg55b97fe2016-01-28 05:22:45 -0800297 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000298}
299
stefan1d8a5062015-10-02 03:39:33 -0700300bool Channel::SendRtp(const uint8_t* data,
301 size_t len,
302 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800303 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
304 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000305
kwiberg55b97fe2016-01-28 05:22:45 -0800306 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000307
kwiberg55b97fe2016-01-28 05:22:45 -0800308 if (_transportPtr == NULL) {
309 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
310 "Channel::SendPacket() failed to send RTP packet due to"
311 " invalid transport object");
312 return false;
313 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000314
kwiberg55b97fe2016-01-28 05:22:45 -0800315 uint8_t* bufferToSendPtr = (uint8_t*)data;
316 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000317
kwiberg55b97fe2016-01-28 05:22:45 -0800318 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
319 std::string transport_name =
320 _externalTransport ? "external transport" : "WebRtc sockets";
321 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
322 "Channel::SendPacket() RTP transmission using %s failed",
323 transport_name.c_str());
324 return false;
325 }
326 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000327}
328
kwiberg55b97fe2016-01-28 05:22:45 -0800329bool Channel::SendRtcp(const uint8_t* data, size_t len) {
330 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
331 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000332
kwiberg55b97fe2016-01-28 05:22:45 -0800333 rtc::CritScope cs(&_callbackCritSect);
334 if (_transportPtr == NULL) {
335 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
336 "Channel::SendRtcp() failed to send RTCP packet"
337 " due to invalid transport object");
338 return false;
339 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000340
kwiberg55b97fe2016-01-28 05:22:45 -0800341 uint8_t* bufferToSendPtr = (uint8_t*)data;
342 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000343
kwiberg55b97fe2016-01-28 05:22:45 -0800344 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
345 if (n < 0) {
346 std::string transport_name =
347 _externalTransport ? "external transport" : "WebRtc sockets";
348 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
349 "Channel::SendRtcp() transmission using %s failed",
350 transport_name.c_str());
351 return false;
352 }
353 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000354}
355
kwiberg55b97fe2016-01-28 05:22:45 -0800356void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
357 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
358 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000359
kwiberg55b97fe2016-01-28 05:22:45 -0800360 // Update ssrc so that NTP for AV sync can be updated.
361 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000362}
363
Peter Boströmac547a62015-09-17 23:03:57 +0200364void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
365 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
366 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
367 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000368}
369
Peter Boströmac547a62015-09-17 23:03:57 +0200370int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000371 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000372 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000373 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800374 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200375 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800376 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
377 "Channel::OnInitializeDecoder(payloadType=%d, "
378 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
379 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000380
kwiberg55b97fe2016-01-28 05:22:45 -0800381 CodecInst receiveCodec = {0};
382 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000383
kwiberg55b97fe2016-01-28 05:22:45 -0800384 receiveCodec.pltype = payloadType;
385 receiveCodec.plfreq = frequency;
386 receiveCodec.channels = channels;
387 receiveCodec.rate = rate;
388 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000389
kwiberg55b97fe2016-01-28 05:22:45 -0800390 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
391 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000392
kwiberg55b97fe2016-01-28 05:22:45 -0800393 // Register the new codec to the ACM
394 if (audio_coding_->RegisterReceiveCodec(receiveCodec) == -1) {
395 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
396 "Channel::OnInitializeDecoder() invalid codec ("
397 "pt=%d, name=%s) received - 1",
398 payloadType, payloadName);
399 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
400 return -1;
401 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000402
kwiberg55b97fe2016-01-28 05:22:45 -0800403 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000404}
405
kwiberg55b97fe2016-01-28 05:22:45 -0800406int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
407 size_t payloadSize,
408 const WebRtcRTPHeader* rtpHeader) {
409 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
410 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
411 ","
412 " payloadType=%u, audioChannel=%" PRIuS ")",
413 payloadSize, rtpHeader->header.payloadType,
414 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000415
kwiberg55b97fe2016-01-28 05:22:45 -0800416 if (!channel_state_.Get().playing) {
417 // Avoid inserting into NetEQ when we are not playing. Count the
418 // packet as discarded.
419 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
420 "received packet is discarded since playing is not"
421 " activated");
422 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000423 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800424 }
425
426 // Push the incoming payload (parsed and ready for decoding) into the ACM
427 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
428 0) {
429 _engineStatisticsPtr->SetLastError(
430 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
431 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
432 return -1;
433 }
434
435 // Update the packet delay.
436 UpdatePacketDelay(rtpHeader->header.timestamp,
437 rtpHeader->header.sequenceNumber);
438
439 int64_t round_trip_time = 0;
440 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
441 NULL);
442
443 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
444 if (!nack_list.empty()) {
445 // Can't use nack_list.data() since it's not supported by all
446 // compilers.
447 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
448 }
449 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000450}
451
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000452bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000453 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000454 RTPHeader header;
455 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
456 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
457 "IncomingPacket invalid RTP header");
458 return false;
459 }
460 header.payload_type_frequency =
461 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
462 if (header.payload_type_frequency < 0)
463 return false;
464 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
465}
466
kwiberg55b97fe2016-01-28 05:22:45 -0800467int32_t Channel::GetAudioFrame(int32_t id, AudioFrame* audioFrame) {
468 if (event_log_) {
469 unsigned int ssrc;
470 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
471 event_log_->LogAudioPlayout(ssrc);
472 }
473 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
474 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame) ==
475 -1) {
476 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
477 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
478 // In all likelihood, the audio in this frame is garbage. We return an
479 // error so that the audio mixer module doesn't add it to the mix. As
480 // a result, it won't be played out and the actions skipped here are
481 // irrelevant.
482 return -1;
483 }
484
485 if (_RxVadDetection) {
486 UpdateRxVadDetection(*audioFrame);
487 }
488
489 // Convert module ID to internal VoE channel ID
490 audioFrame->id_ = VoEChannelId(audioFrame->id_);
491 // Store speech type for dead-or-alive detection
492 _outputSpeechType = audioFrame->speech_type_;
493
494 ChannelState::State state = channel_state_.Get();
495
496 if (state.rx_apm_is_enabled) {
497 int err = rx_audioproc_->ProcessStream(audioFrame);
498 if (err) {
499 LOG(LS_ERROR) << "ProcessStream() error: " << err;
500 assert(false);
Ivo Creusenae856f22015-09-17 16:30:16 +0200501 }
kwiberg55b97fe2016-01-28 05:22:45 -0800502 }
503
504 {
505 // Pass the audio buffers to an optional sink callback, before applying
506 // scaling/panning, as that applies to the mix operation.
507 // External recipients of the audio (e.g. via AudioTrack), will do their
508 // own mixing/dynamic processing.
509 rtc::CritScope cs(&_callbackCritSect);
510 if (audio_sink_) {
511 AudioSinkInterface::Data data(
512 &audioFrame->data_[0], audioFrame->samples_per_channel_,
513 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
514 audioFrame->timestamp_);
515 audio_sink_->OnData(data);
516 }
517 }
518
519 float output_gain = 1.0f;
520 float left_pan = 1.0f;
521 float right_pan = 1.0f;
522 {
523 rtc::CritScope cs(&volume_settings_critsect_);
524 output_gain = _outputGain;
525 left_pan = _panLeft;
526 right_pan = _panRight;
527 }
528
529 // Output volume scaling
530 if (output_gain < 0.99f || output_gain > 1.01f) {
531 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
532 }
533
534 // Scale left and/or right channel(s) if stereo and master balance is
535 // active
536
537 if (left_pan != 1.0f || right_pan != 1.0f) {
538 if (audioFrame->num_channels_ == 1) {
539 // Emulate stereo mode since panning is active.
540 // The mono signal is copied to both left and right channels here.
541 AudioFrameOperations::MonoToStereo(audioFrame);
542 }
543 // For true stereo mode (when we are receiving a stereo signal), no
544 // action is needed.
545
546 // Do the panning operation (the audio frame contains stereo at this
547 // stage)
548 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
549 }
550
551 // Mix decoded PCM output with file if file mixing is enabled
552 if (state.output_file_playing) {
553 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
554 }
555
556 // External media
557 if (_outputExternalMedia) {
558 rtc::CritScope cs(&_callbackCritSect);
559 const bool isStereo = (audioFrame->num_channels_ == 2);
560 if (_outputExternalMediaCallbackPtr) {
561 _outputExternalMediaCallbackPtr->Process(
562 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
563 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
564 isStereo);
565 }
566 }
567
568 // Record playout if enabled
569 {
570 rtc::CritScope cs(&_fileCritSect);
571
572 if (_outputFileRecording && _outputFileRecorderPtr) {
573 _outputFileRecorderPtr->RecordAudioToFile(*audioFrame);
574 }
575 }
576
577 // Measure audio level (0-9)
578 _outputAudioLevel.ComputeLevel(*audioFrame);
579
580 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
581 // The first frame with a valid rtp timestamp.
582 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
583 }
584
585 if (capture_start_rtp_time_stamp_ >= 0) {
586 // audioFrame.timestamp_ should be valid from now on.
587
588 // Compute elapsed time.
589 int64_t unwrap_timestamp =
590 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
591 audioFrame->elapsed_time_ms_ =
592 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
593 (GetPlayoutFrequency() / 1000);
594
niklase@google.com470e71d2011-07-07 08:21:25 +0000595 {
kwiberg55b97fe2016-01-28 05:22:45 -0800596 rtc::CritScope lock(&ts_stats_lock_);
597 // Compute ntp time.
598 audioFrame->ntp_time_ms_ =
599 ntp_estimator_.Estimate(audioFrame->timestamp_);
600 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
601 if (audioFrame->ntp_time_ms_ > 0) {
602 // Compute |capture_start_ntp_time_ms_| so that
603 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
604 capture_start_ntp_time_ms_ =
605 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000606 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000607 }
kwiberg55b97fe2016-01-28 05:22:45 -0800608 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000609
kwiberg55b97fe2016-01-28 05:22:45 -0800610 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000611}
612
kwiberg55b97fe2016-01-28 05:22:45 -0800613int32_t Channel::NeededFrequency(int32_t id) const {
614 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
615 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000616
kwiberg55b97fe2016-01-28 05:22:45 -0800617 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000618
kwiberg55b97fe2016-01-28 05:22:45 -0800619 // Determine highest needed receive frequency
620 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000621
kwiberg55b97fe2016-01-28 05:22:45 -0800622 // Return the bigger of playout and receive frequency in the ACM.
623 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
624 highestNeeded = audio_coding_->PlayoutFrequency();
625 } else {
626 highestNeeded = receiveFrequency;
627 }
628
629 // Special case, if we're playing a file on the playout side
630 // we take that frequency into consideration as well
631 // This is not needed on sending side, since the codec will
632 // limit the spectrum anyway.
633 if (channel_state_.Get().output_file_playing) {
634 rtc::CritScope cs(&_fileCritSect);
635 if (_outputFilePlayerPtr) {
636 if (_outputFilePlayerPtr->Frequency() > highestNeeded) {
637 highestNeeded = _outputFilePlayerPtr->Frequency();
638 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000639 }
kwiberg55b97fe2016-01-28 05:22:45 -0800640 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000641
kwiberg55b97fe2016-01-28 05:22:45 -0800642 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000643}
644
ivocb04965c2015-09-09 00:09:43 -0700645int32_t Channel::CreateChannel(Channel*& channel,
646 int32_t channelId,
647 uint32_t instanceId,
648 RtcEventLog* const event_log,
649 const Config& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800650 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
651 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
652 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000653
kwiberg55b97fe2016-01-28 05:22:45 -0800654 channel = new Channel(channelId, instanceId, event_log, config);
655 if (channel == NULL) {
656 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
657 "Channel::CreateChannel() unable to allocate memory for"
658 " channel");
659 return -1;
660 }
661 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000662}
663
kwiberg55b97fe2016-01-28 05:22:45 -0800664void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
665 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
666 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
667 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000668
kwiberg55b97fe2016-01-28 05:22:45 -0800669 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000670}
671
kwiberg55b97fe2016-01-28 05:22:45 -0800672void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
673 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
674 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
675 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000676
kwiberg55b97fe2016-01-28 05:22:45 -0800677 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000678}
679
kwiberg55b97fe2016-01-28 05:22:45 -0800680void Channel::PlayFileEnded(int32_t id) {
681 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
682 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000683
kwiberg55b97fe2016-01-28 05:22:45 -0800684 if (id == _inputFilePlayerId) {
685 channel_state_.SetInputFilePlaying(false);
686 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
687 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000688 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800689 } else if (id == _outputFilePlayerId) {
690 channel_state_.SetOutputFilePlaying(false);
691 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
692 "Channel::PlayFileEnded() => output file player module is"
693 " shutdown");
694 }
695}
696
697void Channel::RecordFileEnded(int32_t id) {
698 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
699 "Channel::RecordFileEnded(id=%d)", id);
700
701 assert(id == _outputFileRecorderId);
702
703 rtc::CritScope cs(&_fileCritSect);
704
705 _outputFileRecording = false;
706 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
707 "Channel::RecordFileEnded() => output file recorder module is"
708 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000709}
710
pbos@webrtc.org92135212013-05-14 08:31:39 +0000711Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000712 uint32_t instanceId,
ivocb04965c2015-09-09 00:09:43 -0700713 RtcEventLog* const event_log,
714 const Config& config)
tommi31fc21f2016-01-21 10:37:37 -0800715 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100716 _channelId(channelId),
717 event_log_(event_log),
718 rtp_header_parser_(RtpHeaderParser::Create()),
719 rtp_payload_registry_(
720 new RTPPayloadRegistry(RTPPayloadStrategy::CreateStrategy(true))),
721 rtp_receive_statistics_(
722 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
723 rtp_receiver_(
724 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
solenbergb69395b2016-03-16 07:05:17 -0700725 nullptr,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100726 this,
727 this,
728 rtp_payload_registry_.get())),
729 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
730 _outputAudioLevel(),
731 _externalTransport(false),
732 _inputFilePlayerPtr(NULL),
733 _outputFilePlayerPtr(NULL),
734 _outputFileRecorderPtr(NULL),
735 // Avoid conflict with other channels by adding 1024 - 1026,
736 // won't use as much as 1024 channels.
737 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
738 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
739 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
740 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100741 _outputExternalMedia(false),
742 _inputExternalMediaCallbackPtr(NULL),
743 _outputExternalMediaCallbackPtr(NULL),
744 _timeStamp(0), // This is just an offset, RTP module will add it's own
745 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100746 ntp_estimator_(Clock::GetRealTimeClock()),
747 jitter_buffer_playout_timestamp_(0),
748 playout_timestamp_rtp_(0),
749 playout_timestamp_rtcp_(0),
750 playout_delay_ms_(0),
751 _numberOfDiscardedPackets(0),
752 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100753 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
754 capture_start_rtp_time_stamp_(-1),
755 capture_start_ntp_time_ms_(-1),
756 _engineStatisticsPtr(NULL),
757 _outputMixerPtr(NULL),
758 _transmitMixerPtr(NULL),
759 _moduleProcessThreadPtr(NULL),
760 _audioDeviceModulePtr(NULL),
761 _voiceEngineObserverPtr(NULL),
762 _callbackCritSectPtr(NULL),
763 _transportPtr(NULL),
764 _rxVadObserverPtr(NULL),
765 _oldVadDecision(-1),
766 _sendFrameType(0),
767 _externalMixing(false),
768 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700769 input_mute_(false),
770 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100771 _panLeft(1.0f),
772 _panRight(1.0f),
773 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100774 _lastLocalTimeStamp(0),
775 _lastPayloadType(0),
776 _includeAudioLevelIndication(false),
777 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100778 _average_jitter_buffer_delay_us(0),
779 _previousTimestamp(0),
780 _recPacketDelayMs(20),
781 _RxVadDetection(false),
782 _rxAgcIsEnabled(false),
783 _rxNsIsEnabled(false),
784 restored_packet_in_use_(false),
785 rtcp_observer_(new VoERtcpObserver(this)),
786 network_predictor_(new NetworkPredictor(Clock::GetRealTimeClock())),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100787 associate_send_channel_(ChannelOwner(nullptr)),
788 pacing_enabled_(config.Get<VoicePacing>().enabled),
stefanbba9dec2016-02-01 04:39:55 -0800789 feedback_observer_proxy_(new TransportFeedbackProxy()),
790 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
791 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()) {
kwiberg55b97fe2016-01-28 05:22:45 -0800792 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
793 "Channel::Channel() - ctor");
794 AudioCodingModule::Config acm_config;
795 acm_config.id = VoEModuleId(instanceId, channelId);
796 if (config.Get<NetEqCapacityConfig>().enabled) {
797 // Clamping the buffer capacity at 20 packets. While going lower will
798 // probably work, it makes little sense.
799 acm_config.neteq_config.max_packets_in_buffer =
800 std::max(20, config.Get<NetEqCapacityConfig>().capacity);
801 }
802 acm_config.neteq_config.enable_fast_accelerate =
803 config.Get<NetEqFastAccelerate>().enabled;
804 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200805
kwiberg55b97fe2016-01-28 05:22:45 -0800806 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000807
kwiberg55b97fe2016-01-28 05:22:45 -0800808 RtpRtcp::Configuration configuration;
809 configuration.audio = true;
810 configuration.outgoing_transport = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800811 configuration.receive_statistics = rtp_receive_statistics_.get();
812 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800813 if (pacing_enabled_) {
814 configuration.paced_sender = rtp_packet_sender_proxy_.get();
815 configuration.transport_sequence_number_allocator =
816 seq_num_allocator_proxy_.get();
817 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
818 }
kwiberg55b97fe2016-01-28 05:22:45 -0800819 configuration.event_log = event_log;
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000820
kwiberg55b97fe2016-01-28 05:22:45 -0800821 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100822 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000823
kwiberg55b97fe2016-01-28 05:22:45 -0800824 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
825 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
826 statistics_proxy_.get());
aluebs@webrtc.orgf927fd62014-04-16 11:58:18 +0000827
kwiberg55b97fe2016-01-28 05:22:45 -0800828 Config audioproc_config;
829 audioproc_config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
830 rx_audioproc_.reset(AudioProcessing::Create(audioproc_config));
niklase@google.com470e71d2011-07-07 08:21:25 +0000831}
832
kwiberg55b97fe2016-01-28 05:22:45 -0800833Channel::~Channel() {
834 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
835 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
836 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000837
kwiberg55b97fe2016-01-28 05:22:45 -0800838 if (_outputExternalMedia) {
839 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
840 }
841 if (channel_state_.Get().input_external_media) {
842 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
843 }
844 StopSend();
845 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000846
kwiberg55b97fe2016-01-28 05:22:45 -0800847 {
848 rtc::CritScope cs(&_fileCritSect);
849 if (_inputFilePlayerPtr) {
850 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
851 _inputFilePlayerPtr->StopPlayingFile();
852 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
853 _inputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000854 }
kwiberg55b97fe2016-01-28 05:22:45 -0800855 if (_outputFilePlayerPtr) {
856 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
857 _outputFilePlayerPtr->StopPlayingFile();
858 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
859 _outputFilePlayerPtr = NULL;
860 }
861 if (_outputFileRecorderPtr) {
862 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
863 _outputFileRecorderPtr->StopRecording();
864 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
865 _outputFileRecorderPtr = NULL;
866 }
867 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000868
kwiberg55b97fe2016-01-28 05:22:45 -0800869 // The order to safely shutdown modules in a channel is:
870 // 1. De-register callbacks in modules
871 // 2. De-register modules in process thread
872 // 3. Destroy modules
873 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
874 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
875 "~Channel() failed to de-register transport callback"
876 " (Audio coding module)");
877 }
878 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
879 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
880 "~Channel() failed to de-register VAD callback"
881 " (Audio coding module)");
882 }
883 // De-register modules in process thread
884 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +0000885
kwiberg55b97fe2016-01-28 05:22:45 -0800886 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +0000887}
888
kwiberg55b97fe2016-01-28 05:22:45 -0800889int32_t Channel::Init() {
890 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
891 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000892
kwiberg55b97fe2016-01-28 05:22:45 -0800893 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000894
kwiberg55b97fe2016-01-28 05:22:45 -0800895 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000896
kwiberg55b97fe2016-01-28 05:22:45 -0800897 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
898 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
899 "Channel::Init() must call SetEngineInformation() first");
900 return -1;
901 }
902
903 // --- Add modules to process thread (for periodic schedulation)
904
905 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
906
907 // --- ACM initialization
908
909 if (audio_coding_->InitializeReceiver() == -1) {
910 _engineStatisticsPtr->SetLastError(
911 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
912 "Channel::Init() unable to initialize the ACM - 1");
913 return -1;
914 }
915
916 // --- RTP/RTCP module initialization
917
918 // Ensure that RTCP is enabled by default for the created channel.
919 // Note that, the module will keep generating RTCP until it is explicitly
920 // disabled by the user.
921 // After StopListen (when no sockets exists), RTCP packets will no longer
922 // be transmitted since the Transport object will then be invalid.
923 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
924 // RTCP is enabled by default.
925 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
926 // --- Register all permanent callbacks
927 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
928 (audio_coding_->RegisterVADCallback(this) == -1);
929
930 if (fail) {
931 _engineStatisticsPtr->SetLastError(
932 VE_CANNOT_INIT_CHANNEL, kTraceError,
933 "Channel::Init() callbacks not registered");
934 return -1;
935 }
936
937 // --- Register all supported codecs to the receiving side of the
938 // RTP/RTCP module
939
940 CodecInst codec;
941 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
942
943 for (int idx = 0; idx < nSupportedCodecs; idx++) {
944 // Open up the RTP/RTCP receiver for all supported codecs
945 if ((audio_coding_->Codec(idx, &codec) == -1) ||
946 (rtp_receiver_->RegisterReceivePayload(
947 codec.plname, codec.pltype, codec.plfreq, codec.channels,
948 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
949 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
950 "Channel::Init() unable to register %s "
951 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
952 codec.plname, codec.pltype, codec.plfreq, codec.channels,
953 codec.rate);
954 } else {
955 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
956 "Channel::Init() %s (%d/%d/%" PRIuS
957 "/%d) has been "
958 "added to the RTP/RTCP receiver",
959 codec.plname, codec.pltype, codec.plfreq, codec.channels,
960 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000961 }
962
kwiberg55b97fe2016-01-28 05:22:45 -0800963 // Ensure that PCMU is used as default codec on the sending side
964 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
965 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +0000966 }
967
kwiberg55b97fe2016-01-28 05:22:45 -0800968 // Register default PT for outband 'telephone-event'
969 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
970 if ((_rtpRtcpModule->RegisterSendPayload(codec) == -1) ||
971 (audio_coding_->RegisterReceiveCodec(codec) == -1)) {
972 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
973 "Channel::Init() failed to register outband "
974 "'telephone-event' (%d/%d) correctly",
975 codec.pltype, codec.plfreq);
976 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000977 }
978
kwiberg55b97fe2016-01-28 05:22:45 -0800979 if (!STR_CASE_CMP(codec.plname, "CN")) {
980 if ((audio_coding_->RegisterSendCodec(codec) == -1) ||
981 (audio_coding_->RegisterReceiveCodec(codec) == -1) ||
982 (_rtpRtcpModule->RegisterSendPayload(codec) == -1)) {
983 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
984 "Channel::Init() failed to register CN (%d/%d) "
985 "correctly - 1",
986 codec.pltype, codec.plfreq);
987 }
988 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000989#ifdef WEBRTC_CODEC_RED
kwiberg55b97fe2016-01-28 05:22:45 -0800990 // Register RED to the receiving side of the ACM.
991 // We will not receive an OnInitializeDecoder() callback for RED.
992 if (!STR_CASE_CMP(codec.plname, "RED")) {
993 if (audio_coding_->RegisterReceiveCodec(codec) == -1) {
994 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
995 "Channel::Init() failed to register RED (%d/%d) "
996 "correctly",
997 codec.pltype, codec.plfreq);
998 }
999 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001000#endif
kwiberg55b97fe2016-01-28 05:22:45 -08001001 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001002
kwiberg55b97fe2016-01-28 05:22:45 -08001003 if (rx_audioproc_->noise_suppression()->set_level(kDefaultNsMode) != 0) {
1004 LOG(LS_ERROR) << "noise_suppression()->set_level(kDefaultNsMode) failed.";
1005 return -1;
1006 }
1007 if (rx_audioproc_->gain_control()->set_mode(kDefaultRxAgcMode) != 0) {
1008 LOG(LS_ERROR) << "gain_control()->set_mode(kDefaultRxAgcMode) failed.";
1009 return -1;
1010 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001011
kwiberg55b97fe2016-01-28 05:22:45 -08001012 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001013}
1014
kwiberg55b97fe2016-01-28 05:22:45 -08001015int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1016 OutputMixer& outputMixer,
1017 voe::TransmitMixer& transmitMixer,
1018 ProcessThread& moduleProcessThread,
1019 AudioDeviceModule& audioDeviceModule,
1020 VoiceEngineObserver* voiceEngineObserver,
1021 rtc::CriticalSection* callbackCritSect) {
1022 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1023 "Channel::SetEngineInformation()");
1024 _engineStatisticsPtr = &engineStatistics;
1025 _outputMixerPtr = &outputMixer;
1026 _transmitMixerPtr = &transmitMixer,
1027 _moduleProcessThreadPtr = &moduleProcessThread;
1028 _audioDeviceModulePtr = &audioDeviceModule;
1029 _voiceEngineObserverPtr = voiceEngineObserver;
1030 _callbackCritSectPtr = callbackCritSect;
1031 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001032}
1033
kwiberg55b97fe2016-01-28 05:22:45 -08001034int32_t Channel::UpdateLocalTimeStamp() {
1035 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1036 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001037}
1038
kwibergb7f89d62016-02-17 10:04:18 -08001039void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001040 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001041 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001042}
1043
kwiberg55b97fe2016-01-28 05:22:45 -08001044int32_t Channel::StartPlayout() {
1045 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1046 "Channel::StartPlayout()");
1047 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001048 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001049 }
1050
1051 if (!_externalMixing) {
1052 // Add participant as candidates for mixing.
1053 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1054 _engineStatisticsPtr->SetLastError(
1055 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1056 "StartPlayout() failed to add participant to mixer");
1057 return -1;
1058 }
1059 }
1060
1061 channel_state_.SetPlaying(true);
1062 if (RegisterFilePlayingToMixer() != 0)
1063 return -1;
1064
1065 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001066}
1067
kwiberg55b97fe2016-01-28 05:22:45 -08001068int32_t Channel::StopPlayout() {
1069 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1070 "Channel::StopPlayout()");
1071 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001072 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001073 }
1074
1075 if (!_externalMixing) {
1076 // Remove participant as candidates for mixing
1077 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1078 _engineStatisticsPtr->SetLastError(
1079 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1080 "StopPlayout() failed to remove participant from mixer");
1081 return -1;
1082 }
1083 }
1084
1085 channel_state_.SetPlaying(false);
1086 _outputAudioLevel.Clear();
1087
1088 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001089}
1090
kwiberg55b97fe2016-01-28 05:22:45 -08001091int32_t Channel::StartSend() {
1092 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1093 "Channel::StartSend()");
1094 // Resume the previous sequence number which was reset by StopSend().
1095 // This needs to be done before |sending| is set to true.
1096 if (send_sequence_number_)
1097 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001098
kwiberg55b97fe2016-01-28 05:22:45 -08001099 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001100 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001101 }
1102 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001103
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001104 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001105 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1106 _engineStatisticsPtr->SetLastError(
1107 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1108 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001109 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001110 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001111 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001112 return -1;
1113 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001114
kwiberg55b97fe2016-01-28 05:22:45 -08001115 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001116}
1117
kwiberg55b97fe2016-01-28 05:22:45 -08001118int32_t Channel::StopSend() {
1119 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1120 "Channel::StopSend()");
1121 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001122 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001123 }
1124 channel_state_.SetSending(false);
1125
1126 // Store the sequence number to be able to pick up the same sequence for
1127 // the next StartSend(). This is needed for restarting device, otherwise
1128 // it might cause libSRTP to complain about packets being replayed.
1129 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1130 // CL is landed. See issue
1131 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1132 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1133
1134 // Reset sending SSRC and sequence number and triggers direct transmission
1135 // of RTCP BYE
1136 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1137 _engineStatisticsPtr->SetLastError(
1138 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1139 "StartSend() RTP/RTCP failed to stop sending");
1140 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001141 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001142
1143 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001144}
1145
kwiberg55b97fe2016-01-28 05:22:45 -08001146int32_t Channel::StartReceiving() {
1147 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1148 "Channel::StartReceiving()");
1149 if (channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001150 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001151 }
1152 channel_state_.SetReceiving(true);
1153 _numberOfDiscardedPackets = 0;
1154 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001155}
1156
kwiberg55b97fe2016-01-28 05:22:45 -08001157int32_t Channel::StopReceiving() {
1158 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1159 "Channel::StopReceiving()");
1160 if (!channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001161 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001162 }
1163
1164 channel_state_.SetReceiving(false);
1165 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001166}
1167
kwiberg55b97fe2016-01-28 05:22:45 -08001168int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1169 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1170 "Channel::RegisterVoiceEngineObserver()");
1171 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001172
kwiberg55b97fe2016-01-28 05:22:45 -08001173 if (_voiceEngineObserverPtr) {
1174 _engineStatisticsPtr->SetLastError(
1175 VE_INVALID_OPERATION, kTraceError,
1176 "RegisterVoiceEngineObserver() observer already enabled");
1177 return -1;
1178 }
1179 _voiceEngineObserverPtr = &observer;
1180 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001181}
1182
kwiberg55b97fe2016-01-28 05:22:45 -08001183int32_t Channel::DeRegisterVoiceEngineObserver() {
1184 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1185 "Channel::DeRegisterVoiceEngineObserver()");
1186 rtc::CritScope cs(&_callbackCritSect);
1187
1188 if (!_voiceEngineObserverPtr) {
1189 _engineStatisticsPtr->SetLastError(
1190 VE_INVALID_OPERATION, kTraceWarning,
1191 "DeRegisterVoiceEngineObserver() observer already disabled");
1192 return 0;
1193 }
1194 _voiceEngineObserverPtr = NULL;
1195 return 0;
1196}
1197
1198int32_t Channel::GetSendCodec(CodecInst& codec) {
kwiberg1fd4a4a2015-11-03 11:20:50 -08001199 auto send_codec = audio_coding_->SendCodec();
1200 if (send_codec) {
1201 codec = *send_codec;
1202 return 0;
1203 }
1204 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001205}
1206
kwiberg55b97fe2016-01-28 05:22:45 -08001207int32_t Channel::GetRecCodec(CodecInst& codec) {
1208 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001209}
1210
kwiberg55b97fe2016-01-28 05:22:45 -08001211int32_t Channel::SetSendCodec(const CodecInst& codec) {
1212 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1213 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001214
kwiberg55b97fe2016-01-28 05:22:45 -08001215 if (audio_coding_->RegisterSendCodec(codec) != 0) {
1216 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1217 "SetSendCodec() failed to register codec to ACM");
1218 return -1;
1219 }
1220
1221 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1222 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1223 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1224 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1225 "SetSendCodec() failed to register codec to"
1226 " RTP/RTCP module");
1227 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001228 }
kwiberg55b97fe2016-01-28 05:22:45 -08001229 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001230
kwiberg55b97fe2016-01-28 05:22:45 -08001231 if (_rtpRtcpModule->SetAudioPacketSize(codec.pacsize) != 0) {
1232 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1233 "SetSendCodec() failed to set audio packet size");
1234 return -1;
1235 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001236
kwiberg55b97fe2016-01-28 05:22:45 -08001237 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001238}
1239
Ivo Creusenadf89b72015-04-29 16:03:33 +02001240void Channel::SetBitRate(int bitrate_bps) {
1241 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1242 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
1243 audio_coding_->SetBitRate(bitrate_bps);
1244}
1245
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001246void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue@webrtc.org74aaf292014-07-16 21:28:26 +00001247 network_predictor_->UpdatePacketLossRate(fraction_lost);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001248 uint8_t average_fraction_loss = network_predictor_->GetLossRate();
1249
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001250 // Normalizes rate to 0 - 100.
kwiberg55b97fe2016-01-28 05:22:45 -08001251 if (audio_coding_->SetPacketLossRate(100 * average_fraction_loss / 255) !=
1252 0) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001253 assert(false); // This should not happen.
1254 }
1255}
1256
kwiberg55b97fe2016-01-28 05:22:45 -08001257int32_t Channel::SetVADStatus(bool enableVAD,
1258 ACMVADMode mode,
1259 bool disableDTX) {
1260 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1261 "Channel::SetVADStatus(mode=%d)", mode);
1262 assert(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1263 // To disable VAD, DTX must be disabled too
1264 disableDTX = ((enableVAD == false) ? true : disableDTX);
1265 if (audio_coding_->SetVAD(!disableDTX, enableVAD, mode) != 0) {
1266 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1267 kTraceError,
1268 "SetVADStatus() failed to set VAD");
1269 return -1;
1270 }
1271 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001272}
1273
kwiberg55b97fe2016-01-28 05:22:45 -08001274int32_t Channel::GetVADStatus(bool& enabledVAD,
1275 ACMVADMode& mode,
1276 bool& disabledDTX) {
1277 if (audio_coding_->VAD(&disabledDTX, &enabledVAD, &mode) != 0) {
1278 _engineStatisticsPtr->SetLastError(
1279 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1280 "GetVADStatus() failed to get VAD status");
1281 return -1;
1282 }
1283 disabledDTX = !disabledDTX;
1284 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001285}
1286
kwiberg55b97fe2016-01-28 05:22:45 -08001287int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1288 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1289 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001290
kwiberg55b97fe2016-01-28 05:22:45 -08001291 if (channel_state_.Get().playing) {
1292 _engineStatisticsPtr->SetLastError(
1293 VE_ALREADY_PLAYING, kTraceError,
1294 "SetRecPayloadType() unable to set PT while playing");
1295 return -1;
1296 }
1297 if (channel_state_.Get().receiving) {
1298 _engineStatisticsPtr->SetLastError(
1299 VE_ALREADY_LISTENING, kTraceError,
1300 "SetRecPayloadType() unable to set PT while listening");
1301 return -1;
1302 }
1303
1304 if (codec.pltype == -1) {
1305 // De-register the selected codec (RTP/RTCP module and ACM)
1306
1307 int8_t pltype(-1);
1308 CodecInst rxCodec = codec;
1309
1310 // Get payload type for the given codec
1311 rtp_payload_registry_->ReceivePayloadType(
1312 rxCodec.plname, rxCodec.plfreq, rxCodec.channels,
1313 (rxCodec.rate < 0) ? 0 : rxCodec.rate, &pltype);
1314 rxCodec.pltype = pltype;
1315
1316 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1317 _engineStatisticsPtr->SetLastError(
1318 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1319 "SetRecPayloadType() RTP/RTCP-module deregistration "
1320 "failed");
1321 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001322 }
kwiberg55b97fe2016-01-28 05:22:45 -08001323 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1324 _engineStatisticsPtr->SetLastError(
1325 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1326 "SetRecPayloadType() ACM deregistration failed - 1");
1327 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001328 }
kwiberg55b97fe2016-01-28 05:22:45 -08001329 return 0;
1330 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001331
kwiberg55b97fe2016-01-28 05:22:45 -08001332 if (rtp_receiver_->RegisterReceivePayload(
1333 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1334 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1335 // First attempt to register failed => de-register and try again
1336 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001337 if (rtp_receiver_->RegisterReceivePayload(
kwiberg55b97fe2016-01-28 05:22:45 -08001338 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1339 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1340 _engineStatisticsPtr->SetLastError(
1341 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1342 "SetRecPayloadType() RTP/RTCP-module registration failed");
1343 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001344 }
kwiberg55b97fe2016-01-28 05:22:45 -08001345 }
1346 if (audio_coding_->RegisterReceiveCodec(codec) != 0) {
1347 audio_coding_->UnregisterReceiveCodec(codec.pltype);
1348 if (audio_coding_->RegisterReceiveCodec(codec) != 0) {
1349 _engineStatisticsPtr->SetLastError(
1350 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1351 "SetRecPayloadType() ACM registration failed - 1");
1352 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001353 }
kwiberg55b97fe2016-01-28 05:22:45 -08001354 }
1355 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001356}
1357
kwiberg55b97fe2016-01-28 05:22:45 -08001358int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1359 int8_t payloadType(-1);
1360 if (rtp_payload_registry_->ReceivePayloadType(
1361 codec.plname, codec.plfreq, codec.channels,
1362 (codec.rate < 0) ? 0 : codec.rate, &payloadType) != 0) {
1363 _engineStatisticsPtr->SetLastError(
1364 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1365 "GetRecPayloadType() failed to retrieve RX payload type");
1366 return -1;
1367 }
1368 codec.pltype = payloadType;
1369 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001370}
1371
kwiberg55b97fe2016-01-28 05:22:45 -08001372int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1373 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1374 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001375
kwiberg55b97fe2016-01-28 05:22:45 -08001376 CodecInst codec;
1377 int32_t samplingFreqHz(-1);
1378 const size_t kMono = 1;
1379 if (frequency == kFreq32000Hz)
1380 samplingFreqHz = 32000;
1381 else if (frequency == kFreq16000Hz)
1382 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001383
kwiberg55b97fe2016-01-28 05:22:45 -08001384 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1385 _engineStatisticsPtr->SetLastError(
1386 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1387 "SetSendCNPayloadType() failed to retrieve default CN codec "
1388 "settings");
1389 return -1;
1390 }
1391
1392 // Modify the payload type (must be set to dynamic range)
1393 codec.pltype = type;
1394
1395 if (audio_coding_->RegisterSendCodec(codec) != 0) {
1396 _engineStatisticsPtr->SetLastError(
1397 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1398 "SetSendCNPayloadType() failed to register CN to ACM");
1399 return -1;
1400 }
1401
1402 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1403 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1404 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1405 _engineStatisticsPtr->SetLastError(
1406 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1407 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1408 "module");
1409 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001410 }
kwiberg55b97fe2016-01-28 05:22:45 -08001411 }
1412 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001413}
1414
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001415int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001416 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001417 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001418
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001419 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001420 _engineStatisticsPtr->SetLastError(
1421 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001422 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001423 return -1;
1424 }
1425 return 0;
1426}
1427
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001428int Channel::SetOpusDtx(bool enable_dtx) {
1429 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1430 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001431 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001432 : audio_coding_->DisableOpusDtx();
1433 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001434 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1435 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001436 return -1;
1437 }
1438 return 0;
1439}
1440
kwiberg55b97fe2016-01-28 05:22:45 -08001441int32_t Channel::RegisterExternalTransport(Transport& transport) {
1442 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001443 "Channel::RegisterExternalTransport()");
1444
kwiberg55b97fe2016-01-28 05:22:45 -08001445 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001446
kwiberg55b97fe2016-01-28 05:22:45 -08001447 if (_externalTransport) {
1448 _engineStatisticsPtr->SetLastError(
1449 VE_INVALID_OPERATION, kTraceError,
1450 "RegisterExternalTransport() external transport already enabled");
1451 return -1;
1452 }
1453 _externalTransport = true;
1454 _transportPtr = &transport;
1455 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001456}
1457
kwiberg55b97fe2016-01-28 05:22:45 -08001458int32_t Channel::DeRegisterExternalTransport() {
1459 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1460 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001461
kwiberg55b97fe2016-01-28 05:22:45 -08001462 rtc::CritScope cs(&_callbackCritSect);
xians@webrtc.org83661f52011-11-25 10:58:15 +00001463
kwiberg55b97fe2016-01-28 05:22:45 -08001464 if (!_transportPtr) {
1465 _engineStatisticsPtr->SetLastError(
1466 VE_INVALID_OPERATION, kTraceWarning,
1467 "DeRegisterExternalTransport() external transport already "
1468 "disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00001469 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001470 }
1471 _externalTransport = false;
1472 _transportPtr = NULL;
1473 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1474 "DeRegisterExternalTransport() all transport is disabled");
1475 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001476}
1477
kwiberg55b97fe2016-01-28 05:22:45 -08001478int32_t Channel::ReceivedRTPPacket(const int8_t* data,
1479 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001480 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001481 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001482 "Channel::ReceivedRTPPacket()");
1483
1484 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001485 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001486
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001487 const uint8_t* received_packet = reinterpret_cast<const uint8_t*>(data);
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001488 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001489 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1490 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1491 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001492 return -1;
1493 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001494 header.payload_type_frequency =
1495 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001496 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001497 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001498 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001499 rtp_receive_statistics_->IncomingPacket(
1500 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001501 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001502
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001503 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001504}
1505
1506bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001507 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001508 const RTPHeader& header,
1509 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001510 if (rtp_payload_registry_->IsRtx(header)) {
1511 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001512 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001513 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001514 assert(packet_length >= header.headerLength);
1515 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001516 PayloadUnion payload_specific;
1517 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001518 &payload_specific)) {
1519 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001520 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001521 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1522 payload_specific, in_order);
1523}
1524
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001525bool Channel::HandleRtxPacket(const uint8_t* packet,
1526 size_t packet_length,
1527 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001528 if (!rtp_payload_registry_->IsRtx(header))
1529 return false;
1530
1531 // Remove the RTX header and parse the original RTP header.
1532 if (packet_length < header.headerLength)
1533 return false;
1534 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1535 return false;
1536 if (restored_packet_in_use_) {
1537 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1538 "Multiple RTX headers detected, dropping packet");
1539 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001540 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001541 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001542 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1543 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001544 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1545 "Incoming RTX packet: invalid RTP header");
1546 return false;
1547 }
1548 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001549 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001550 restored_packet_in_use_ = false;
1551 return ret;
1552}
1553
1554bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1555 StreamStatistician* statistician =
1556 rtp_receive_statistics_->GetStatistician(header.ssrc);
1557 if (!statistician)
1558 return false;
1559 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001560}
1561
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001562bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1563 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001564 // Retransmissions are handled separately if RTX is enabled.
1565 if (rtp_payload_registry_->RtxEnabled())
1566 return false;
1567 StreamStatistician* statistician =
1568 rtp_receive_statistics_->GetStatistician(header.ssrc);
1569 if (!statistician)
1570 return false;
1571 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001572 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001573 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001574 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001575}
1576
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001577int32_t Channel::ReceivedRTCPPacket(const int8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001578 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001579 "Channel::ReceivedRTCPPacket()");
1580 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001581 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001582
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001583 // Deliver RTCP packet to RTP/RTCP module for parsing
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001584 if (_rtpRtcpModule->IncomingRtcpPacket((const uint8_t*)data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001585 _engineStatisticsPtr->SetLastError(
1586 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1587 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1588 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001589
Minyue2013aec2015-05-13 14:14:42 +02001590 int64_t rtt = GetRTT(true);
1591 if (rtt == 0) {
1592 // Waiting for valid RTT.
1593 return 0;
1594 }
1595 uint32_t ntp_secs = 0;
1596 uint32_t ntp_frac = 0;
1597 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001598 if (0 !=
1599 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1600 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001601 // Waiting for RTCP.
1602 return 0;
1603 }
1604
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001605 {
tommi31fc21f2016-01-21 10:37:37 -08001606 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001607 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001608 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001609 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001610}
1611
niklase@google.com470e71d2011-07-07 08:21:25 +00001612int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001613 bool loop,
1614 FileFormats format,
1615 int startPosition,
1616 float volumeScaling,
1617 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001618 const CodecInst* codecInst) {
1619 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1620 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1621 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1622 "stopPosition=%d)",
1623 fileName, loop, format, volumeScaling, startPosition,
1624 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001625
kwiberg55b97fe2016-01-28 05:22:45 -08001626 if (channel_state_.Get().output_file_playing) {
1627 _engineStatisticsPtr->SetLastError(
1628 VE_ALREADY_PLAYING, kTraceError,
1629 "StartPlayingFileLocally() is already playing");
1630 return -1;
1631 }
1632
1633 {
1634 rtc::CritScope cs(&_fileCritSect);
1635
1636 if (_outputFilePlayerPtr) {
1637 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1638 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1639 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001640 }
1641
kwiberg55b97fe2016-01-28 05:22:45 -08001642 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1643 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001644
kwiberg55b97fe2016-01-28 05:22:45 -08001645 if (_outputFilePlayerPtr == NULL) {
1646 _engineStatisticsPtr->SetLastError(
1647 VE_INVALID_ARGUMENT, kTraceError,
1648 "StartPlayingFileLocally() filePlayer format is not correct");
1649 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001650 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001651
kwiberg55b97fe2016-01-28 05:22:45 -08001652 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001653
kwiberg55b97fe2016-01-28 05:22:45 -08001654 if (_outputFilePlayerPtr->StartPlayingFile(
1655 fileName, loop, startPosition, volumeScaling, notificationTime,
1656 stopPosition, (const CodecInst*)codecInst) != 0) {
1657 _engineStatisticsPtr->SetLastError(
1658 VE_BAD_FILE, kTraceError,
1659 "StartPlayingFile() failed to start file playout");
1660 _outputFilePlayerPtr->StopPlayingFile();
1661 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1662 _outputFilePlayerPtr = NULL;
1663 return -1;
1664 }
1665 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1666 channel_state_.SetOutputFilePlaying(true);
1667 }
1668
1669 if (RegisterFilePlayingToMixer() != 0)
1670 return -1;
1671
1672 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001673}
1674
1675int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001676 FileFormats format,
1677 int startPosition,
1678 float volumeScaling,
1679 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001680 const CodecInst* codecInst) {
1681 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1682 "Channel::StartPlayingFileLocally(format=%d,"
1683 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1684 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001685
kwiberg55b97fe2016-01-28 05:22:45 -08001686 if (stream == NULL) {
1687 _engineStatisticsPtr->SetLastError(
1688 VE_BAD_FILE, kTraceError,
1689 "StartPlayingFileLocally() NULL as input stream");
1690 return -1;
1691 }
1692
1693 if (channel_state_.Get().output_file_playing) {
1694 _engineStatisticsPtr->SetLastError(
1695 VE_ALREADY_PLAYING, kTraceError,
1696 "StartPlayingFileLocally() is already playing");
1697 return -1;
1698 }
1699
1700 {
1701 rtc::CritScope cs(&_fileCritSect);
1702
1703 // Destroy the old instance
1704 if (_outputFilePlayerPtr) {
1705 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1706 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1707 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001708 }
1709
kwiberg55b97fe2016-01-28 05:22:45 -08001710 // Create the instance
1711 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1712 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001713
kwiberg55b97fe2016-01-28 05:22:45 -08001714 if (_outputFilePlayerPtr == NULL) {
1715 _engineStatisticsPtr->SetLastError(
1716 VE_INVALID_ARGUMENT, kTraceError,
1717 "StartPlayingFileLocally() filePlayer format isnot correct");
1718 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001719 }
1720
kwiberg55b97fe2016-01-28 05:22:45 -08001721 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001722
kwiberg55b97fe2016-01-28 05:22:45 -08001723 if (_outputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1724 volumeScaling, notificationTime,
1725 stopPosition, codecInst) != 0) {
1726 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1727 "StartPlayingFile() failed to "
1728 "start file playout");
1729 _outputFilePlayerPtr->StopPlayingFile();
1730 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1731 _outputFilePlayerPtr = NULL;
1732 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001733 }
kwiberg55b97fe2016-01-28 05:22:45 -08001734 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1735 channel_state_.SetOutputFilePlaying(true);
1736 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001737
kwiberg55b97fe2016-01-28 05:22:45 -08001738 if (RegisterFilePlayingToMixer() != 0)
1739 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001740
kwiberg55b97fe2016-01-28 05:22:45 -08001741 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001742}
1743
kwiberg55b97fe2016-01-28 05:22:45 -08001744int Channel::StopPlayingFileLocally() {
1745 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1746 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001747
kwiberg55b97fe2016-01-28 05:22:45 -08001748 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001749 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001750 }
1751
1752 {
1753 rtc::CritScope cs(&_fileCritSect);
1754
1755 if (_outputFilePlayerPtr->StopPlayingFile() != 0) {
1756 _engineStatisticsPtr->SetLastError(
1757 VE_STOP_RECORDING_FAILED, kTraceError,
1758 "StopPlayingFile() could not stop playing");
1759 return -1;
1760 }
1761 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1762 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1763 _outputFilePlayerPtr = NULL;
1764 channel_state_.SetOutputFilePlaying(false);
1765 }
1766 // _fileCritSect cannot be taken while calling
1767 // SetAnonymousMixibilityStatus. Refer to comments in
1768 // StartPlayingFileLocally(const char* ...) for more details.
1769 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1770 _engineStatisticsPtr->SetLastError(
1771 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1772 "StopPlayingFile() failed to stop participant from playing as"
1773 "file in the mixer");
1774 return -1;
1775 }
1776
1777 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001778}
1779
kwiberg55b97fe2016-01-28 05:22:45 -08001780int Channel::IsPlayingFileLocally() const {
1781 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001782}
1783
kwiberg55b97fe2016-01-28 05:22:45 -08001784int Channel::RegisterFilePlayingToMixer() {
1785 // Return success for not registering for file playing to mixer if:
1786 // 1. playing file before playout is started on that channel.
1787 // 2. starting playout without file playing on that channel.
1788 if (!channel_state_.Get().playing ||
1789 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001790 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001791 }
1792
1793 // |_fileCritSect| cannot be taken while calling
1794 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1795 // frames can be pulled by the mixer. Since the frames are generated from
1796 // the file, _fileCritSect will be taken. This would result in a deadlock.
1797 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1798 channel_state_.SetOutputFilePlaying(false);
1799 rtc::CritScope cs(&_fileCritSect);
1800 _engineStatisticsPtr->SetLastError(
1801 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1802 "StartPlayingFile() failed to add participant as file to mixer");
1803 _outputFilePlayerPtr->StopPlayingFile();
1804 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1805 _outputFilePlayerPtr = NULL;
1806 return -1;
1807 }
1808
1809 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001810}
1811
niklase@google.com470e71d2011-07-07 08:21:25 +00001812int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001813 bool loop,
1814 FileFormats format,
1815 int startPosition,
1816 float volumeScaling,
1817 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001818 const CodecInst* codecInst) {
1819 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1820 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1821 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1822 "stopPosition=%d)",
1823 fileName, loop, format, volumeScaling, startPosition,
1824 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001825
kwiberg55b97fe2016-01-28 05:22:45 -08001826 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001827
kwiberg55b97fe2016-01-28 05:22:45 -08001828 if (channel_state_.Get().input_file_playing) {
1829 _engineStatisticsPtr->SetLastError(
1830 VE_ALREADY_PLAYING, kTraceWarning,
1831 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001832 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001833 }
1834
1835 // Destroy the old instance
1836 if (_inputFilePlayerPtr) {
1837 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1838 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1839 _inputFilePlayerPtr = NULL;
1840 }
1841
1842 // Create the instance
1843 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1844 (const FileFormats)format);
1845
1846 if (_inputFilePlayerPtr == NULL) {
1847 _engineStatisticsPtr->SetLastError(
1848 VE_INVALID_ARGUMENT, kTraceError,
1849 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1850 return -1;
1851 }
1852
1853 const uint32_t notificationTime(0);
1854
1855 if (_inputFilePlayerPtr->StartPlayingFile(
1856 fileName, loop, startPosition, volumeScaling, notificationTime,
1857 stopPosition, (const CodecInst*)codecInst) != 0) {
1858 _engineStatisticsPtr->SetLastError(
1859 VE_BAD_FILE, kTraceError,
1860 "StartPlayingFile() failed to start file playout");
1861 _inputFilePlayerPtr->StopPlayingFile();
1862 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1863 _inputFilePlayerPtr = NULL;
1864 return -1;
1865 }
1866 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1867 channel_state_.SetInputFilePlaying(true);
1868
1869 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001870}
1871
1872int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001873 FileFormats format,
1874 int startPosition,
1875 float volumeScaling,
1876 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001877 const CodecInst* codecInst) {
1878 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1879 "Channel::StartPlayingFileAsMicrophone(format=%d, "
1880 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1881 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001882
kwiberg55b97fe2016-01-28 05:22:45 -08001883 if (stream == NULL) {
1884 _engineStatisticsPtr->SetLastError(
1885 VE_BAD_FILE, kTraceError,
1886 "StartPlayingFileAsMicrophone NULL as input stream");
1887 return -1;
1888 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001889
kwiberg55b97fe2016-01-28 05:22:45 -08001890 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001891
kwiberg55b97fe2016-01-28 05:22:45 -08001892 if (channel_state_.Get().input_file_playing) {
1893 _engineStatisticsPtr->SetLastError(
1894 VE_ALREADY_PLAYING, kTraceWarning,
1895 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001896 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001897 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001898
kwiberg55b97fe2016-01-28 05:22:45 -08001899 // Destroy the old instance
1900 if (_inputFilePlayerPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001901 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1902 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1903 _inputFilePlayerPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001904 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001905
kwiberg55b97fe2016-01-28 05:22:45 -08001906 // Create the instance
1907 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1908 (const FileFormats)format);
1909
1910 if (_inputFilePlayerPtr == NULL) {
1911 _engineStatisticsPtr->SetLastError(
1912 VE_INVALID_ARGUMENT, kTraceError,
1913 "StartPlayingInputFile() filePlayer format isnot correct");
1914 return -1;
1915 }
1916
1917 const uint32_t notificationTime(0);
1918
1919 if (_inputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1920 volumeScaling, notificationTime,
1921 stopPosition, codecInst) != 0) {
1922 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1923 "StartPlayingFile() failed to start "
1924 "file playout");
1925 _inputFilePlayerPtr->StopPlayingFile();
1926 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1927 _inputFilePlayerPtr = NULL;
1928 return -1;
1929 }
1930
1931 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1932 channel_state_.SetInputFilePlaying(true);
1933
1934 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001935}
1936
kwiberg55b97fe2016-01-28 05:22:45 -08001937int Channel::StopPlayingFileAsMicrophone() {
1938 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1939 "Channel::StopPlayingFileAsMicrophone()");
1940
1941 rtc::CritScope cs(&_fileCritSect);
1942
1943 if (!channel_state_.Get().input_file_playing) {
1944 return 0;
1945 }
1946
1947 if (_inputFilePlayerPtr->StopPlayingFile() != 0) {
1948 _engineStatisticsPtr->SetLastError(
1949 VE_STOP_RECORDING_FAILED, kTraceError,
1950 "StopPlayingFile() could not stop playing");
1951 return -1;
1952 }
1953 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1954 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1955 _inputFilePlayerPtr = NULL;
1956 channel_state_.SetInputFilePlaying(false);
1957
1958 return 0;
1959}
1960
1961int Channel::IsPlayingFileAsMicrophone() const {
1962 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001963}
1964
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00001965int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08001966 const CodecInst* codecInst) {
1967 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1968 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00001969
kwiberg55b97fe2016-01-28 05:22:45 -08001970 if (_outputFileRecording) {
1971 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
1972 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00001973 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001974 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001975
kwiberg55b97fe2016-01-28 05:22:45 -08001976 FileFormats format;
1977 const uint32_t notificationTime(0); // Not supported in VoE
1978 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00001979
kwiberg55b97fe2016-01-28 05:22:45 -08001980 if ((codecInst != NULL) &&
1981 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
1982 _engineStatisticsPtr->SetLastError(
1983 VE_BAD_ARGUMENT, kTraceError,
1984 "StartRecordingPlayout() invalid compression");
1985 return (-1);
1986 }
1987 if (codecInst == NULL) {
1988 format = kFileFormatPcm16kHzFile;
1989 codecInst = &dummyCodec;
1990 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
1991 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
1992 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
1993 format = kFileFormatWavFile;
1994 } else {
1995 format = kFileFormatCompressedFile;
1996 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001997
kwiberg55b97fe2016-01-28 05:22:45 -08001998 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001999
kwiberg55b97fe2016-01-28 05:22:45 -08002000 // Destroy the old instance
2001 if (_outputFileRecorderPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002002 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2003 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2004 _outputFileRecorderPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08002005 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002006
kwiberg55b97fe2016-01-28 05:22:45 -08002007 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2008 _outputFileRecorderId, (const FileFormats)format);
2009 if (_outputFileRecorderPtr == NULL) {
2010 _engineStatisticsPtr->SetLastError(
2011 VE_INVALID_ARGUMENT, kTraceError,
2012 "StartRecordingPlayout() fileRecorder format isnot correct");
2013 return -1;
2014 }
2015
2016 if (_outputFileRecorderPtr->StartRecordingAudioFile(
2017 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2018 _engineStatisticsPtr->SetLastError(
2019 VE_BAD_FILE, kTraceError,
2020 "StartRecordingAudioFile() failed to start file recording");
2021 _outputFileRecorderPtr->StopRecording();
2022 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2023 _outputFileRecorderPtr = NULL;
2024 return -1;
2025 }
2026 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2027 _outputFileRecording = true;
2028
2029 return 0;
2030}
2031
2032int Channel::StartRecordingPlayout(OutStream* stream,
2033 const CodecInst* codecInst) {
2034 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2035 "Channel::StartRecordingPlayout()");
2036
2037 if (_outputFileRecording) {
2038 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2039 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002040 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002041 }
2042
2043 FileFormats format;
2044 const uint32_t notificationTime(0); // Not supported in VoE
2045 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2046
2047 if (codecInst != NULL && codecInst->channels != 1) {
2048 _engineStatisticsPtr->SetLastError(
2049 VE_BAD_ARGUMENT, kTraceError,
2050 "StartRecordingPlayout() invalid compression");
2051 return (-1);
2052 }
2053 if (codecInst == NULL) {
2054 format = kFileFormatPcm16kHzFile;
2055 codecInst = &dummyCodec;
2056 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2057 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2058 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2059 format = kFileFormatWavFile;
2060 } else {
2061 format = kFileFormatCompressedFile;
2062 }
2063
2064 rtc::CritScope cs(&_fileCritSect);
2065
2066 // Destroy the old instance
2067 if (_outputFileRecorderPtr) {
2068 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2069 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2070 _outputFileRecorderPtr = NULL;
2071 }
2072
2073 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2074 _outputFileRecorderId, (const FileFormats)format);
2075 if (_outputFileRecorderPtr == NULL) {
2076 _engineStatisticsPtr->SetLastError(
2077 VE_INVALID_ARGUMENT, kTraceError,
2078 "StartRecordingPlayout() fileRecorder format isnot correct");
2079 return -1;
2080 }
2081
2082 if (_outputFileRecorderPtr->StartRecordingAudioFile(*stream, *codecInst,
2083 notificationTime) != 0) {
2084 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2085 "StartRecordingPlayout() failed to "
2086 "start file recording");
2087 _outputFileRecorderPtr->StopRecording();
2088 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2089 _outputFileRecorderPtr = NULL;
2090 return -1;
2091 }
2092
2093 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2094 _outputFileRecording = true;
2095
2096 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002097}
2098
kwiberg55b97fe2016-01-28 05:22:45 -08002099int Channel::StopRecordingPlayout() {
2100 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2101 "Channel::StopRecordingPlayout()");
2102
2103 if (!_outputFileRecording) {
2104 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2105 "StopRecordingPlayout() isnot recording");
2106 return -1;
2107 }
2108
2109 rtc::CritScope cs(&_fileCritSect);
2110
2111 if (_outputFileRecorderPtr->StopRecording() != 0) {
2112 _engineStatisticsPtr->SetLastError(
2113 VE_STOP_RECORDING_FAILED, kTraceError,
2114 "StopRecording() could not stop recording");
2115 return (-1);
2116 }
2117 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2118 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2119 _outputFileRecorderPtr = NULL;
2120 _outputFileRecording = false;
2121
2122 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002123}
2124
kwiberg55b97fe2016-01-28 05:22:45 -08002125void Channel::SetMixWithMicStatus(bool mix) {
2126 rtc::CritScope cs(&_fileCritSect);
2127 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002128}
2129
kwiberg55b97fe2016-01-28 05:22:45 -08002130int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2131 int8_t currentLevel = _outputAudioLevel.Level();
2132 level = static_cast<int32_t>(currentLevel);
2133 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002134}
2135
kwiberg55b97fe2016-01-28 05:22:45 -08002136int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2137 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2138 level = static_cast<int32_t>(currentLevel);
2139 return 0;
2140}
2141
solenberg1c2af8e2016-03-24 10:36:00 -07002142int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002143 rtc::CritScope cs(&volume_settings_critsect_);
2144 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002145 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002146 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002147 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002148}
2149
solenberg1c2af8e2016-03-24 10:36:00 -07002150bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002151 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002152 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002153}
2154
kwiberg55b97fe2016-01-28 05:22:45 -08002155int Channel::SetOutputVolumePan(float left, float right) {
2156 rtc::CritScope cs(&volume_settings_critsect_);
2157 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002158 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002159 _panLeft = left;
2160 _panRight = right;
2161 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002162}
2163
kwiberg55b97fe2016-01-28 05:22:45 -08002164int Channel::GetOutputVolumePan(float& left, float& right) const {
2165 rtc::CritScope cs(&volume_settings_critsect_);
2166 left = _panLeft;
2167 right = _panRight;
2168 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002169}
2170
kwiberg55b97fe2016-01-28 05:22:45 -08002171int Channel::SetChannelOutputVolumeScaling(float scaling) {
2172 rtc::CritScope cs(&volume_settings_critsect_);
2173 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002174 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002175 _outputGain = scaling;
2176 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002177}
2178
kwiberg55b97fe2016-01-28 05:22:45 -08002179int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2180 rtc::CritScope cs(&volume_settings_critsect_);
2181 scaling = _outputGain;
2182 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002183}
2184
solenberg8842c3e2016-03-11 03:06:41 -08002185int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002186 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002187 "Channel::SendTelephoneEventOutband(...)");
2188 RTC_DCHECK_LE(0, event);
2189 RTC_DCHECK_GE(255, event);
2190 RTC_DCHECK_LE(0, duration_ms);
2191 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002192 if (!Sending()) {
2193 return -1;
2194 }
solenberg8842c3e2016-03-11 03:06:41 -08002195 if (_rtpRtcpModule->SendTelephoneEventOutband(
2196 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002197 _engineStatisticsPtr->SetLastError(
2198 VE_SEND_DTMF_FAILED, kTraceWarning,
2199 "SendTelephoneEventOutband() failed to send event");
2200 return -1;
2201 }
2202 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002203}
2204
solenberg31642aa2016-03-14 08:00:37 -07002205int Channel::SetSendTelephoneEventPayloadType(int payload_type) {
kwiberg55b97fe2016-01-28 05:22:45 -08002206 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002207 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002208 RTC_DCHECK_LE(0, payload_type);
2209 RTC_DCHECK_GE(127, payload_type);
2210 CodecInst codec = {0};
kwiberg55b97fe2016-01-28 05:22:45 -08002211 codec.plfreq = 8000;
solenberg31642aa2016-03-14 08:00:37 -07002212 codec.pltype = payload_type;
kwiberg55b97fe2016-01-28 05:22:45 -08002213 memcpy(codec.plname, "telephone-event", 16);
2214 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2215 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2216 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2217 _engineStatisticsPtr->SetLastError(
2218 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2219 "SetSendTelephoneEventPayloadType() failed to register send"
2220 "payload type");
2221 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002222 }
kwiberg55b97fe2016-01-28 05:22:45 -08002223 }
kwiberg55b97fe2016-01-28 05:22:45 -08002224 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002225}
2226
kwiberg55b97fe2016-01-28 05:22:45 -08002227int Channel::UpdateRxVadDetection(AudioFrame& audioFrame) {
2228 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2229 "Channel::UpdateRxVadDetection()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002230
kwiberg55b97fe2016-01-28 05:22:45 -08002231 int vadDecision = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002232
kwiberg55b97fe2016-01-28 05:22:45 -08002233 vadDecision = (audioFrame.vad_activity_ == AudioFrame::kVadActive) ? 1 : 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002234
kwiberg55b97fe2016-01-28 05:22:45 -08002235 if ((vadDecision != _oldVadDecision) && _rxVadObserverPtr) {
2236 OnRxVadDetected(vadDecision);
2237 _oldVadDecision = vadDecision;
2238 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002239
kwiberg55b97fe2016-01-28 05:22:45 -08002240 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2241 "Channel::UpdateRxVadDetection() => vadDecision=%d",
2242 vadDecision);
2243 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002244}
2245
kwiberg55b97fe2016-01-28 05:22:45 -08002246int Channel::RegisterRxVadObserver(VoERxVadCallback& observer) {
2247 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2248 "Channel::RegisterRxVadObserver()");
2249 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002250
kwiberg55b97fe2016-01-28 05:22:45 -08002251 if (_rxVadObserverPtr) {
2252 _engineStatisticsPtr->SetLastError(
2253 VE_INVALID_OPERATION, kTraceError,
2254 "RegisterRxVadObserver() observer already enabled");
2255 return -1;
2256 }
2257 _rxVadObserverPtr = &observer;
2258 _RxVadDetection = true;
2259 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002260}
2261
kwiberg55b97fe2016-01-28 05:22:45 -08002262int Channel::DeRegisterRxVadObserver() {
2263 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2264 "Channel::DeRegisterRxVadObserver()");
2265 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002266
kwiberg55b97fe2016-01-28 05:22:45 -08002267 if (!_rxVadObserverPtr) {
2268 _engineStatisticsPtr->SetLastError(
2269 VE_INVALID_OPERATION, kTraceWarning,
2270 "DeRegisterRxVadObserver() observer already disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00002271 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002272 }
2273 _rxVadObserverPtr = NULL;
2274 _RxVadDetection = false;
2275 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002276}
2277
kwiberg55b97fe2016-01-28 05:22:45 -08002278int Channel::VoiceActivityIndicator(int& activity) {
2279 activity = _sendFrameType;
2280 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002281}
2282
2283#ifdef WEBRTC_VOICE_ENGINE_AGC
2284
kwiberg55b97fe2016-01-28 05:22:45 -08002285int Channel::SetRxAgcStatus(bool enable, AgcModes mode) {
2286 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2287 "Channel::SetRxAgcStatus(enable=%d, mode=%d)", (int)enable,
2288 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002289
kwiberg55b97fe2016-01-28 05:22:45 -08002290 GainControl::Mode agcMode = kDefaultRxAgcMode;
2291 switch (mode) {
2292 case kAgcDefault:
2293 break;
2294 case kAgcUnchanged:
2295 agcMode = rx_audioproc_->gain_control()->mode();
2296 break;
2297 case kAgcFixedDigital:
2298 agcMode = GainControl::kFixedDigital;
2299 break;
2300 case kAgcAdaptiveDigital:
2301 agcMode = GainControl::kAdaptiveDigital;
2302 break;
2303 default:
2304 _engineStatisticsPtr->SetLastError(VE_INVALID_ARGUMENT, kTraceError,
2305 "SetRxAgcStatus() invalid Agc mode");
2306 return -1;
2307 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002308
kwiberg55b97fe2016-01-28 05:22:45 -08002309 if (rx_audioproc_->gain_control()->set_mode(agcMode) != 0) {
2310 _engineStatisticsPtr->SetLastError(
2311 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc mode");
2312 return -1;
2313 }
2314 if (rx_audioproc_->gain_control()->Enable(enable) != 0) {
2315 _engineStatisticsPtr->SetLastError(
2316 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc state");
2317 return -1;
2318 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002319
kwiberg55b97fe2016-01-28 05:22:45 -08002320 _rxAgcIsEnabled = enable;
2321 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002322
kwiberg55b97fe2016-01-28 05:22:45 -08002323 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002324}
2325
kwiberg55b97fe2016-01-28 05:22:45 -08002326int Channel::GetRxAgcStatus(bool& enabled, AgcModes& mode) {
2327 bool enable = rx_audioproc_->gain_control()->is_enabled();
2328 GainControl::Mode agcMode = rx_audioproc_->gain_control()->mode();
niklase@google.com470e71d2011-07-07 08:21:25 +00002329
kwiberg55b97fe2016-01-28 05:22:45 -08002330 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002331
kwiberg55b97fe2016-01-28 05:22:45 -08002332 switch (agcMode) {
2333 case GainControl::kFixedDigital:
2334 mode = kAgcFixedDigital;
2335 break;
2336 case GainControl::kAdaptiveDigital:
2337 mode = kAgcAdaptiveDigital;
2338 break;
2339 default:
2340 _engineStatisticsPtr->SetLastError(VE_APM_ERROR, kTraceError,
2341 "GetRxAgcStatus() invalid Agc mode");
2342 return -1;
2343 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002344
kwiberg55b97fe2016-01-28 05:22:45 -08002345 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002346}
2347
kwiberg55b97fe2016-01-28 05:22:45 -08002348int Channel::SetRxAgcConfig(AgcConfig config) {
2349 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2350 "Channel::SetRxAgcConfig()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002351
kwiberg55b97fe2016-01-28 05:22:45 -08002352 if (rx_audioproc_->gain_control()->set_target_level_dbfs(
2353 config.targetLeveldBOv) != 0) {
2354 _engineStatisticsPtr->SetLastError(
2355 VE_APM_ERROR, kTraceError,
2356 "SetRxAgcConfig() failed to set target peak |level|"
2357 "(or envelope) of the Agc");
2358 return -1;
2359 }
2360 if (rx_audioproc_->gain_control()->set_compression_gain_db(
2361 config.digitalCompressionGaindB) != 0) {
2362 _engineStatisticsPtr->SetLastError(
2363 VE_APM_ERROR, kTraceError,
2364 "SetRxAgcConfig() failed to set the range in |gain| the"
2365 " digital compression stage may apply");
2366 return -1;
2367 }
2368 if (rx_audioproc_->gain_control()->enable_limiter(config.limiterEnable) !=
2369 0) {
2370 _engineStatisticsPtr->SetLastError(
2371 VE_APM_ERROR, kTraceError,
2372 "SetRxAgcConfig() failed to set hard limiter to the signal");
2373 return -1;
2374 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002375
kwiberg55b97fe2016-01-28 05:22:45 -08002376 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002377}
2378
kwiberg55b97fe2016-01-28 05:22:45 -08002379int Channel::GetRxAgcConfig(AgcConfig& config) {
2380 config.targetLeveldBOv = rx_audioproc_->gain_control()->target_level_dbfs();
2381 config.digitalCompressionGaindB =
2382 rx_audioproc_->gain_control()->compression_gain_db();
2383 config.limiterEnable = rx_audioproc_->gain_control()->is_limiter_enabled();
niklase@google.com470e71d2011-07-07 08:21:25 +00002384
kwiberg55b97fe2016-01-28 05:22:45 -08002385 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002386}
2387
kwiberg55b97fe2016-01-28 05:22:45 -08002388#endif // #ifdef WEBRTC_VOICE_ENGINE_AGC
niklase@google.com470e71d2011-07-07 08:21:25 +00002389
2390#ifdef WEBRTC_VOICE_ENGINE_NR
2391
kwiberg55b97fe2016-01-28 05:22:45 -08002392int Channel::SetRxNsStatus(bool enable, NsModes mode) {
2393 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2394 "Channel::SetRxNsStatus(enable=%d, mode=%d)", (int)enable,
2395 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002396
kwiberg55b97fe2016-01-28 05:22:45 -08002397 NoiseSuppression::Level nsLevel = kDefaultNsMode;
2398 switch (mode) {
2399 case kNsDefault:
2400 break;
2401 case kNsUnchanged:
2402 nsLevel = rx_audioproc_->noise_suppression()->level();
2403 break;
2404 case kNsConference:
2405 nsLevel = NoiseSuppression::kHigh;
2406 break;
2407 case kNsLowSuppression:
2408 nsLevel = NoiseSuppression::kLow;
2409 break;
2410 case kNsModerateSuppression:
2411 nsLevel = NoiseSuppression::kModerate;
2412 break;
2413 case kNsHighSuppression:
2414 nsLevel = NoiseSuppression::kHigh;
2415 break;
2416 case kNsVeryHighSuppression:
2417 nsLevel = NoiseSuppression::kVeryHigh;
2418 break;
2419 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002420
kwiberg55b97fe2016-01-28 05:22:45 -08002421 if (rx_audioproc_->noise_suppression()->set_level(nsLevel) != 0) {
2422 _engineStatisticsPtr->SetLastError(
2423 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS level");
2424 return -1;
2425 }
2426 if (rx_audioproc_->noise_suppression()->Enable(enable) != 0) {
2427 _engineStatisticsPtr->SetLastError(
2428 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS state");
2429 return -1;
2430 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002431
kwiberg55b97fe2016-01-28 05:22:45 -08002432 _rxNsIsEnabled = enable;
2433 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002434
kwiberg55b97fe2016-01-28 05:22:45 -08002435 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002436}
2437
kwiberg55b97fe2016-01-28 05:22:45 -08002438int Channel::GetRxNsStatus(bool& enabled, NsModes& mode) {
2439 bool enable = rx_audioproc_->noise_suppression()->is_enabled();
2440 NoiseSuppression::Level ncLevel = rx_audioproc_->noise_suppression()->level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002441
kwiberg55b97fe2016-01-28 05:22:45 -08002442 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002443
kwiberg55b97fe2016-01-28 05:22:45 -08002444 switch (ncLevel) {
2445 case NoiseSuppression::kLow:
2446 mode = kNsLowSuppression;
2447 break;
2448 case NoiseSuppression::kModerate:
2449 mode = kNsModerateSuppression;
2450 break;
2451 case NoiseSuppression::kHigh:
2452 mode = kNsHighSuppression;
2453 break;
2454 case NoiseSuppression::kVeryHigh:
2455 mode = kNsVeryHighSuppression;
2456 break;
2457 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002458
kwiberg55b97fe2016-01-28 05:22:45 -08002459 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002460}
2461
kwiberg55b97fe2016-01-28 05:22:45 -08002462#endif // #ifdef WEBRTC_VOICE_ENGINE_NR
niklase@google.com470e71d2011-07-07 08:21:25 +00002463
kwiberg55b97fe2016-01-28 05:22:45 -08002464int Channel::SetLocalSSRC(unsigned int ssrc) {
2465 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2466 "Channel::SetLocalSSRC()");
2467 if (channel_state_.Get().sending) {
2468 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2469 "SetLocalSSRC() already sending");
2470 return -1;
2471 }
2472 _rtpRtcpModule->SetSSRC(ssrc);
2473 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002474}
2475
kwiberg55b97fe2016-01-28 05:22:45 -08002476int Channel::GetLocalSSRC(unsigned int& ssrc) {
2477 ssrc = _rtpRtcpModule->SSRC();
2478 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002479}
2480
kwiberg55b97fe2016-01-28 05:22:45 -08002481int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2482 ssrc = rtp_receiver_->SSRC();
2483 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002484}
2485
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002486int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002487 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002488 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002489}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002490
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002491int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2492 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002493 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2494 if (enable &&
2495 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2496 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002497 return -1;
2498 }
2499 return 0;
2500}
2501
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002502int Channel::SetSendAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2503 return SetSendRtpHeaderExtension(enable, kRtpExtensionAbsoluteSendTime, id);
2504}
2505
2506int Channel::SetReceiveAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2507 rtp_header_parser_->DeregisterRtpHeaderExtension(
2508 kRtpExtensionAbsoluteSendTime);
kwiberg55b97fe2016-01-28 05:22:45 -08002509 if (enable &&
2510 !rtp_header_parser_->RegisterRtpHeaderExtension(
2511 kRtpExtensionAbsoluteSendTime, id)) {
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00002512 return -1;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002513 }
2514 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002515}
2516
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002517void Channel::EnableSendTransportSequenceNumber(int id) {
2518 int ret =
2519 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2520 RTC_DCHECK_EQ(0, ret);
2521}
2522
stefan3313ec92016-01-21 06:32:43 -08002523void Channel::EnableReceiveTransportSequenceNumber(int id) {
2524 rtp_header_parser_->DeregisterRtpHeaderExtension(
2525 kRtpExtensionTransportSequenceNumber);
2526 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2527 kRtpExtensionTransportSequenceNumber, id);
2528 RTC_DCHECK(ret);
2529}
2530
stefanbba9dec2016-02-01 04:39:55 -08002531void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002532 RtpPacketSender* rtp_packet_sender,
2533 TransportFeedbackObserver* transport_feedback_observer,
2534 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002535 RTC_DCHECK(rtp_packet_sender);
2536 RTC_DCHECK(transport_feedback_observer);
2537 RTC_DCHECK(packet_router && !packet_router_);
2538 feedback_observer_proxy_->SetTransportFeedbackObserver(
2539 transport_feedback_observer);
2540 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2541 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2542 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002543 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002544 packet_router_ = packet_router;
2545}
2546
stefanbba9dec2016-02-01 04:39:55 -08002547void Channel::RegisterReceiverCongestionControlObjects(
2548 PacketRouter* packet_router) {
2549 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002550 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002551 packet_router_ = packet_router;
2552}
2553
2554void Channel::ResetCongestionControlObjects() {
2555 RTC_DCHECK(packet_router_);
2556 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2557 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2558 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002559 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002560 packet_router_ = nullptr;
2561 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2562}
2563
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002564void Channel::SetRTCPStatus(bool enable) {
2565 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2566 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002567 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002568}
2569
kwiberg55b97fe2016-01-28 05:22:45 -08002570int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002571 RtcpMode method = _rtpRtcpModule->RTCP();
2572 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002573 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002574}
2575
kwiberg55b97fe2016-01-28 05:22:45 -08002576int Channel::SetRTCP_CNAME(const char cName[256]) {
2577 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2578 "Channel::SetRTCP_CNAME()");
2579 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2580 _engineStatisticsPtr->SetLastError(
2581 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2582 "SetRTCP_CNAME() failed to set RTCP CNAME");
2583 return -1;
2584 }
2585 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002586}
2587
kwiberg55b97fe2016-01-28 05:22:45 -08002588int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2589 if (cName == NULL) {
2590 _engineStatisticsPtr->SetLastError(
2591 VE_INVALID_ARGUMENT, kTraceError,
2592 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2593 return -1;
2594 }
2595 char cname[RTCP_CNAME_SIZE];
2596 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2597 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2598 _engineStatisticsPtr->SetLastError(
2599 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2600 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2601 return -1;
2602 }
2603 strcpy(cName, cname);
2604 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002605}
2606
kwiberg55b97fe2016-01-28 05:22:45 -08002607int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2608 unsigned int& NTPLow,
2609 unsigned int& timestamp,
2610 unsigned int& playoutTimestamp,
2611 unsigned int* jitter,
2612 unsigned short* fractionLost) {
2613 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002614
kwiberg55b97fe2016-01-28 05:22:45 -08002615 RTCPSenderInfo senderInfo;
2616 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2617 _engineStatisticsPtr->SetLastError(
2618 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2619 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2620 "side");
2621 return -1;
2622 }
2623
2624 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2625 // and octet count)
2626 NTPHigh = senderInfo.NTPseconds;
2627 NTPLow = senderInfo.NTPfraction;
2628 timestamp = senderInfo.RTPtimeStamp;
2629
2630 // --- Locally derived information
2631
2632 // This value is updated on each incoming RTCP packet (0 when no packet
2633 // has been received)
2634 playoutTimestamp = playout_timestamp_rtcp_;
2635
2636 if (NULL != jitter || NULL != fractionLost) {
2637 // Get all RTCP receiver report blocks that have been received on this
2638 // channel. If we receive RTP packets from a remote source we know the
2639 // remote SSRC and use the report block from him.
2640 // Otherwise use the first report block.
2641 std::vector<RTCPReportBlock> remote_stats;
2642 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2643 remote_stats.empty()) {
2644 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2645 "GetRemoteRTCPData() failed to measure statistics due"
2646 " to lack of received RTP and/or RTCP packets");
2647 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002648 }
2649
kwiberg55b97fe2016-01-28 05:22:45 -08002650 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2651 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2652 for (; it != remote_stats.end(); ++it) {
2653 if (it->remoteSSRC == remoteSSRC)
2654 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002655 }
kwiberg55b97fe2016-01-28 05:22:45 -08002656
2657 if (it == remote_stats.end()) {
2658 // If we have not received any RTCP packets from this SSRC it probably
2659 // means that we have not received any RTP packets.
2660 // Use the first received report block instead.
2661 it = remote_stats.begin();
2662 remoteSSRC = it->remoteSSRC;
2663 }
2664
2665 if (jitter) {
2666 *jitter = it->jitter;
2667 }
2668
2669 if (fractionLost) {
2670 *fractionLost = it->fractionLost;
2671 }
2672 }
2673 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002674}
2675
kwiberg55b97fe2016-01-28 05:22:45 -08002676int Channel::SendApplicationDefinedRTCPPacket(
2677 unsigned char subType,
2678 unsigned int name,
2679 const char* data,
2680 unsigned short dataLengthInBytes) {
2681 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2682 "Channel::SendApplicationDefinedRTCPPacket()");
2683 if (!channel_state_.Get().sending) {
2684 _engineStatisticsPtr->SetLastError(
2685 VE_NOT_SENDING, kTraceError,
2686 "SendApplicationDefinedRTCPPacket() not sending");
2687 return -1;
2688 }
2689 if (NULL == data) {
2690 _engineStatisticsPtr->SetLastError(
2691 VE_INVALID_ARGUMENT, kTraceError,
2692 "SendApplicationDefinedRTCPPacket() invalid data value");
2693 return -1;
2694 }
2695 if (dataLengthInBytes % 4 != 0) {
2696 _engineStatisticsPtr->SetLastError(
2697 VE_INVALID_ARGUMENT, kTraceError,
2698 "SendApplicationDefinedRTCPPacket() invalid length value");
2699 return -1;
2700 }
2701 RtcpMode status = _rtpRtcpModule->RTCP();
2702 if (status == RtcpMode::kOff) {
2703 _engineStatisticsPtr->SetLastError(
2704 VE_RTCP_ERROR, kTraceError,
2705 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2706 return -1;
2707 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002708
kwiberg55b97fe2016-01-28 05:22:45 -08002709 // Create and schedule the RTCP APP packet for transmission
2710 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2711 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2712 _engineStatisticsPtr->SetLastError(
2713 VE_SEND_ERROR, kTraceError,
2714 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2715 return -1;
2716 }
2717 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002718}
2719
kwiberg55b97fe2016-01-28 05:22:45 -08002720int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2721 unsigned int& maxJitterMs,
2722 unsigned int& discardedPackets) {
2723 // The jitter statistics is updated for each received RTP packet and is
2724 // based on received packets.
2725 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2726 // If RTCP is off, there is no timed thread in the RTCP module regularly
2727 // generating new stats, trigger the update manually here instead.
2728 StreamStatistician* statistician =
2729 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2730 if (statistician) {
2731 // Don't use returned statistics, use data from proxy instead so that
2732 // max jitter can be fetched atomically.
2733 RtcpStatistics s;
2734 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002735 }
kwiberg55b97fe2016-01-28 05:22:45 -08002736 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002737
kwiberg55b97fe2016-01-28 05:22:45 -08002738 ChannelStatistics stats = statistics_proxy_->GetStats();
2739 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2740 if (playoutFrequency > 0) {
2741 // Scale RTP statistics given the current playout frequency
2742 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2743 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2744 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002745
kwiberg55b97fe2016-01-28 05:22:45 -08002746 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002747
kwiberg55b97fe2016-01-28 05:22:45 -08002748 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002749}
2750
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002751int Channel::GetRemoteRTCPReportBlocks(
2752 std::vector<ReportBlock>* report_blocks) {
2753 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002754 _engineStatisticsPtr->SetLastError(
2755 VE_INVALID_ARGUMENT, kTraceError,
2756 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002757 return -1;
2758 }
2759
2760 // Get the report blocks from the latest received RTCP Sender or Receiver
2761 // Report. Each element in the vector contains the sender's SSRC and a
2762 // report block according to RFC 3550.
2763 std::vector<RTCPReportBlock> rtcp_report_blocks;
2764 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002765 return -1;
2766 }
2767
2768 if (rtcp_report_blocks.empty())
2769 return 0;
2770
2771 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2772 for (; it != rtcp_report_blocks.end(); ++it) {
2773 ReportBlock report_block;
2774 report_block.sender_SSRC = it->remoteSSRC;
2775 report_block.source_SSRC = it->sourceSSRC;
2776 report_block.fraction_lost = it->fractionLost;
2777 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2778 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2779 report_block.interarrival_jitter = it->jitter;
2780 report_block.last_SR_timestamp = it->lastSR;
2781 report_block.delay_since_last_SR = it->delaySinceLastSR;
2782 report_blocks->push_back(report_block);
2783 }
2784 return 0;
2785}
2786
kwiberg55b97fe2016-01-28 05:22:45 -08002787int Channel::GetRTPStatistics(CallStatistics& stats) {
2788 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002789
kwiberg55b97fe2016-01-28 05:22:45 -08002790 // The jitter statistics is updated for each received RTP packet and is
2791 // based on received packets.
2792 RtcpStatistics statistics;
2793 StreamStatistician* statistician =
2794 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002795 if (statistician) {
2796 statistician->GetStatistics(&statistics,
2797 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002798 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002799
kwiberg55b97fe2016-01-28 05:22:45 -08002800 stats.fractionLost = statistics.fraction_lost;
2801 stats.cumulativeLost = statistics.cumulative_lost;
2802 stats.extendedMax = statistics.extended_max_sequence_number;
2803 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002804
kwiberg55b97fe2016-01-28 05:22:45 -08002805 // --- RTT
2806 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002807
kwiberg55b97fe2016-01-28 05:22:45 -08002808 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002809
kwiberg55b97fe2016-01-28 05:22:45 -08002810 size_t bytesSent(0);
2811 uint32_t packetsSent(0);
2812 size_t bytesReceived(0);
2813 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002814
kwiberg55b97fe2016-01-28 05:22:45 -08002815 if (statistician) {
2816 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2817 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002818
kwiberg55b97fe2016-01-28 05:22:45 -08002819 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2820 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2821 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2822 " output will not be complete");
2823 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002824
kwiberg55b97fe2016-01-28 05:22:45 -08002825 stats.bytesSent = bytesSent;
2826 stats.packetsSent = packetsSent;
2827 stats.bytesReceived = bytesReceived;
2828 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002829
kwiberg55b97fe2016-01-28 05:22:45 -08002830 // --- Timestamps
2831 {
2832 rtc::CritScope lock(&ts_stats_lock_);
2833 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2834 }
2835 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002836}
2837
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002838int Channel::SetREDStatus(bool enable, int redPayloadtype) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002839 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002840 "Channel::SetREDStatus()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002841
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002842 if (enable) {
2843 if (redPayloadtype < 0 || redPayloadtype > 127) {
2844 _engineStatisticsPtr->SetLastError(
2845 VE_PLTYPE_ERROR, kTraceError,
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002846 "SetREDStatus() invalid RED payload type");
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00002847 return -1;
2848 }
2849
2850 if (SetRedPayloadType(redPayloadtype) < 0) {
2851 _engineStatisticsPtr->SetLastError(
2852 VE_CODEC_ERROR, kTraceError,
2853 "SetSecondarySendCodec() Failed to register RED ACM");
2854 return -1;
2855 }
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002856 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002857
minyue@webrtc.orgaa5ea1c2014-05-23 15:16:51 +00002858 if (audio_coding_->SetREDStatus(enable) != 0) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002859 _engineStatisticsPtr->SetLastError(
2860 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgaa5ea1c2014-05-23 15:16:51 +00002861 "SetREDStatus() failed to set RED state in the ACM");
turaj@webrtc.org42259e72012-12-11 02:15:12 +00002862 return -1;
2863 }
2864 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002865}
2866
kwiberg55b97fe2016-01-28 05:22:45 -08002867int Channel::GetREDStatus(bool& enabled, int& redPayloadtype) {
2868 enabled = audio_coding_->REDStatus();
2869 if (enabled) {
2870 int8_t payloadType = 0;
2871 if (_rtpRtcpModule->SendREDPayloadType(&payloadType) != 0) {
2872 _engineStatisticsPtr->SetLastError(
2873 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2874 "GetREDStatus() failed to retrieve RED PT from RTP/RTCP "
2875 "module");
2876 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002877 }
kwiberg55b97fe2016-01-28 05:22:45 -08002878 redPayloadtype = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +00002879 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002880 }
2881 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002882}
2883
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002884int Channel::SetCodecFECStatus(bool enable) {
2885 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2886 "Channel::SetCodecFECStatus()");
2887
2888 if (audio_coding_->SetCodecFEC(enable) != 0) {
2889 _engineStatisticsPtr->SetLastError(
2890 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2891 "SetCodecFECStatus() failed to set FEC state");
2892 return -1;
2893 }
2894 return 0;
2895}
2896
2897bool Channel::GetCodecFECStatus() {
2898 bool enabled = audio_coding_->CodecFEC();
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002899 return enabled;
2900}
2901
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002902void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2903 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002904 // If pacing is enabled we always store packets.
2905 if (!pacing_enabled_)
2906 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002907 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
2908 rtp_receiver_->SetNACKStatus(enable ? kNackRtcp : kNackOff);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002909 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002910 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002911 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002912 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002913}
2914
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002915// Called when we are missing one or more packets.
2916int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002917 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2918}
2919
kwiberg55b97fe2016-01-28 05:22:45 -08002920uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2921 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2922 "Channel::Demultiplex()");
2923 _audioFrame.CopyFrom(audioFrame);
2924 _audioFrame.id_ = _channelId;
2925 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002926}
2927
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002928void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002929 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002930 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002931 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002932 CodecInst codec;
2933 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002934
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002935 // Never upsample or upmix the capture signal here. This should be done at the
2936 // end of the send chain.
2937 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2938 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2939 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2940 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002941}
2942
kwiberg55b97fe2016-01-28 05:22:45 -08002943uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2944 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2945 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002946
kwiberg55b97fe2016-01-28 05:22:45 -08002947 if (_audioFrame.samples_per_channel_ == 0) {
2948 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2949 "Channel::PrepareEncodeAndSend() invalid audio frame");
2950 return 0xFFFFFFFF;
2951 }
2952
2953 if (channel_state_.Get().input_file_playing) {
2954 MixOrReplaceAudioWithFile(mixingFrequency);
2955 }
2956
solenberg1c2af8e2016-03-24 10:36:00 -07002957 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2958 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002959
2960 if (channel_state_.Get().input_external_media) {
2961 rtc::CritScope cs(&_callbackCritSect);
2962 const bool isStereo = (_audioFrame.num_channels_ == 2);
2963 if (_inputExternalMediaCallbackPtr) {
2964 _inputExternalMediaCallbackPtr->Process(
2965 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2966 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2967 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002968 }
kwiberg55b97fe2016-01-28 05:22:45 -08002969 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002970
kwiberg55b97fe2016-01-28 05:22:45 -08002971 if (_includeAudioLevelIndication) {
2972 size_t length =
2973 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
solenberg1c2af8e2016-03-24 10:36:00 -07002974 if (is_muted && previous_frame_muted_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002975 rms_level_.ProcessMuted(length);
2976 } else {
2977 rms_level_.Process(_audioFrame.data_, length);
niklase@google.com470e71d2011-07-07 08:21:25 +00002978 }
kwiberg55b97fe2016-01-28 05:22:45 -08002979 }
solenberg1c2af8e2016-03-24 10:36:00 -07002980 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002981
kwiberg55b97fe2016-01-28 05:22:45 -08002982 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002983}
2984
kwiberg55b97fe2016-01-28 05:22:45 -08002985uint32_t Channel::EncodeAndSend() {
2986 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2987 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002988
kwiberg55b97fe2016-01-28 05:22:45 -08002989 assert(_audioFrame.num_channels_ <= 2);
2990 if (_audioFrame.samples_per_channel_ == 0) {
2991 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2992 "Channel::EncodeAndSend() invalid audio frame");
2993 return 0xFFFFFFFF;
2994 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002995
kwiberg55b97fe2016-01-28 05:22:45 -08002996 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002997
kwiberg55b97fe2016-01-28 05:22:45 -08002998 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002999
kwiberg55b97fe2016-01-28 05:22:45 -08003000 // The ACM resamples internally.
3001 _audioFrame.timestamp_ = _timeStamp;
3002 // This call will trigger AudioPacketizationCallback::SendData if encoding
3003 // is done and payload is ready for packetization and transmission.
3004 // Otherwise, it will return without invoking the callback.
3005 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
3006 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
3007 "Channel::EncodeAndSend() ACM encoding failed");
3008 return 0xFFFFFFFF;
3009 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003010
kwiberg55b97fe2016-01-28 05:22:45 -08003011 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
3012 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003013}
3014
Minyue2013aec2015-05-13 14:14:42 +02003015void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08003016 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003017 Channel* channel = associate_send_channel_.channel();
3018 if (channel && channel->ChannelId() == channel_id) {
3019 // If this channel is associated with a send channel of the specified
3020 // Channel ID, disassociate with it.
3021 ChannelOwner ref(NULL);
3022 associate_send_channel_ = ref;
3023 }
3024}
3025
kwiberg55b97fe2016-01-28 05:22:45 -08003026int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
3027 VoEMediaProcess& processObject) {
3028 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3029 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003030
kwiberg55b97fe2016-01-28 05:22:45 -08003031 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003032
kwiberg55b97fe2016-01-28 05:22:45 -08003033 if (kPlaybackPerChannel == type) {
3034 if (_outputExternalMediaCallbackPtr) {
3035 _engineStatisticsPtr->SetLastError(
3036 VE_INVALID_OPERATION, kTraceError,
3037 "Channel::RegisterExternalMediaProcessing() "
3038 "output external media already enabled");
3039 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003040 }
kwiberg55b97fe2016-01-28 05:22:45 -08003041 _outputExternalMediaCallbackPtr = &processObject;
3042 _outputExternalMedia = true;
3043 } else if (kRecordingPerChannel == type) {
3044 if (_inputExternalMediaCallbackPtr) {
3045 _engineStatisticsPtr->SetLastError(
3046 VE_INVALID_OPERATION, kTraceError,
3047 "Channel::RegisterExternalMediaProcessing() "
3048 "output external media already enabled");
3049 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003050 }
kwiberg55b97fe2016-01-28 05:22:45 -08003051 _inputExternalMediaCallbackPtr = &processObject;
3052 channel_state_.SetInputExternalMedia(true);
3053 }
3054 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003055}
3056
kwiberg55b97fe2016-01-28 05:22:45 -08003057int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
3058 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3059 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003060
kwiberg55b97fe2016-01-28 05:22:45 -08003061 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003062
kwiberg55b97fe2016-01-28 05:22:45 -08003063 if (kPlaybackPerChannel == type) {
3064 if (!_outputExternalMediaCallbackPtr) {
3065 _engineStatisticsPtr->SetLastError(
3066 VE_INVALID_OPERATION, kTraceWarning,
3067 "Channel::DeRegisterExternalMediaProcessing() "
3068 "output external media already disabled");
3069 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003070 }
kwiberg55b97fe2016-01-28 05:22:45 -08003071 _outputExternalMedia = false;
3072 _outputExternalMediaCallbackPtr = NULL;
3073 } else if (kRecordingPerChannel == type) {
3074 if (!_inputExternalMediaCallbackPtr) {
3075 _engineStatisticsPtr->SetLastError(
3076 VE_INVALID_OPERATION, kTraceWarning,
3077 "Channel::DeRegisterExternalMediaProcessing() "
3078 "input external media already disabled");
3079 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003080 }
kwiberg55b97fe2016-01-28 05:22:45 -08003081 channel_state_.SetInputExternalMedia(false);
3082 _inputExternalMediaCallbackPtr = NULL;
3083 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003084
kwiberg55b97fe2016-01-28 05:22:45 -08003085 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003086}
3087
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003088int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08003089 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3090 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003091
kwiberg55b97fe2016-01-28 05:22:45 -08003092 if (channel_state_.Get().playing) {
3093 _engineStatisticsPtr->SetLastError(
3094 VE_INVALID_OPERATION, kTraceError,
3095 "Channel::SetExternalMixing() "
3096 "external mixing cannot be changed while playing.");
3097 return -1;
3098 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003099
kwiberg55b97fe2016-01-28 05:22:45 -08003100 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003101
kwiberg55b97fe2016-01-28 05:22:45 -08003102 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003103}
3104
kwiberg55b97fe2016-01-28 05:22:45 -08003105int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3106 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003107}
3108
wu@webrtc.org24301a62013-12-13 19:17:43 +00003109void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3110 audio_coding_->GetDecodingCallStatistics(stats);
3111}
3112
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003113bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3114 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003115 rtc::CritScope lock(&video_sync_lock_);
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003116 if (_average_jitter_buffer_delay_us == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003117 return false;
3118 }
kwiberg55b97fe2016-01-28 05:22:45 -08003119 *jitter_buffer_delay_ms =
3120 (_average_jitter_buffer_delay_us + 500) / 1000 + _recPacketDelayMs;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003121 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003122 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003123}
3124
solenberg358057b2015-11-27 10:46:42 -08003125uint32_t Channel::GetDelayEstimate() const {
3126 int jitter_buffer_delay_ms = 0;
3127 int playout_buffer_delay_ms = 0;
3128 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3129 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3130}
3131
deadbeef74375882015-08-13 12:09:10 -07003132int Channel::LeastRequiredDelayMs() const {
3133 return audio_coding_->LeastRequiredDelayMs();
3134}
3135
kwiberg55b97fe2016-01-28 05:22:45 -08003136int Channel::SetMinimumPlayoutDelay(int delayMs) {
3137 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3138 "Channel::SetMinimumPlayoutDelay()");
3139 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3140 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3141 _engineStatisticsPtr->SetLastError(
3142 VE_INVALID_ARGUMENT, kTraceError,
3143 "SetMinimumPlayoutDelay() invalid min delay");
3144 return -1;
3145 }
3146 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3147 _engineStatisticsPtr->SetLastError(
3148 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3149 "SetMinimumPlayoutDelay() failed to set min playout delay");
3150 return -1;
3151 }
3152 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003153}
3154
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003155int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003156 uint32_t playout_timestamp_rtp = 0;
3157 {
tommi31fc21f2016-01-21 10:37:37 -08003158 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003159 playout_timestamp_rtp = playout_timestamp_rtp_;
3160 }
kwiberg55b97fe2016-01-28 05:22:45 -08003161 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003162 _engineStatisticsPtr->SetLastError(
3163 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3164 "GetPlayoutTimestamp() failed to retrieve timestamp");
3165 return -1;
3166 }
deadbeef74375882015-08-13 12:09:10 -07003167 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003168 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003169}
3170
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003171int Channel::SetInitTimestamp(unsigned int timestamp) {
3172 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003173 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003174 if (channel_state_.Get().sending) {
3175 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3176 "SetInitTimestamp() already sending");
3177 return -1;
3178 }
3179 _rtpRtcpModule->SetStartTimestamp(timestamp);
3180 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003181}
3182
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003183int Channel::SetInitSequenceNumber(short sequenceNumber) {
3184 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3185 "Channel::SetInitSequenceNumber()");
3186 if (channel_state_.Get().sending) {
3187 _engineStatisticsPtr->SetLastError(
3188 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3189 return -1;
3190 }
3191 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3192 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003193}
3194
kwiberg55b97fe2016-01-28 05:22:45 -08003195int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3196 RtpReceiver** rtp_receiver) const {
3197 *rtpRtcpModule = _rtpRtcpModule.get();
3198 *rtp_receiver = rtp_receiver_.get();
3199 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003200}
3201
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003202// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3203// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003204int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003205 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003206 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003207
kwiberg55b97fe2016-01-28 05:22:45 -08003208 {
3209 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003210
kwiberg55b97fe2016-01-28 05:22:45 -08003211 if (_inputFilePlayerPtr == NULL) {
3212 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3213 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3214 " doesnt exist");
3215 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003216 }
3217
kwiberg55b97fe2016-01-28 05:22:45 -08003218 if (_inputFilePlayerPtr->Get10msAudioFromFile(fileBuffer.get(), fileSamples,
3219 mixingFrequency) == -1) {
3220 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3221 "Channel::MixOrReplaceAudioWithFile() file mixing "
3222 "failed");
3223 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003224 }
kwiberg55b97fe2016-01-28 05:22:45 -08003225 if (fileSamples == 0) {
3226 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3227 "Channel::MixOrReplaceAudioWithFile() file is ended");
3228 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003229 }
kwiberg55b97fe2016-01-28 05:22:45 -08003230 }
3231
3232 assert(_audioFrame.samples_per_channel_ == fileSamples);
3233
3234 if (_mixFileWithMicrophone) {
3235 // Currently file stream is always mono.
3236 // TODO(xians): Change the code when FilePlayer supports real stereo.
3237 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3238 1, fileSamples);
3239 } else {
3240 // Replace ACM audio with file.
3241 // Currently file stream is always mono.
3242 // TODO(xians): Change the code when FilePlayer supports real stereo.
3243 _audioFrame.UpdateFrame(
3244 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3245 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3246 }
3247 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003248}
3249
kwiberg55b97fe2016-01-28 05:22:45 -08003250int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3251 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003252
kwibergb7f89d62016-02-17 10:04:18 -08003253 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003254 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003255
kwiberg55b97fe2016-01-28 05:22:45 -08003256 {
3257 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003258
kwiberg55b97fe2016-01-28 05:22:45 -08003259 if (_outputFilePlayerPtr == NULL) {
3260 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3261 "Channel::MixAudioWithFile() file mixing failed");
3262 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003263 }
3264
kwiberg55b97fe2016-01-28 05:22:45 -08003265 // We should get the frequency we ask for.
3266 if (_outputFilePlayerPtr->Get10msAudioFromFile(
3267 fileBuffer.get(), fileSamples, mixingFrequency) == -1) {
3268 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3269 "Channel::MixAudioWithFile() file mixing failed");
3270 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003271 }
kwiberg55b97fe2016-01-28 05:22:45 -08003272 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003273
kwiberg55b97fe2016-01-28 05:22:45 -08003274 if (audioFrame.samples_per_channel_ == fileSamples) {
3275 // Currently file stream is always mono.
3276 // TODO(xians): Change the code when FilePlayer supports real stereo.
3277 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3278 fileSamples);
3279 } else {
3280 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3281 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3282 ") != "
3283 "fileSamples(%" PRIuS ")",
3284 audioFrame.samples_per_channel_, fileSamples);
3285 return -1;
3286 }
3287
3288 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003289}
3290
deadbeef74375882015-08-13 12:09:10 -07003291void Channel::UpdatePlayoutTimestamp(bool rtcp) {
3292 uint32_t playout_timestamp = 0;
3293
kwiberg55b97fe2016-01-28 05:22:45 -08003294 if (audio_coding_->PlayoutTimestamp(&playout_timestamp) == -1) {
deadbeef74375882015-08-13 12:09:10 -07003295 // This can happen if this channel has not been received any RTP packet. In
3296 // this case, NetEq is not capable of computing playout timestamp.
3297 return;
3298 }
3299
3300 uint16_t delay_ms = 0;
3301 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003302 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003303 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3304 " delay from the ADM");
3305 _engineStatisticsPtr->SetLastError(
3306 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3307 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3308 return;
3309 }
3310
3311 jitter_buffer_playout_timestamp_ = playout_timestamp;
3312
3313 // Remove the playout delay.
3314 playout_timestamp -= (delay_ms * (GetPlayoutFrequency() / 1000));
3315
kwiberg55b97fe2016-01-28 05:22:45 -08003316 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003317 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
3318 playout_timestamp);
3319
3320 {
tommi31fc21f2016-01-21 10:37:37 -08003321 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003322 if (rtcp) {
3323 playout_timestamp_rtcp_ = playout_timestamp;
3324 } else {
3325 playout_timestamp_rtp_ = playout_timestamp;
3326 }
3327 playout_delay_ms_ = delay_ms;
3328 }
3329}
3330
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003331// Called for incoming RTP packets after successful RTP header parsing.
3332void Channel::UpdatePacketDelay(uint32_t rtp_timestamp,
3333 uint16_t sequence_number) {
kwiberg55b97fe2016-01-28 05:22:45 -08003334 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003335 "Channel::UpdatePacketDelay(timestamp=%lu, sequenceNumber=%u)",
3336 rtp_timestamp, sequence_number);
niklase@google.com470e71d2011-07-07 08:21:25 +00003337
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003338 // Get frequency of last received payload
wu@webrtc.org94454b72014-06-05 20:34:08 +00003339 int rtp_receive_frequency = GetPlayoutFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +00003340
turaj@webrtc.org167b6df2013-12-13 21:05:07 +00003341 // |jitter_buffer_playout_timestamp_| updated in UpdatePlayoutTimestamp for
3342 // every incoming packet.
kwiberg55b97fe2016-01-28 05:22:45 -08003343 uint32_t timestamp_diff_ms =
3344 (rtp_timestamp - jitter_buffer_playout_timestamp_) /
3345 (rtp_receive_frequency / 1000);
henrik.lundin@webrtc.orgd6692992014-03-20 12:04:09 +00003346 if (!IsNewerTimestamp(rtp_timestamp, jitter_buffer_playout_timestamp_) ||
3347 timestamp_diff_ms > (2 * kVoiceEngineMaxMinPlayoutDelayMs)) {
3348 // If |jitter_buffer_playout_timestamp_| is newer than the incoming RTP
3349 // timestamp, the resulting difference is negative, but is set to zero.
3350 // This can happen when a network glitch causes a packet to arrive late,
3351 // and during long comfort noise periods with clock drift.
3352 timestamp_diff_ms = 0;
3353 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003354
kwiberg55b97fe2016-01-28 05:22:45 -08003355 uint16_t packet_delay_ms =
3356 (rtp_timestamp - _previousTimestamp) / (rtp_receive_frequency / 1000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003357
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003358 _previousTimestamp = rtp_timestamp;
niklase@google.com470e71d2011-07-07 08:21:25 +00003359
kwiberg55b97fe2016-01-28 05:22:45 -08003360 if (timestamp_diff_ms == 0)
3361 return;
niklase@google.com470e71d2011-07-07 08:21:25 +00003362
deadbeef74375882015-08-13 12:09:10 -07003363 {
tommi31fc21f2016-01-21 10:37:37 -08003364 rtc::CritScope lock(&video_sync_lock_);
niklase@google.com470e71d2011-07-07 08:21:25 +00003365
deadbeef74375882015-08-13 12:09:10 -07003366 if (packet_delay_ms >= 10 && packet_delay_ms <= 60) {
3367 _recPacketDelayMs = packet_delay_ms;
3368 }
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003369
deadbeef74375882015-08-13 12:09:10 -07003370 if (_average_jitter_buffer_delay_us == 0) {
3371 _average_jitter_buffer_delay_us = timestamp_diff_ms * 1000;
3372 return;
3373 }
3374
3375 // Filter average delay value using exponential filter (alpha is
3376 // 7/8). We derive 1000 *_average_jitter_buffer_delay_us here (reduces
3377 // risk of rounding error) and compensate for it in GetDelayEstimate()
3378 // later.
kwiberg55b97fe2016-01-28 05:22:45 -08003379 _average_jitter_buffer_delay_us =
3380 (_average_jitter_buffer_delay_us * 7 + 1000 * timestamp_diff_ms + 500) /
3381 8;
deadbeef74375882015-08-13 12:09:10 -07003382 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003383}
3384
kwiberg55b97fe2016-01-28 05:22:45 -08003385void Channel::RegisterReceiveCodecsToRTPModule() {
3386 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3387 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003388
kwiberg55b97fe2016-01-28 05:22:45 -08003389 CodecInst codec;
3390 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003391
kwiberg55b97fe2016-01-28 05:22:45 -08003392 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3393 // Open up the RTP/RTCP receiver for all supported codecs
3394 if ((audio_coding_->Codec(idx, &codec) == -1) ||
3395 (rtp_receiver_->RegisterReceivePayload(
3396 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3397 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
3398 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3399 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3400 " to register %s (%d/%d/%" PRIuS
3401 "/%d) to RTP/RTCP "
3402 "receiver",
3403 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3404 codec.rate);
3405 } else {
3406 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3407 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3408 "(%d/%d/%" PRIuS
3409 "/%d) has been added to the RTP/RTCP "
3410 "receiver",
3411 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3412 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003413 }
kwiberg55b97fe2016-01-28 05:22:45 -08003414 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003415}
3416
turaj@webrtc.org8c8ad852013-01-31 18:20:17 +00003417// Assuming this method is called with valid payload type.
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003418int Channel::SetRedPayloadType(int red_payload_type) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003419 CodecInst codec;
3420 bool found_red = false;
3421
3422 // Get default RED settings from the ACM database
3423 const int num_codecs = AudioCodingModule::NumberOfCodecs();
3424 for (int idx = 0; idx < num_codecs; idx++) {
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00003425 audio_coding_->Codec(idx, &codec);
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003426 if (!STR_CASE_CMP(codec.plname, "RED")) {
3427 found_red = true;
3428 break;
3429 }
3430 }
3431
3432 if (!found_red) {
3433 _engineStatisticsPtr->SetLastError(
3434 VE_CODEC_ERROR, kTraceError,
3435 "SetRedPayloadType() RED is not supported");
3436 return -1;
3437 }
3438
turaj@webrtc.org9d532fd2013-01-31 18:34:19 +00003439 codec.pltype = red_payload_type;
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00003440 if (audio_coding_->RegisterSendCodec(codec) < 0) {
turaj@webrtc.org42259e72012-12-11 02:15:12 +00003441 _engineStatisticsPtr->SetLastError(
3442 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3443 "SetRedPayloadType() RED registration in ACM module failed");
3444 return -1;
3445 }
3446
3447 if (_rtpRtcpModule->SetSendREDPayloadType(red_payload_type) != 0) {
3448 _engineStatisticsPtr->SetLastError(
3449 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
3450 "SetRedPayloadType() RED registration in RTP/RTCP module failed");
3451 return -1;
3452 }
3453 return 0;
3454}
3455
kwiberg55b97fe2016-01-28 05:22:45 -08003456int Channel::SetSendRtpHeaderExtension(bool enable,
3457 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003458 unsigned char id) {
3459 int error = 0;
3460 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3461 if (enable) {
3462 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3463 }
3464 return error;
3465}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003466
wu@webrtc.org94454b72014-06-05 20:34:08 +00003467int32_t Channel::GetPlayoutFrequency() {
3468 int32_t playout_frequency = audio_coding_->PlayoutFrequency();
3469 CodecInst current_recive_codec;
3470 if (audio_coding_->ReceiveCodec(&current_recive_codec) == 0) {
3471 if (STR_CASE_CMP("G722", current_recive_codec.plname) == 0) {
3472 // Even though the actual sampling rate for G.722 audio is
3473 // 16,000 Hz, the RTP clock rate for the G722 payload format is
3474 // 8,000 Hz because that value was erroneously assigned in
3475 // RFC 1890 and must remain unchanged for backward compatibility.
3476 playout_frequency = 8000;
3477 } else if (STR_CASE_CMP("opus", current_recive_codec.plname) == 0) {
3478 // We are resampling Opus internally to 32,000 Hz until all our
3479 // DSP routines can operate at 48,000 Hz, but the RTP clock
3480 // rate for the Opus payload format is standardized to 48,000 Hz,
3481 // because that is the maximum supported decoding sampling rate.
3482 playout_frequency = 48000;
3483 }
3484 }
3485 return playout_frequency;
3486}
3487
Minyue2013aec2015-05-13 14:14:42 +02003488int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003489 RtcpMode method = _rtpRtcpModule->RTCP();
3490 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003491 return 0;
3492 }
3493 std::vector<RTCPReportBlock> report_blocks;
3494 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003495
3496 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003497 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003498 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003499 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003500 Channel* channel = associate_send_channel_.channel();
3501 // Tries to get RTT from an associated channel. This is important for
3502 // receive-only channels.
3503 if (channel) {
3504 // To prevent infinite recursion and deadlock, calling GetRTT of
3505 // associate channel should always use "false" for argument:
3506 // |allow_associate_channel|.
3507 rtt = channel->GetRTT(false);
3508 }
3509 }
3510 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003511 }
3512
3513 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3514 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3515 for (; it != report_blocks.end(); ++it) {
3516 if (it->remoteSSRC == remoteSSRC)
3517 break;
3518 }
3519 if (it == report_blocks.end()) {
3520 // We have not received packets with SSRC matching the report blocks.
3521 // To calculate RTT we try with the SSRC of the first report block.
3522 // This is very important for send-only channels where we don't know
3523 // the SSRC of the other end.
3524 remoteSSRC = report_blocks[0].remoteSSRC;
3525 }
Minyue2013aec2015-05-13 14:14:42 +02003526
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003527 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003528 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003529 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003530 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3531 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003532 return 0;
3533 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003534 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003535}
3536
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003537} // namespace voe
3538} // namespace webrtc