blob: 8287668258986fe10a57738fc6cc9cd9a93c142c [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"
ivoc14d5dbe2016-07-04 07:06:55 -070022#include "webrtc/call/rtc_event_log.h"
minyue@webrtc.orge509f942013-09-12 17:03:00 +000023#include "webrtc/common.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020024#include "webrtc/config.h"
ossue3525782016-05-25 07:37:43 -070025#include "webrtc/modules/audio_coding/codecs/builtin_audio_decoder_factory.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000026#include "webrtc/modules/audio_device/include/audio_device.h"
27#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010028#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010029#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010030#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
31#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
32#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000033#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010034#include "webrtc/modules/utility/include/audio_frame_operations.h"
35#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010036#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000037#include "webrtc/voice_engine/include/voe_base.h"
38#include "webrtc/voice_engine/include/voe_external_media.h"
39#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
40#include "webrtc/voice_engine/output_mixer.h"
41#include "webrtc/voice_engine/statistics.h"
42#include "webrtc/voice_engine/transmit_mixer.h"
43#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000044
andrew@webrtc.org50419b02012-11-14 19:07:54 +000045namespace webrtc {
46namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000047
kwibergc8d071e2016-04-06 12:22:38 -070048namespace {
49
50bool RegisterReceiveCodec(std::unique_ptr<AudioCodingModule>* acm,
51 acm2::RentACodec* rac,
52 const CodecInst& ci) {
kwibergabe95ba2016-06-02 02:58:59 -070053 const int result = (*acm)->RegisterReceiveCodec(
54 ci, [&] { return rac->RentIsacDecoder(ci.plfreq); });
kwibergc8d071e2016-04-06 12:22:38 -070055 return result == 0;
56}
57
58} // namespace
59
solenberg8842c3e2016-03-11 03:06:41 -080060const int kTelephoneEventAttenuationdB = 10;
61
ivoc14d5dbe2016-07-04 07:06:55 -070062class RtcEventLogProxy final : public webrtc::RtcEventLog {
63 public:
64 RtcEventLogProxy() : event_log_(nullptr) {}
65
66 bool StartLogging(const std::string& file_name,
67 int64_t max_size_bytes) override {
68 RTC_NOTREACHED();
69 return false;
70 }
71
72 bool StartLogging(rtc::PlatformFile log_file,
73 int64_t max_size_bytes) override {
74 RTC_NOTREACHED();
75 return false;
76 }
77
78 void StopLogging() override { RTC_NOTREACHED(); }
79
80 void LogVideoReceiveStreamConfig(
81 const webrtc::VideoReceiveStream::Config& config) override {
82 rtc::CritScope lock(&crit_);
83 if (event_log_) {
84 event_log_->LogVideoReceiveStreamConfig(config);
85 }
86 }
87
88 void LogVideoSendStreamConfig(
89 const webrtc::VideoSendStream::Config& config) override {
90 rtc::CritScope lock(&crit_);
91 if (event_log_) {
92 event_log_->LogVideoSendStreamConfig(config);
93 }
94 }
95
96 void LogRtpHeader(webrtc::PacketDirection direction,
97 webrtc::MediaType media_type,
98 const uint8_t* header,
99 size_t packet_length) override {
100 rtc::CritScope lock(&crit_);
101 if (event_log_) {
102 event_log_->LogRtpHeader(direction, media_type, header, packet_length);
103 }
104 }
105
106 void LogRtcpPacket(webrtc::PacketDirection direction,
107 webrtc::MediaType media_type,
108 const uint8_t* packet,
109 size_t length) override {
110 rtc::CritScope lock(&crit_);
111 if (event_log_) {
112 event_log_->LogRtcpPacket(direction, media_type, packet, length);
113 }
114 }
115
116 void LogAudioPlayout(uint32_t ssrc) override {
117 rtc::CritScope lock(&crit_);
118 if (event_log_) {
119 event_log_->LogAudioPlayout(ssrc);
120 }
121 }
122
123 void LogBwePacketLossEvent(int32_t bitrate,
124 uint8_t fraction_loss,
125 int32_t total_packets) override {
126 rtc::CritScope lock(&crit_);
127 if (event_log_) {
128 event_log_->LogBwePacketLossEvent(bitrate, fraction_loss, total_packets);
129 }
130 }
131
132 void SetEventLog(RtcEventLog* event_log) {
133 rtc::CritScope lock(&crit_);
134 event_log_ = event_log;
135 }
136
137 private:
138 rtc::CriticalSection crit_;
139 RtcEventLog* event_log_ GUARDED_BY(crit_);
140 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
141};
142
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100143class TransportFeedbackProxy : public TransportFeedbackObserver {
144 public:
145 TransportFeedbackProxy() : feedback_observer_(nullptr) {
146 pacer_thread_.DetachFromThread();
147 network_thread_.DetachFromThread();
148 }
149
150 void SetTransportFeedbackObserver(
151 TransportFeedbackObserver* feedback_observer) {
152 RTC_DCHECK(thread_checker_.CalledOnValidThread());
153 rtc::CritScope lock(&crit_);
154 feedback_observer_ = feedback_observer;
155 }
156
157 // Implements TransportFeedbackObserver.
158 void AddPacket(uint16_t sequence_number,
159 size_t length,
philipela1ed0b32016-06-01 06:31:17 -0700160 int probe_cluster_id) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100161 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
162 rtc::CritScope lock(&crit_);
163 if (feedback_observer_)
pbos2169d8b2016-06-20 11:53:02 -0700164 feedback_observer_->AddPacket(sequence_number, length, probe_cluster_id);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100165 }
166 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
167 RTC_DCHECK(network_thread_.CalledOnValidThread());
168 rtc::CritScope lock(&crit_);
169 if (feedback_observer_)
170 feedback_observer_->OnTransportFeedback(feedback);
171 }
172
173 private:
174 rtc::CriticalSection crit_;
175 rtc::ThreadChecker thread_checker_;
176 rtc::ThreadChecker pacer_thread_;
177 rtc::ThreadChecker network_thread_;
178 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
179};
180
181class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
182 public:
183 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
184 pacer_thread_.DetachFromThread();
185 }
186
187 void SetSequenceNumberAllocator(
188 TransportSequenceNumberAllocator* seq_num_allocator) {
189 RTC_DCHECK(thread_checker_.CalledOnValidThread());
190 rtc::CritScope lock(&crit_);
191 seq_num_allocator_ = seq_num_allocator;
192 }
193
194 // Implements TransportSequenceNumberAllocator.
195 uint16_t AllocateSequenceNumber() override {
196 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
197 rtc::CritScope lock(&crit_);
198 if (!seq_num_allocator_)
199 return 0;
200 return seq_num_allocator_->AllocateSequenceNumber();
201 }
202
203 private:
204 rtc::CriticalSection crit_;
205 rtc::ThreadChecker thread_checker_;
206 rtc::ThreadChecker pacer_thread_;
207 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
208};
209
210class RtpPacketSenderProxy : public RtpPacketSender {
211 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800212 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100213
214 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
215 RTC_DCHECK(thread_checker_.CalledOnValidThread());
216 rtc::CritScope lock(&crit_);
217 rtp_packet_sender_ = rtp_packet_sender;
218 }
219
220 // Implements RtpPacketSender.
221 void InsertPacket(Priority priority,
222 uint32_t ssrc,
223 uint16_t sequence_number,
224 int64_t capture_time_ms,
225 size_t bytes,
226 bool retransmission) override {
227 rtc::CritScope lock(&crit_);
228 if (rtp_packet_sender_) {
229 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
230 capture_time_ms, bytes, retransmission);
231 }
232 }
233
234 private:
235 rtc::ThreadChecker thread_checker_;
236 rtc::CriticalSection crit_;
237 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
238};
239
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000240// Extend the default RTCP statistics struct with max_jitter, defined as the
241// maximum jitter value seen in an RTCP report block.
242struct ChannelStatistics : public RtcpStatistics {
243 ChannelStatistics() : rtcp(), max_jitter(0) {}
244
245 RtcpStatistics rtcp;
246 uint32_t max_jitter;
247};
248
249// Statistics callback, called at each generation of a new RTCP report block.
250class StatisticsProxy : public RtcpStatisticsCallback {
251 public:
tommi31fc21f2016-01-21 10:37:37 -0800252 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000253 virtual ~StatisticsProxy() {}
254
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000255 void StatisticsUpdated(const RtcpStatistics& statistics,
256 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000257 if (ssrc != ssrc_)
258 return;
259
tommi31fc21f2016-01-21 10:37:37 -0800260 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000261 stats_.rtcp = statistics;
262 if (statistics.jitter > stats_.max_jitter) {
263 stats_.max_jitter = statistics.jitter;
264 }
265 }
266
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000267 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000268
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000269 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800270 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000271 return stats_;
272 }
273
274 private:
275 // StatisticsUpdated calls are triggered from threads in the RTP module,
276 // while GetStats calls can be triggered from the public voice engine API,
277 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800278 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000279 const uint32_t ssrc_;
280 ChannelStatistics stats_;
281};
282
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000283class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000284 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000285 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
286 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000287
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000288 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
289 // Not used for Voice Engine.
290 }
291
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000292 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
293 int64_t rtt,
294 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000295 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
296 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
297 // report for VoiceEngine?
298 if (report_blocks.empty())
299 return;
300
301 int fraction_lost_aggregate = 0;
302 int total_number_of_packets = 0;
303
304 // If receiving multiple report blocks, calculate the weighted average based
305 // on the number of packets a report refers to.
306 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
307 block_it != report_blocks.end(); ++block_it) {
308 // Find the previous extended high sequence number for this remote SSRC,
309 // to calculate the number of RTP packets this report refers to. Ignore if
310 // we haven't seen this SSRC before.
311 std::map<uint32_t, uint32_t>::iterator seq_num_it =
312 extended_max_sequence_number_.find(block_it->sourceSSRC);
313 int number_of_packets = 0;
314 if (seq_num_it != extended_max_sequence_number_.end()) {
315 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
316 }
317 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
318 total_number_of_packets += number_of_packets;
319
320 extended_max_sequence_number_[block_it->sourceSSRC] =
321 block_it->extendedHighSeqNum;
322 }
323 int weighted_fraction_lost = 0;
324 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800325 weighted_fraction_lost =
326 (fraction_lost_aggregate + total_number_of_packets / 2) /
327 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000328 }
329 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000330 }
331
332 private:
333 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000334 // Maps remote side ssrc to extended highest sequence number received.
335 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000336};
337
kwiberg55b97fe2016-01-28 05:22:45 -0800338int32_t Channel::SendData(FrameType frameType,
339 uint8_t payloadType,
340 uint32_t timeStamp,
341 const uint8_t* payloadData,
342 size_t payloadSize,
343 const RTPFragmentationHeader* fragmentation) {
344 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
345 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
346 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
347 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000348
kwiberg55b97fe2016-01-28 05:22:45 -0800349 if (_includeAudioLevelIndication) {
350 // Store current audio level in the RTP/RTCP module.
351 // The level will be used in combination with voice-activity state
352 // (frameType) to add an RTP header extension
353 _rtpRtcpModule->SetAudioLevel(rms_level_.RMS());
354 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000355
kwiberg55b97fe2016-01-28 05:22:45 -0800356 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
357 // packetization.
358 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
359 if (_rtpRtcpModule->SendOutgoingData(
360 (FrameType&)frameType, payloadType, timeStamp,
361 // Leaving the time when this frame was
362 // received from the capture device as
363 // undefined for voice for now.
364 -1, payloadData, payloadSize, fragmentation) == -1) {
365 _engineStatisticsPtr->SetLastError(
366 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
367 "Channel::SendData() failed to send data to RTP/RTCP module");
368 return -1;
369 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000370
kwiberg55b97fe2016-01-28 05:22:45 -0800371 _lastLocalTimeStamp = timeStamp;
372 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000373
kwiberg55b97fe2016-01-28 05:22:45 -0800374 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000375}
376
kwiberg55b97fe2016-01-28 05:22:45 -0800377int32_t Channel::InFrameType(FrameType frame_type) {
378 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
379 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000380
kwiberg55b97fe2016-01-28 05:22:45 -0800381 rtc::CritScope cs(&_callbackCritSect);
382 _sendFrameType = (frame_type == kAudioFrameSpeech);
383 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000384}
385
kwiberg55b97fe2016-01-28 05:22:45 -0800386int32_t Channel::OnRxVadDetected(int vadDecision) {
387 rtc::CritScope cs(&_callbackCritSect);
388 if (_rxVadObserverPtr) {
389 _rxVadObserverPtr->OnRxVad(_channelId, vadDecision);
390 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000391
kwiberg55b97fe2016-01-28 05:22:45 -0800392 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000393}
394
stefan1d8a5062015-10-02 03:39:33 -0700395bool Channel::SendRtp(const uint8_t* data,
396 size_t len,
397 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800398 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
399 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000400
kwiberg55b97fe2016-01-28 05:22:45 -0800401 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000402
kwiberg55b97fe2016-01-28 05:22:45 -0800403 if (_transportPtr == NULL) {
404 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
405 "Channel::SendPacket() failed to send RTP packet due to"
406 " invalid transport object");
407 return false;
408 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000409
kwiberg55b97fe2016-01-28 05:22:45 -0800410 uint8_t* bufferToSendPtr = (uint8_t*)data;
411 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000412
kwiberg55b97fe2016-01-28 05:22:45 -0800413 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
414 std::string transport_name =
415 _externalTransport ? "external transport" : "WebRtc sockets";
416 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
417 "Channel::SendPacket() RTP transmission using %s failed",
418 transport_name.c_str());
419 return false;
420 }
421 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000422}
423
kwiberg55b97fe2016-01-28 05:22:45 -0800424bool Channel::SendRtcp(const uint8_t* data, size_t len) {
425 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
426 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000427
kwiberg55b97fe2016-01-28 05:22:45 -0800428 rtc::CritScope cs(&_callbackCritSect);
429 if (_transportPtr == NULL) {
430 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
431 "Channel::SendRtcp() failed to send RTCP packet"
432 " due to invalid transport object");
433 return false;
434 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000435
kwiberg55b97fe2016-01-28 05:22:45 -0800436 uint8_t* bufferToSendPtr = (uint8_t*)data;
437 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000438
kwiberg55b97fe2016-01-28 05:22:45 -0800439 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
440 if (n < 0) {
441 std::string transport_name =
442 _externalTransport ? "external transport" : "WebRtc sockets";
443 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
444 "Channel::SendRtcp() transmission using %s failed",
445 transport_name.c_str());
446 return false;
447 }
448 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000449}
450
kwiberg55b97fe2016-01-28 05:22:45 -0800451void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
452 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
453 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000454
kwiberg55b97fe2016-01-28 05:22:45 -0800455 // Update ssrc so that NTP for AV sync can be updated.
456 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000457}
458
Peter Boströmac547a62015-09-17 23:03:57 +0200459void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
460 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
461 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
462 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000463}
464
Peter Boströmac547a62015-09-17 23:03:57 +0200465int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000466 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000467 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000468 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800469 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200470 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800471 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
472 "Channel::OnInitializeDecoder(payloadType=%d, "
473 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
474 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000475
kwiberg55b97fe2016-01-28 05:22:45 -0800476 CodecInst receiveCodec = {0};
477 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000478
kwiberg55b97fe2016-01-28 05:22:45 -0800479 receiveCodec.pltype = payloadType;
480 receiveCodec.plfreq = frequency;
481 receiveCodec.channels = channels;
482 receiveCodec.rate = rate;
483 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000484
kwiberg55b97fe2016-01-28 05:22:45 -0800485 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
486 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000487
kwiberg55b97fe2016-01-28 05:22:45 -0800488 // Register the new codec to the ACM
kwibergc8d071e2016-04-06 12:22:38 -0700489 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, receiveCodec)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800490 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
491 "Channel::OnInitializeDecoder() invalid codec ("
492 "pt=%d, name=%s) received - 1",
493 payloadType, payloadName);
494 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
495 return -1;
496 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000497
kwiberg55b97fe2016-01-28 05:22:45 -0800498 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000499}
500
kwiberg55b97fe2016-01-28 05:22:45 -0800501int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
502 size_t payloadSize,
503 const WebRtcRTPHeader* rtpHeader) {
504 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
505 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
506 ","
507 " payloadType=%u, audioChannel=%" PRIuS ")",
508 payloadSize, rtpHeader->header.payloadType,
509 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000510
kwiberg55b97fe2016-01-28 05:22:45 -0800511 if (!channel_state_.Get().playing) {
512 // Avoid inserting into NetEQ when we are not playing. Count the
513 // packet as discarded.
514 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
515 "received packet is discarded since playing is not"
516 " activated");
517 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000518 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800519 }
520
521 // Push the incoming payload (parsed and ready for decoding) into the ACM
522 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
523 0) {
524 _engineStatisticsPtr->SetLastError(
525 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
526 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
527 return -1;
528 }
529
530 // Update the packet delay.
531 UpdatePacketDelay(rtpHeader->header.timestamp,
532 rtpHeader->header.sequenceNumber);
533
534 int64_t round_trip_time = 0;
535 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
536 NULL);
537
538 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
539 if (!nack_list.empty()) {
540 // Can't use nack_list.data() since it's not supported by all
541 // compilers.
542 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
543 }
544 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000545}
546
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000547bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000548 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000549 RTPHeader header;
550 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
551 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
552 "IncomingPacket invalid RTP header");
553 return false;
554 }
555 header.payload_type_frequency =
556 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
557 if (header.payload_type_frequency < 0)
558 return false;
559 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
560}
561
henrik.lundin42dda502016-05-18 05:36:01 -0700562MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
563 int32_t id,
564 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700565 unsigned int ssrc;
566 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
567 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800568 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700569 bool muted;
570 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
571 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800572 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
573 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
574 // In all likelihood, the audio in this frame is garbage. We return an
575 // error so that the audio mixer module doesn't add it to the mix. As
576 // a result, it won't be played out and the actions skipped here are
577 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700578 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800579 }
henrik.lundina89ab962016-05-18 08:52:45 -0700580
581 if (muted) {
582 // TODO(henrik.lundin): We should be able to do better than this. But we
583 // will have to go through all the cases below where the audio samples may
584 // be used, and handle the muted case in some way.
585 audioFrame->Mute();
586 }
kwiberg55b97fe2016-01-28 05:22:45 -0800587
588 if (_RxVadDetection) {
589 UpdateRxVadDetection(*audioFrame);
590 }
591
592 // Convert module ID to internal VoE channel ID
593 audioFrame->id_ = VoEChannelId(audioFrame->id_);
594 // Store speech type for dead-or-alive detection
595 _outputSpeechType = audioFrame->speech_type_;
596
597 ChannelState::State state = channel_state_.Get();
598
599 if (state.rx_apm_is_enabled) {
600 int err = rx_audioproc_->ProcessStream(audioFrame);
601 if (err) {
602 LOG(LS_ERROR) << "ProcessStream() error: " << err;
603 assert(false);
Ivo Creusenae856f22015-09-17 16:30:16 +0200604 }
kwiberg55b97fe2016-01-28 05:22:45 -0800605 }
606
607 {
608 // Pass the audio buffers to an optional sink callback, before applying
609 // scaling/panning, as that applies to the mix operation.
610 // External recipients of the audio (e.g. via AudioTrack), will do their
611 // own mixing/dynamic processing.
612 rtc::CritScope cs(&_callbackCritSect);
613 if (audio_sink_) {
614 AudioSinkInterface::Data data(
615 &audioFrame->data_[0], audioFrame->samples_per_channel_,
616 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
617 audioFrame->timestamp_);
618 audio_sink_->OnData(data);
619 }
620 }
621
622 float output_gain = 1.0f;
623 float left_pan = 1.0f;
624 float right_pan = 1.0f;
625 {
626 rtc::CritScope cs(&volume_settings_critsect_);
627 output_gain = _outputGain;
628 left_pan = _panLeft;
629 right_pan = _panRight;
630 }
631
632 // Output volume scaling
633 if (output_gain < 0.99f || output_gain > 1.01f) {
634 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
635 }
636
637 // Scale left and/or right channel(s) if stereo and master balance is
638 // active
639
640 if (left_pan != 1.0f || right_pan != 1.0f) {
641 if (audioFrame->num_channels_ == 1) {
642 // Emulate stereo mode since panning is active.
643 // The mono signal is copied to both left and right channels here.
644 AudioFrameOperations::MonoToStereo(audioFrame);
645 }
646 // For true stereo mode (when we are receiving a stereo signal), no
647 // action is needed.
648
649 // Do the panning operation (the audio frame contains stereo at this
650 // stage)
651 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
652 }
653
654 // Mix decoded PCM output with file if file mixing is enabled
655 if (state.output_file_playing) {
656 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700657 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800658 }
659
660 // External media
661 if (_outputExternalMedia) {
662 rtc::CritScope cs(&_callbackCritSect);
663 const bool isStereo = (audioFrame->num_channels_ == 2);
664 if (_outputExternalMediaCallbackPtr) {
665 _outputExternalMediaCallbackPtr->Process(
666 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
667 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
668 isStereo);
669 }
670 }
671
672 // Record playout if enabled
673 {
674 rtc::CritScope cs(&_fileCritSect);
675
676 if (_outputFileRecording && _outputFileRecorderPtr) {
677 _outputFileRecorderPtr->RecordAudioToFile(*audioFrame);
678 }
679 }
680
681 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700682 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800683 _outputAudioLevel.ComputeLevel(*audioFrame);
684
685 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
686 // The first frame with a valid rtp timestamp.
687 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
688 }
689
690 if (capture_start_rtp_time_stamp_ >= 0) {
691 // audioFrame.timestamp_ should be valid from now on.
692
693 // Compute elapsed time.
694 int64_t unwrap_timestamp =
695 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
696 audioFrame->elapsed_time_ms_ =
697 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
698 (GetPlayoutFrequency() / 1000);
699
niklase@google.com470e71d2011-07-07 08:21:25 +0000700 {
kwiberg55b97fe2016-01-28 05:22:45 -0800701 rtc::CritScope lock(&ts_stats_lock_);
702 // Compute ntp time.
703 audioFrame->ntp_time_ms_ =
704 ntp_estimator_.Estimate(audioFrame->timestamp_);
705 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
706 if (audioFrame->ntp_time_ms_ > 0) {
707 // Compute |capture_start_ntp_time_ms_| so that
708 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
709 capture_start_ntp_time_ms_ =
710 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000711 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000712 }
kwiberg55b97fe2016-01-28 05:22:45 -0800713 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000714
henrik.lundin42dda502016-05-18 05:36:01 -0700715 return muted ? MixerParticipant::AudioFrameInfo::kMuted
716 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000717}
718
kwiberg55b97fe2016-01-28 05:22:45 -0800719int32_t Channel::NeededFrequency(int32_t id) const {
720 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
721 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000722
kwiberg55b97fe2016-01-28 05:22:45 -0800723 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000724
kwiberg55b97fe2016-01-28 05:22:45 -0800725 // Determine highest needed receive frequency
726 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000727
kwiberg55b97fe2016-01-28 05:22:45 -0800728 // Return the bigger of playout and receive frequency in the ACM.
729 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
730 highestNeeded = audio_coding_->PlayoutFrequency();
731 } else {
732 highestNeeded = receiveFrequency;
733 }
734
735 // Special case, if we're playing a file on the playout side
736 // we take that frequency into consideration as well
737 // This is not needed on sending side, since the codec will
738 // limit the spectrum anyway.
739 if (channel_state_.Get().output_file_playing) {
740 rtc::CritScope cs(&_fileCritSect);
741 if (_outputFilePlayerPtr) {
742 if (_outputFilePlayerPtr->Frequency() > highestNeeded) {
743 highestNeeded = _outputFilePlayerPtr->Frequency();
744 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000745 }
kwiberg55b97fe2016-01-28 05:22:45 -0800746 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000747
kwiberg55b97fe2016-01-28 05:22:45 -0800748 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000749}
750
ivocb04965c2015-09-09 00:09:43 -0700751int32_t Channel::CreateChannel(Channel*& channel,
752 int32_t channelId,
753 uint32_t instanceId,
ivocb04965c2015-09-09 00:09:43 -0700754 const Config& config) {
ivoc14d5dbe2016-07-04 07:06:55 -0700755 return CreateChannel(channel, channelId, instanceId, config,
ossu5f7cfa52016-05-30 08:11:28 -0700756 CreateBuiltinAudioDecoderFactory());
757}
758
759int32_t Channel::CreateChannel(
760 Channel*& channel,
761 int32_t channelId,
762 uint32_t instanceId,
ossu5f7cfa52016-05-30 08:11:28 -0700763 const Config& config,
764 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory) {
kwiberg55b97fe2016-01-28 05:22:45 -0800765 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
766 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
767 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000768
ivoc14d5dbe2016-07-04 07:06:55 -0700769 channel = new Channel(channelId, instanceId, config, decoder_factory);
kwiberg55b97fe2016-01-28 05:22:45 -0800770 if (channel == NULL) {
771 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
772 "Channel::CreateChannel() unable to allocate memory for"
773 " channel");
774 return -1;
775 }
776 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000777}
778
kwiberg55b97fe2016-01-28 05:22:45 -0800779void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
780 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
781 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
782 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000783
kwiberg55b97fe2016-01-28 05:22:45 -0800784 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000785}
786
kwiberg55b97fe2016-01-28 05:22:45 -0800787void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
788 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
789 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
790 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000791
kwiberg55b97fe2016-01-28 05:22:45 -0800792 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000793}
794
kwiberg55b97fe2016-01-28 05:22:45 -0800795void Channel::PlayFileEnded(int32_t id) {
796 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
797 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000798
kwiberg55b97fe2016-01-28 05:22:45 -0800799 if (id == _inputFilePlayerId) {
800 channel_state_.SetInputFilePlaying(false);
801 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
802 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000803 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800804 } else if (id == _outputFilePlayerId) {
805 channel_state_.SetOutputFilePlaying(false);
806 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
807 "Channel::PlayFileEnded() => output file player module is"
808 " shutdown");
809 }
810}
811
812void Channel::RecordFileEnded(int32_t id) {
813 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
814 "Channel::RecordFileEnded(id=%d)", id);
815
816 assert(id == _outputFileRecorderId);
817
818 rtc::CritScope cs(&_fileCritSect);
819
820 _outputFileRecording = false;
821 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
822 "Channel::RecordFileEnded() => output file recorder module is"
823 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000824}
825
pbos@webrtc.org92135212013-05-14 08:31:39 +0000826Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000827 uint32_t instanceId,
ossu5f7cfa52016-05-30 08:11:28 -0700828 const Config& config,
829 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
tommi31fc21f2016-01-21 10:37:37 -0800830 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100831 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700832 event_log_proxy_(new RtcEventLogProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100833 rtp_header_parser_(RtpHeaderParser::Create()),
834 rtp_payload_registry_(
835 new RTPPayloadRegistry(RTPPayloadStrategy::CreateStrategy(true))),
836 rtp_receive_statistics_(
837 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
838 rtp_receiver_(
839 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100840 this,
841 this,
842 rtp_payload_registry_.get())),
843 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
844 _outputAudioLevel(),
845 _externalTransport(false),
846 _inputFilePlayerPtr(NULL),
847 _outputFilePlayerPtr(NULL),
848 _outputFileRecorderPtr(NULL),
849 // Avoid conflict with other channels by adding 1024 - 1026,
850 // won't use as much as 1024 channels.
851 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
852 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
853 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
854 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100855 _outputExternalMedia(false),
856 _inputExternalMediaCallbackPtr(NULL),
857 _outputExternalMediaCallbackPtr(NULL),
858 _timeStamp(0), // This is just an offset, RTP module will add it's own
859 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100860 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100861 playout_timestamp_rtp_(0),
862 playout_timestamp_rtcp_(0),
863 playout_delay_ms_(0),
864 _numberOfDiscardedPackets(0),
865 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100866 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
867 capture_start_rtp_time_stamp_(-1),
868 capture_start_ntp_time_ms_(-1),
869 _engineStatisticsPtr(NULL),
870 _outputMixerPtr(NULL),
871 _transmitMixerPtr(NULL),
872 _moduleProcessThreadPtr(NULL),
873 _audioDeviceModulePtr(NULL),
874 _voiceEngineObserverPtr(NULL),
875 _callbackCritSectPtr(NULL),
876 _transportPtr(NULL),
877 _rxVadObserverPtr(NULL),
878 _oldVadDecision(-1),
879 _sendFrameType(0),
880 _externalMixing(false),
881 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700882 input_mute_(false),
883 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100884 _panLeft(1.0f),
885 _panRight(1.0f),
886 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100887 _lastLocalTimeStamp(0),
888 _lastPayloadType(0),
889 _includeAudioLevelIndication(false),
890 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100891 _average_jitter_buffer_delay_us(0),
892 _previousTimestamp(0),
893 _recPacketDelayMs(20),
894 _RxVadDetection(false),
895 _rxAgcIsEnabled(false),
896 _rxNsIsEnabled(false),
897 restored_packet_in_use_(false),
898 rtcp_observer_(new VoERtcpObserver(this)),
899 network_predictor_(new NetworkPredictor(Clock::GetRealTimeClock())),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100900 associate_send_channel_(ChannelOwner(nullptr)),
901 pacing_enabled_(config.Get<VoicePacing>().enabled),
stefanbba9dec2016-02-01 04:39:55 -0800902 feedback_observer_proxy_(new TransportFeedbackProxy()),
903 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700904 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
905 decoder_factory_(decoder_factory) {
kwiberg55b97fe2016-01-28 05:22:45 -0800906 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
907 "Channel::Channel() - ctor");
908 AudioCodingModule::Config acm_config;
909 acm_config.id = VoEModuleId(instanceId, channelId);
910 if (config.Get<NetEqCapacityConfig>().enabled) {
911 // Clamping the buffer capacity at 20 packets. While going lower will
912 // probably work, it makes little sense.
913 acm_config.neteq_config.max_packets_in_buffer =
914 std::max(20, config.Get<NetEqCapacityConfig>().capacity);
915 }
916 acm_config.neteq_config.enable_fast_accelerate =
917 config.Get<NetEqFastAccelerate>().enabled;
henrik.lundina89ab962016-05-18 08:52:45 -0700918 acm_config.neteq_config.enable_muted_state = true;
ossu5f7cfa52016-05-30 08:11:28 -0700919 acm_config.decoder_factory = decoder_factory;
kwiberg55b97fe2016-01-28 05:22:45 -0800920 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200921
kwiberg55b97fe2016-01-28 05:22:45 -0800922 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000923
kwiberg55b97fe2016-01-28 05:22:45 -0800924 RtpRtcp::Configuration configuration;
925 configuration.audio = true;
926 configuration.outgoing_transport = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800927 configuration.receive_statistics = rtp_receive_statistics_.get();
928 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800929 if (pacing_enabled_) {
930 configuration.paced_sender = rtp_packet_sender_proxy_.get();
931 configuration.transport_sequence_number_allocator =
932 seq_num_allocator_proxy_.get();
933 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
934 }
ivoc14d5dbe2016-07-04 07:06:55 -0700935 configuration.event_log = &(*event_log_proxy_);
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000936
kwiberg55b97fe2016-01-28 05:22:45 -0800937 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100938 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000939
kwiberg55b97fe2016-01-28 05:22:45 -0800940 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
941 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
942 statistics_proxy_.get());
aluebs@webrtc.orgf927fd62014-04-16 11:58:18 +0000943
kwiberg55b97fe2016-01-28 05:22:45 -0800944 Config audioproc_config;
945 audioproc_config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
946 rx_audioproc_.reset(AudioProcessing::Create(audioproc_config));
niklase@google.com470e71d2011-07-07 08:21:25 +0000947}
948
kwiberg55b97fe2016-01-28 05:22:45 -0800949Channel::~Channel() {
950 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
951 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
952 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000953
kwiberg55b97fe2016-01-28 05:22:45 -0800954 if (_outputExternalMedia) {
955 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
956 }
957 if (channel_state_.Get().input_external_media) {
958 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
959 }
960 StopSend();
961 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000962
kwiberg55b97fe2016-01-28 05:22:45 -0800963 {
964 rtc::CritScope cs(&_fileCritSect);
965 if (_inputFilePlayerPtr) {
966 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
967 _inputFilePlayerPtr->StopPlayingFile();
968 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
969 _inputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000970 }
kwiberg55b97fe2016-01-28 05:22:45 -0800971 if (_outputFilePlayerPtr) {
972 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
973 _outputFilePlayerPtr->StopPlayingFile();
974 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
975 _outputFilePlayerPtr = NULL;
976 }
977 if (_outputFileRecorderPtr) {
978 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
979 _outputFileRecorderPtr->StopRecording();
980 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
981 _outputFileRecorderPtr = NULL;
982 }
983 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000984
kwiberg55b97fe2016-01-28 05:22:45 -0800985 // The order to safely shutdown modules in a channel is:
986 // 1. De-register callbacks in modules
987 // 2. De-register modules in process thread
988 // 3. Destroy modules
989 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
990 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
991 "~Channel() failed to de-register transport callback"
992 " (Audio coding module)");
993 }
994 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
995 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
996 "~Channel() failed to de-register VAD callback"
997 " (Audio coding module)");
998 }
999 // De-register modules in process thread
1000 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +00001001
kwiberg55b97fe2016-01-28 05:22:45 -08001002 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +00001003}
1004
kwiberg55b97fe2016-01-28 05:22:45 -08001005int32_t Channel::Init() {
1006 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1007 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001008
kwiberg55b97fe2016-01-28 05:22:45 -08001009 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001010
kwiberg55b97fe2016-01-28 05:22:45 -08001011 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +00001012
kwiberg55b97fe2016-01-28 05:22:45 -08001013 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
1014 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1015 "Channel::Init() must call SetEngineInformation() first");
1016 return -1;
1017 }
1018
1019 // --- Add modules to process thread (for periodic schedulation)
1020
1021 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
1022
1023 // --- ACM initialization
1024
1025 if (audio_coding_->InitializeReceiver() == -1) {
1026 _engineStatisticsPtr->SetLastError(
1027 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1028 "Channel::Init() unable to initialize the ACM - 1");
1029 return -1;
1030 }
1031
1032 // --- RTP/RTCP module initialization
1033
1034 // Ensure that RTCP is enabled by default for the created channel.
1035 // Note that, the module will keep generating RTCP until it is explicitly
1036 // disabled by the user.
1037 // After StopListen (when no sockets exists), RTCP packets will no longer
1038 // be transmitted since the Transport object will then be invalid.
1039 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
1040 // RTCP is enabled by default.
1041 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1042 // --- Register all permanent callbacks
1043 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
1044 (audio_coding_->RegisterVADCallback(this) == -1);
1045
1046 if (fail) {
1047 _engineStatisticsPtr->SetLastError(
1048 VE_CANNOT_INIT_CHANNEL, kTraceError,
1049 "Channel::Init() callbacks not registered");
1050 return -1;
1051 }
1052
1053 // --- Register all supported codecs to the receiving side of the
1054 // RTP/RTCP module
1055
1056 CodecInst codec;
1057 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1058
1059 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1060 // Open up the RTP/RTCP receiver for all supported codecs
1061 if ((audio_coding_->Codec(idx, &codec) == -1) ||
1062 (rtp_receiver_->RegisterReceivePayload(
1063 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1064 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
1065 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1066 "Channel::Init() unable to register %s "
1067 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1068 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1069 codec.rate);
1070 } else {
1071 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1072 "Channel::Init() %s (%d/%d/%" PRIuS
1073 "/%d) has been "
1074 "added to the RTP/RTCP receiver",
1075 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1076 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001077 }
1078
kwiberg55b97fe2016-01-28 05:22:45 -08001079 // Ensure that PCMU is used as default codec on the sending side
1080 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1081 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001082 }
1083
kwiberg55b97fe2016-01-28 05:22:45 -08001084 // Register default PT for outband 'telephone-event'
1085 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001086 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
1087 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001088 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1089 "Channel::Init() failed to register outband "
1090 "'telephone-event' (%d/%d) correctly",
1091 codec.pltype, codec.plfreq);
1092 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001093 }
1094
kwiberg55b97fe2016-01-28 05:22:45 -08001095 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001096 if (!codec_manager_.RegisterEncoder(codec) ||
1097 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1098 !RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec) ||
1099 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001100 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1101 "Channel::Init() failed to register CN (%d/%d) "
1102 "correctly - 1",
1103 codec.pltype, codec.plfreq);
1104 }
1105 }
kwiberg55b97fe2016-01-28 05:22:45 -08001106 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001107
kwiberg55b97fe2016-01-28 05:22:45 -08001108 if (rx_audioproc_->noise_suppression()->set_level(kDefaultNsMode) != 0) {
1109 LOG(LS_ERROR) << "noise_suppression()->set_level(kDefaultNsMode) failed.";
1110 return -1;
1111 }
1112 if (rx_audioproc_->gain_control()->set_mode(kDefaultRxAgcMode) != 0) {
1113 LOG(LS_ERROR) << "gain_control()->set_mode(kDefaultRxAgcMode) failed.";
1114 return -1;
1115 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001116
kwiberg55b97fe2016-01-28 05:22:45 -08001117 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001118}
1119
kwiberg55b97fe2016-01-28 05:22:45 -08001120int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1121 OutputMixer& outputMixer,
1122 voe::TransmitMixer& transmitMixer,
1123 ProcessThread& moduleProcessThread,
1124 AudioDeviceModule& audioDeviceModule,
1125 VoiceEngineObserver* voiceEngineObserver,
1126 rtc::CriticalSection* callbackCritSect) {
1127 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1128 "Channel::SetEngineInformation()");
1129 _engineStatisticsPtr = &engineStatistics;
1130 _outputMixerPtr = &outputMixer;
1131 _transmitMixerPtr = &transmitMixer,
1132 _moduleProcessThreadPtr = &moduleProcessThread;
1133 _audioDeviceModulePtr = &audioDeviceModule;
1134 _voiceEngineObserverPtr = voiceEngineObserver;
1135 _callbackCritSectPtr = callbackCritSect;
1136 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001137}
1138
kwiberg55b97fe2016-01-28 05:22:45 -08001139int32_t Channel::UpdateLocalTimeStamp() {
1140 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1141 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001142}
1143
kwibergb7f89d62016-02-17 10:04:18 -08001144void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001145 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001146 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001147}
1148
ossu29b1a8d2016-06-13 07:34:51 -07001149const rtc::scoped_refptr<AudioDecoderFactory>&
1150Channel::GetAudioDecoderFactory() const {
1151 return decoder_factory_;
1152}
1153
kwiberg55b97fe2016-01-28 05:22:45 -08001154int32_t Channel::StartPlayout() {
1155 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1156 "Channel::StartPlayout()");
1157 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001158 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001159 }
1160
1161 if (!_externalMixing) {
1162 // Add participant as candidates for mixing.
1163 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1164 _engineStatisticsPtr->SetLastError(
1165 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1166 "StartPlayout() failed to add participant to mixer");
1167 return -1;
1168 }
1169 }
1170
1171 channel_state_.SetPlaying(true);
1172 if (RegisterFilePlayingToMixer() != 0)
1173 return -1;
1174
1175 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001176}
1177
kwiberg55b97fe2016-01-28 05:22:45 -08001178int32_t Channel::StopPlayout() {
1179 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1180 "Channel::StopPlayout()");
1181 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001182 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001183 }
1184
1185 if (!_externalMixing) {
1186 // Remove participant as candidates for mixing
1187 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1188 _engineStatisticsPtr->SetLastError(
1189 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1190 "StopPlayout() failed to remove participant from mixer");
1191 return -1;
1192 }
1193 }
1194
1195 channel_state_.SetPlaying(false);
1196 _outputAudioLevel.Clear();
1197
1198 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001199}
1200
kwiberg55b97fe2016-01-28 05:22:45 -08001201int32_t Channel::StartSend() {
1202 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1203 "Channel::StartSend()");
1204 // Resume the previous sequence number which was reset by StopSend().
1205 // This needs to be done before |sending| is set to true.
1206 if (send_sequence_number_)
1207 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001208
kwiberg55b97fe2016-01-28 05:22:45 -08001209 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001210 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001211 }
1212 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001213
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001214 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001215 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1216 _engineStatisticsPtr->SetLastError(
1217 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1218 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001219 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001220 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001221 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001222 return -1;
1223 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001224
kwiberg55b97fe2016-01-28 05:22:45 -08001225 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001226}
1227
kwiberg55b97fe2016-01-28 05:22:45 -08001228int32_t Channel::StopSend() {
1229 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1230 "Channel::StopSend()");
1231 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001232 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001233 }
1234 channel_state_.SetSending(false);
1235
1236 // Store the sequence number to be able to pick up the same sequence for
1237 // the next StartSend(). This is needed for restarting device, otherwise
1238 // it might cause libSRTP to complain about packets being replayed.
1239 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1240 // CL is landed. See issue
1241 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1242 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1243
1244 // Reset sending SSRC and sequence number and triggers direct transmission
1245 // of RTCP BYE
1246 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1247 _engineStatisticsPtr->SetLastError(
1248 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1249 "StartSend() RTP/RTCP failed to stop sending");
1250 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001251 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001252
1253 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001254}
1255
kwiberg55b97fe2016-01-28 05:22:45 -08001256int32_t Channel::StartReceiving() {
1257 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1258 "Channel::StartReceiving()");
1259 if (channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001260 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001261 }
1262 channel_state_.SetReceiving(true);
1263 _numberOfDiscardedPackets = 0;
1264 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001265}
1266
kwiberg55b97fe2016-01-28 05:22:45 -08001267int32_t Channel::StopReceiving() {
1268 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1269 "Channel::StopReceiving()");
1270 if (!channel_state_.Get().receiving) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001271 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001272 }
1273
1274 channel_state_.SetReceiving(false);
1275 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001276}
1277
kwiberg55b97fe2016-01-28 05:22:45 -08001278int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1279 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1280 "Channel::RegisterVoiceEngineObserver()");
1281 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001282
kwiberg55b97fe2016-01-28 05:22:45 -08001283 if (_voiceEngineObserverPtr) {
1284 _engineStatisticsPtr->SetLastError(
1285 VE_INVALID_OPERATION, kTraceError,
1286 "RegisterVoiceEngineObserver() observer already enabled");
1287 return -1;
1288 }
1289 _voiceEngineObserverPtr = &observer;
1290 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001291}
1292
kwiberg55b97fe2016-01-28 05:22:45 -08001293int32_t Channel::DeRegisterVoiceEngineObserver() {
1294 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1295 "Channel::DeRegisterVoiceEngineObserver()");
1296 rtc::CritScope cs(&_callbackCritSect);
1297
1298 if (!_voiceEngineObserverPtr) {
1299 _engineStatisticsPtr->SetLastError(
1300 VE_INVALID_OPERATION, kTraceWarning,
1301 "DeRegisterVoiceEngineObserver() observer already disabled");
1302 return 0;
1303 }
1304 _voiceEngineObserverPtr = NULL;
1305 return 0;
1306}
1307
1308int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001309 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001310 if (send_codec) {
1311 codec = *send_codec;
1312 return 0;
1313 }
1314 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001315}
1316
kwiberg55b97fe2016-01-28 05:22:45 -08001317int32_t Channel::GetRecCodec(CodecInst& codec) {
1318 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001319}
1320
kwiberg55b97fe2016-01-28 05:22:45 -08001321int32_t Channel::SetSendCodec(const CodecInst& codec) {
1322 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1323 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001324
kwibergc8d071e2016-04-06 12:22:38 -07001325 if (!codec_manager_.RegisterEncoder(codec) ||
1326 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001327 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1328 "SetSendCodec() failed to register codec to ACM");
1329 return -1;
1330 }
1331
1332 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1333 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1334 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1335 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1336 "SetSendCodec() failed to register codec to"
1337 " RTP/RTCP module");
1338 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001339 }
kwiberg55b97fe2016-01-28 05:22:45 -08001340 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001341
kwiberg55b97fe2016-01-28 05:22:45 -08001342 if (_rtpRtcpModule->SetAudioPacketSize(codec.pacsize) != 0) {
1343 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1344 "SetSendCodec() failed to set audio packet size");
1345 return -1;
1346 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001347
kwiberg55b97fe2016-01-28 05:22:45 -08001348 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001349}
1350
Ivo Creusenadf89b72015-04-29 16:03:33 +02001351void Channel::SetBitRate(int bitrate_bps) {
1352 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1353 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
1354 audio_coding_->SetBitRate(bitrate_bps);
1355}
1356
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001357void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue@webrtc.org74aaf292014-07-16 21:28:26 +00001358 network_predictor_->UpdatePacketLossRate(fraction_lost);
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001359 uint8_t average_fraction_loss = network_predictor_->GetLossRate();
1360
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001361 // Normalizes rate to 0 - 100.
kwiberg55b97fe2016-01-28 05:22:45 -08001362 if (audio_coding_->SetPacketLossRate(100 * average_fraction_loss / 255) !=
1363 0) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001364 assert(false); // This should not happen.
1365 }
1366}
1367
kwiberg55b97fe2016-01-28 05:22:45 -08001368int32_t Channel::SetVADStatus(bool enableVAD,
1369 ACMVADMode mode,
1370 bool disableDTX) {
1371 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1372 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001373 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1374 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1375 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001376 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1377 kTraceError,
1378 "SetVADStatus() failed to set VAD");
1379 return -1;
1380 }
1381 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001382}
1383
kwiberg55b97fe2016-01-28 05:22:45 -08001384int32_t Channel::GetVADStatus(bool& enabledVAD,
1385 ACMVADMode& mode,
1386 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001387 const auto* params = codec_manager_.GetStackParams();
1388 enabledVAD = params->use_cng;
1389 mode = params->vad_mode;
1390 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001391 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001392}
1393
kwiberg55b97fe2016-01-28 05:22:45 -08001394int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1395 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1396 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001397
kwiberg55b97fe2016-01-28 05:22:45 -08001398 if (channel_state_.Get().playing) {
1399 _engineStatisticsPtr->SetLastError(
1400 VE_ALREADY_PLAYING, kTraceError,
1401 "SetRecPayloadType() unable to set PT while playing");
1402 return -1;
1403 }
1404 if (channel_state_.Get().receiving) {
1405 _engineStatisticsPtr->SetLastError(
1406 VE_ALREADY_LISTENING, kTraceError,
1407 "SetRecPayloadType() unable to set PT while listening");
1408 return -1;
1409 }
1410
1411 if (codec.pltype == -1) {
1412 // De-register the selected codec (RTP/RTCP module and ACM)
1413
1414 int8_t pltype(-1);
1415 CodecInst rxCodec = codec;
1416
1417 // Get payload type for the given codec
1418 rtp_payload_registry_->ReceivePayloadType(
1419 rxCodec.plname, rxCodec.plfreq, rxCodec.channels,
1420 (rxCodec.rate < 0) ? 0 : rxCodec.rate, &pltype);
1421 rxCodec.pltype = pltype;
1422
1423 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1424 _engineStatisticsPtr->SetLastError(
1425 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1426 "SetRecPayloadType() RTP/RTCP-module deregistration "
1427 "failed");
1428 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001429 }
kwiberg55b97fe2016-01-28 05:22:45 -08001430 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1431 _engineStatisticsPtr->SetLastError(
1432 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1433 "SetRecPayloadType() ACM deregistration failed - 1");
1434 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001435 }
kwiberg55b97fe2016-01-28 05:22:45 -08001436 return 0;
1437 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001438
kwiberg55b97fe2016-01-28 05:22:45 -08001439 if (rtp_receiver_->RegisterReceivePayload(
1440 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1441 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1442 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001443 // TODO(kwiberg): Retrying is probably not necessary, since
1444 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001445 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001446 if (rtp_receiver_->RegisterReceivePayload(
kwiberg55b97fe2016-01-28 05:22:45 -08001447 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1448 (codec.rate < 0) ? 0 : codec.rate) != 0) {
1449 _engineStatisticsPtr->SetLastError(
1450 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1451 "SetRecPayloadType() RTP/RTCP-module registration failed");
1452 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001453 }
kwiberg55b97fe2016-01-28 05:22:45 -08001454 }
kwibergc8d071e2016-04-06 12:22:38 -07001455 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001456 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergc8d071e2016-04-06 12:22:38 -07001457 if (!RegisterReceiveCodec(&audio_coding_, &rent_a_codec_, codec)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001458 _engineStatisticsPtr->SetLastError(
1459 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1460 "SetRecPayloadType() ACM registration failed - 1");
1461 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001462 }
kwiberg55b97fe2016-01-28 05:22:45 -08001463 }
1464 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001465}
1466
kwiberg55b97fe2016-01-28 05:22:45 -08001467int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1468 int8_t payloadType(-1);
1469 if (rtp_payload_registry_->ReceivePayloadType(
1470 codec.plname, codec.plfreq, codec.channels,
1471 (codec.rate < 0) ? 0 : codec.rate, &payloadType) != 0) {
1472 _engineStatisticsPtr->SetLastError(
1473 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1474 "GetRecPayloadType() failed to retrieve RX payload type");
1475 return -1;
1476 }
1477 codec.pltype = payloadType;
1478 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001479}
1480
kwiberg55b97fe2016-01-28 05:22:45 -08001481int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1482 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1483 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001484
kwiberg55b97fe2016-01-28 05:22:45 -08001485 CodecInst codec;
1486 int32_t samplingFreqHz(-1);
1487 const size_t kMono = 1;
1488 if (frequency == kFreq32000Hz)
1489 samplingFreqHz = 32000;
1490 else if (frequency == kFreq16000Hz)
1491 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001492
kwiberg55b97fe2016-01-28 05:22:45 -08001493 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1494 _engineStatisticsPtr->SetLastError(
1495 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1496 "SetSendCNPayloadType() failed to retrieve default CN codec "
1497 "settings");
1498 return -1;
1499 }
1500
1501 // Modify the payload type (must be set to dynamic range)
1502 codec.pltype = type;
1503
kwibergc8d071e2016-04-06 12:22:38 -07001504 if (!codec_manager_.RegisterEncoder(codec) ||
1505 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001506 _engineStatisticsPtr->SetLastError(
1507 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1508 "SetSendCNPayloadType() failed to register CN to ACM");
1509 return -1;
1510 }
1511
1512 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1513 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1514 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1515 _engineStatisticsPtr->SetLastError(
1516 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1517 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1518 "module");
1519 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001520 }
kwiberg55b97fe2016-01-28 05:22:45 -08001521 }
1522 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001523}
1524
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001525int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001526 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001527 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001528
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001529 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001530 _engineStatisticsPtr->SetLastError(
1531 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001532 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001533 return -1;
1534 }
1535 return 0;
1536}
1537
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001538int Channel::SetOpusDtx(bool enable_dtx) {
1539 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1540 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001541 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001542 : audio_coding_->DisableOpusDtx();
1543 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001544 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1545 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001546 return -1;
1547 }
1548 return 0;
1549}
1550
mflodman3d7db262016-04-29 00:57:13 -07001551int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001552 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001553 "Channel::RegisterExternalTransport()");
1554
kwiberg55b97fe2016-01-28 05:22:45 -08001555 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001556 if (_externalTransport) {
1557 _engineStatisticsPtr->SetLastError(
1558 VE_INVALID_OPERATION, kTraceError,
1559 "RegisterExternalTransport() external transport already enabled");
1560 return -1;
1561 }
1562 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001563 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001564 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001565}
1566
kwiberg55b97fe2016-01-28 05:22:45 -08001567int32_t Channel::DeRegisterExternalTransport() {
1568 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1569 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001570
kwiberg55b97fe2016-01-28 05:22:45 -08001571 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001572 if (_transportPtr) {
1573 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1574 "DeRegisterExternalTransport() all transport is disabled");
1575 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001576 _engineStatisticsPtr->SetLastError(
1577 VE_INVALID_OPERATION, kTraceWarning,
1578 "DeRegisterExternalTransport() external transport already "
1579 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001580 }
1581 _externalTransport = false;
1582 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001583 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001584}
1585
mflodman3d7db262016-04-29 00:57:13 -07001586int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001587 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001588 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001589 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001590 "Channel::ReceivedRTPPacket()");
1591
1592 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001593 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001594
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001595 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001596 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1597 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1598 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001599 return -1;
1600 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001601 header.payload_type_frequency =
1602 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001603 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001604 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001605 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001606 rtp_receive_statistics_->IncomingPacket(
1607 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001608 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001609
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001610 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001611}
1612
1613bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001614 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001615 const RTPHeader& header,
1616 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001617 if (rtp_payload_registry_->IsRtx(header)) {
1618 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001619 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001620 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001621 assert(packet_length >= header.headerLength);
1622 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001623 PayloadUnion payload_specific;
1624 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001625 &payload_specific)) {
1626 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001627 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001628 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1629 payload_specific, in_order);
1630}
1631
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001632bool Channel::HandleRtxPacket(const uint8_t* packet,
1633 size_t packet_length,
1634 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001635 if (!rtp_payload_registry_->IsRtx(header))
1636 return false;
1637
1638 // Remove the RTX header and parse the original RTP header.
1639 if (packet_length < header.headerLength)
1640 return false;
1641 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1642 return false;
1643 if (restored_packet_in_use_) {
1644 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1645 "Multiple RTX headers detected, dropping packet");
1646 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001647 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001648 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001649 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1650 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001651 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1652 "Incoming RTX packet: invalid RTP header");
1653 return false;
1654 }
1655 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001656 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001657 restored_packet_in_use_ = false;
1658 return ret;
1659}
1660
1661bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1662 StreamStatistician* statistician =
1663 rtp_receive_statistics_->GetStatistician(header.ssrc);
1664 if (!statistician)
1665 return false;
1666 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001667}
1668
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001669bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1670 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001671 // Retransmissions are handled separately if RTX is enabled.
1672 if (rtp_payload_registry_->RtxEnabled())
1673 return false;
1674 StreamStatistician* statistician =
1675 rtp_receive_statistics_->GetStatistician(header.ssrc);
1676 if (!statistician)
1677 return false;
1678 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001679 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001680 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001681 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001682}
1683
mflodman3d7db262016-04-29 00:57:13 -07001684int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001685 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001686 "Channel::ReceivedRTCPPacket()");
1687 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001688 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001689
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001690 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001691 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001692 _engineStatisticsPtr->SetLastError(
1693 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1694 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1695 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001696
Minyue2013aec2015-05-13 14:14:42 +02001697 int64_t rtt = GetRTT(true);
1698 if (rtt == 0) {
1699 // Waiting for valid RTT.
1700 return 0;
1701 }
1702 uint32_t ntp_secs = 0;
1703 uint32_t ntp_frac = 0;
1704 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001705 if (0 !=
1706 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1707 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001708 // Waiting for RTCP.
1709 return 0;
1710 }
1711
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001712 {
tommi31fc21f2016-01-21 10:37:37 -08001713 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001714 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001715 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001716 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001717}
1718
niklase@google.com470e71d2011-07-07 08:21:25 +00001719int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001720 bool loop,
1721 FileFormats format,
1722 int startPosition,
1723 float volumeScaling,
1724 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001725 const CodecInst* codecInst) {
1726 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1727 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1728 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1729 "stopPosition=%d)",
1730 fileName, loop, format, volumeScaling, startPosition,
1731 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001732
kwiberg55b97fe2016-01-28 05:22:45 -08001733 if (channel_state_.Get().output_file_playing) {
1734 _engineStatisticsPtr->SetLastError(
1735 VE_ALREADY_PLAYING, kTraceError,
1736 "StartPlayingFileLocally() is already playing");
1737 return -1;
1738 }
1739
1740 {
1741 rtc::CritScope cs(&_fileCritSect);
1742
1743 if (_outputFilePlayerPtr) {
1744 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1745 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1746 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001747 }
1748
kwiberg55b97fe2016-01-28 05:22:45 -08001749 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1750 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001751
kwiberg55b97fe2016-01-28 05:22:45 -08001752 if (_outputFilePlayerPtr == NULL) {
1753 _engineStatisticsPtr->SetLastError(
1754 VE_INVALID_ARGUMENT, kTraceError,
1755 "StartPlayingFileLocally() filePlayer format is not correct");
1756 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001757 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001758
kwiberg55b97fe2016-01-28 05:22:45 -08001759 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001760
kwiberg55b97fe2016-01-28 05:22:45 -08001761 if (_outputFilePlayerPtr->StartPlayingFile(
1762 fileName, loop, startPosition, volumeScaling, notificationTime,
1763 stopPosition, (const CodecInst*)codecInst) != 0) {
1764 _engineStatisticsPtr->SetLastError(
1765 VE_BAD_FILE, kTraceError,
1766 "StartPlayingFile() failed to start file playout");
1767 _outputFilePlayerPtr->StopPlayingFile();
1768 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1769 _outputFilePlayerPtr = NULL;
1770 return -1;
1771 }
1772 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1773 channel_state_.SetOutputFilePlaying(true);
1774 }
1775
1776 if (RegisterFilePlayingToMixer() != 0)
1777 return -1;
1778
1779 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001780}
1781
1782int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001783 FileFormats format,
1784 int startPosition,
1785 float volumeScaling,
1786 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001787 const CodecInst* codecInst) {
1788 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1789 "Channel::StartPlayingFileLocally(format=%d,"
1790 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1791 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001792
kwiberg55b97fe2016-01-28 05:22:45 -08001793 if (stream == NULL) {
1794 _engineStatisticsPtr->SetLastError(
1795 VE_BAD_FILE, kTraceError,
1796 "StartPlayingFileLocally() NULL as input stream");
1797 return -1;
1798 }
1799
1800 if (channel_state_.Get().output_file_playing) {
1801 _engineStatisticsPtr->SetLastError(
1802 VE_ALREADY_PLAYING, kTraceError,
1803 "StartPlayingFileLocally() is already playing");
1804 return -1;
1805 }
1806
1807 {
1808 rtc::CritScope cs(&_fileCritSect);
1809
1810 // Destroy the old instance
1811 if (_outputFilePlayerPtr) {
1812 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1813 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1814 _outputFilePlayerPtr = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +00001815 }
1816
kwiberg55b97fe2016-01-28 05:22:45 -08001817 // Create the instance
1818 _outputFilePlayerPtr = FilePlayer::CreateFilePlayer(
1819 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001820
kwiberg55b97fe2016-01-28 05:22:45 -08001821 if (_outputFilePlayerPtr == NULL) {
1822 _engineStatisticsPtr->SetLastError(
1823 VE_INVALID_ARGUMENT, kTraceError,
1824 "StartPlayingFileLocally() filePlayer format isnot correct");
1825 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001826 }
1827
kwiberg55b97fe2016-01-28 05:22:45 -08001828 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001829
kwiberg55b97fe2016-01-28 05:22:45 -08001830 if (_outputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
1831 volumeScaling, notificationTime,
1832 stopPosition, codecInst) != 0) {
1833 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1834 "StartPlayingFile() failed to "
1835 "start file playout");
1836 _outputFilePlayerPtr->StopPlayingFile();
1837 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1838 _outputFilePlayerPtr = NULL;
1839 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001840 }
kwiberg55b97fe2016-01-28 05:22:45 -08001841 _outputFilePlayerPtr->RegisterModuleFileCallback(this);
1842 channel_state_.SetOutputFilePlaying(true);
1843 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001844
kwiberg55b97fe2016-01-28 05:22:45 -08001845 if (RegisterFilePlayingToMixer() != 0)
1846 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001847
kwiberg55b97fe2016-01-28 05:22:45 -08001848 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001849}
1850
kwiberg55b97fe2016-01-28 05:22:45 -08001851int Channel::StopPlayingFileLocally() {
1852 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1853 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001854
kwiberg55b97fe2016-01-28 05:22:45 -08001855 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001856 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001857 }
1858
1859 {
1860 rtc::CritScope cs(&_fileCritSect);
1861
1862 if (_outputFilePlayerPtr->StopPlayingFile() != 0) {
1863 _engineStatisticsPtr->SetLastError(
1864 VE_STOP_RECORDING_FAILED, kTraceError,
1865 "StopPlayingFile() could not stop playing");
1866 return -1;
1867 }
1868 _outputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1869 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1870 _outputFilePlayerPtr = NULL;
1871 channel_state_.SetOutputFilePlaying(false);
1872 }
1873 // _fileCritSect cannot be taken while calling
1874 // SetAnonymousMixibilityStatus. Refer to comments in
1875 // StartPlayingFileLocally(const char* ...) for more details.
1876 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1877 _engineStatisticsPtr->SetLastError(
1878 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1879 "StopPlayingFile() failed to stop participant from playing as"
1880 "file in the mixer");
1881 return -1;
1882 }
1883
1884 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001885}
1886
kwiberg55b97fe2016-01-28 05:22:45 -08001887int Channel::IsPlayingFileLocally() const {
1888 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001889}
1890
kwiberg55b97fe2016-01-28 05:22:45 -08001891int Channel::RegisterFilePlayingToMixer() {
1892 // Return success for not registering for file playing to mixer if:
1893 // 1. playing file before playout is started on that channel.
1894 // 2. starting playout without file playing on that channel.
1895 if (!channel_state_.Get().playing ||
1896 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001897 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001898 }
1899
1900 // |_fileCritSect| cannot be taken while calling
1901 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1902 // frames can be pulled by the mixer. Since the frames are generated from
1903 // the file, _fileCritSect will be taken. This would result in a deadlock.
1904 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1905 channel_state_.SetOutputFilePlaying(false);
1906 rtc::CritScope cs(&_fileCritSect);
1907 _engineStatisticsPtr->SetLastError(
1908 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1909 "StartPlayingFile() failed to add participant as file to mixer");
1910 _outputFilePlayerPtr->StopPlayingFile();
1911 FilePlayer::DestroyFilePlayer(_outputFilePlayerPtr);
1912 _outputFilePlayerPtr = NULL;
1913 return -1;
1914 }
1915
1916 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001917}
1918
niklase@google.com470e71d2011-07-07 08:21:25 +00001919int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001920 bool loop,
1921 FileFormats format,
1922 int startPosition,
1923 float volumeScaling,
1924 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001925 const CodecInst* codecInst) {
1926 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1927 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1928 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1929 "stopPosition=%d)",
1930 fileName, loop, format, volumeScaling, startPosition,
1931 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001932
kwiberg55b97fe2016-01-28 05:22:45 -08001933 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001934
kwiberg55b97fe2016-01-28 05:22:45 -08001935 if (channel_state_.Get().input_file_playing) {
1936 _engineStatisticsPtr->SetLastError(
1937 VE_ALREADY_PLAYING, kTraceWarning,
1938 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001939 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001940 }
1941
1942 // Destroy the old instance
1943 if (_inputFilePlayerPtr) {
1944 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
1945 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1946 _inputFilePlayerPtr = NULL;
1947 }
1948
1949 // Create the instance
1950 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
1951 (const FileFormats)format);
1952
1953 if (_inputFilePlayerPtr == NULL) {
1954 _engineStatisticsPtr->SetLastError(
1955 VE_INVALID_ARGUMENT, kTraceError,
1956 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1957 return -1;
1958 }
1959
1960 const uint32_t notificationTime(0);
1961
1962 if (_inputFilePlayerPtr->StartPlayingFile(
1963 fileName, loop, startPosition, volumeScaling, notificationTime,
1964 stopPosition, (const CodecInst*)codecInst) != 0) {
1965 _engineStatisticsPtr->SetLastError(
1966 VE_BAD_FILE, kTraceError,
1967 "StartPlayingFile() failed to start file playout");
1968 _inputFilePlayerPtr->StopPlayingFile();
1969 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
1970 _inputFilePlayerPtr = NULL;
1971 return -1;
1972 }
1973 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
1974 channel_state_.SetInputFilePlaying(true);
1975
1976 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001977}
1978
1979int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001980 FileFormats format,
1981 int startPosition,
1982 float volumeScaling,
1983 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001984 const CodecInst* codecInst) {
1985 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1986 "Channel::StartPlayingFileAsMicrophone(format=%d, "
1987 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1988 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001989
kwiberg55b97fe2016-01-28 05:22:45 -08001990 if (stream == NULL) {
1991 _engineStatisticsPtr->SetLastError(
1992 VE_BAD_FILE, kTraceError,
1993 "StartPlayingFileAsMicrophone NULL as input stream");
1994 return -1;
1995 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001996
kwiberg55b97fe2016-01-28 05:22:45 -08001997 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001998
kwiberg55b97fe2016-01-28 05:22:45 -08001999 if (channel_state_.Get().input_file_playing) {
2000 _engineStatisticsPtr->SetLastError(
2001 VE_ALREADY_PLAYING, kTraceWarning,
2002 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002003 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002004 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002005
kwiberg55b97fe2016-01-28 05:22:45 -08002006 // Destroy the old instance
2007 if (_inputFilePlayerPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002008 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
2009 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
2010 _inputFilePlayerPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08002011 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002012
kwiberg55b97fe2016-01-28 05:22:45 -08002013 // Create the instance
2014 _inputFilePlayerPtr = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
2015 (const FileFormats)format);
2016
2017 if (_inputFilePlayerPtr == NULL) {
2018 _engineStatisticsPtr->SetLastError(
2019 VE_INVALID_ARGUMENT, kTraceError,
2020 "StartPlayingInputFile() filePlayer format isnot correct");
2021 return -1;
2022 }
2023
2024 const uint32_t notificationTime(0);
2025
2026 if (_inputFilePlayerPtr->StartPlayingFile(*stream, startPosition,
2027 volumeScaling, notificationTime,
2028 stopPosition, codecInst) != 0) {
2029 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2030 "StartPlayingFile() failed to start "
2031 "file playout");
2032 _inputFilePlayerPtr->StopPlayingFile();
2033 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
2034 _inputFilePlayerPtr = NULL;
2035 return -1;
2036 }
2037
2038 _inputFilePlayerPtr->RegisterModuleFileCallback(this);
2039 channel_state_.SetInputFilePlaying(true);
2040
2041 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002042}
2043
kwiberg55b97fe2016-01-28 05:22:45 -08002044int Channel::StopPlayingFileAsMicrophone() {
2045 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2046 "Channel::StopPlayingFileAsMicrophone()");
2047
2048 rtc::CritScope cs(&_fileCritSect);
2049
2050 if (!channel_state_.Get().input_file_playing) {
2051 return 0;
2052 }
2053
2054 if (_inputFilePlayerPtr->StopPlayingFile() != 0) {
2055 _engineStatisticsPtr->SetLastError(
2056 VE_STOP_RECORDING_FAILED, kTraceError,
2057 "StopPlayingFile() could not stop playing");
2058 return -1;
2059 }
2060 _inputFilePlayerPtr->RegisterModuleFileCallback(NULL);
2061 FilePlayer::DestroyFilePlayer(_inputFilePlayerPtr);
2062 _inputFilePlayerPtr = NULL;
2063 channel_state_.SetInputFilePlaying(false);
2064
2065 return 0;
2066}
2067
2068int Channel::IsPlayingFileAsMicrophone() const {
2069 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002070}
2071
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002072int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002073 const CodecInst* codecInst) {
2074 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2075 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002076
kwiberg55b97fe2016-01-28 05:22:45 -08002077 if (_outputFileRecording) {
2078 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2079 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002080 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002081 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002082
kwiberg55b97fe2016-01-28 05:22:45 -08002083 FileFormats format;
2084 const uint32_t notificationTime(0); // Not supported in VoE
2085 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002086
kwiberg55b97fe2016-01-28 05:22:45 -08002087 if ((codecInst != NULL) &&
2088 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2089 _engineStatisticsPtr->SetLastError(
2090 VE_BAD_ARGUMENT, kTraceError,
2091 "StartRecordingPlayout() invalid compression");
2092 return (-1);
2093 }
2094 if (codecInst == NULL) {
2095 format = kFileFormatPcm16kHzFile;
2096 codecInst = &dummyCodec;
2097 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2098 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2099 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2100 format = kFileFormatWavFile;
2101 } else {
2102 format = kFileFormatCompressedFile;
2103 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002104
kwiberg55b97fe2016-01-28 05:22:45 -08002105 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002106
kwiberg55b97fe2016-01-28 05:22:45 -08002107 // Destroy the old instance
2108 if (_outputFileRecorderPtr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002109 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2110 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2111 _outputFileRecorderPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08002112 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002113
kwiberg55b97fe2016-01-28 05:22:45 -08002114 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2115 _outputFileRecorderId, (const FileFormats)format);
2116 if (_outputFileRecorderPtr == NULL) {
2117 _engineStatisticsPtr->SetLastError(
2118 VE_INVALID_ARGUMENT, kTraceError,
2119 "StartRecordingPlayout() fileRecorder format isnot correct");
2120 return -1;
2121 }
2122
2123 if (_outputFileRecorderPtr->StartRecordingAudioFile(
2124 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2125 _engineStatisticsPtr->SetLastError(
2126 VE_BAD_FILE, kTraceError,
2127 "StartRecordingAudioFile() failed to start file recording");
2128 _outputFileRecorderPtr->StopRecording();
2129 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2130 _outputFileRecorderPtr = NULL;
2131 return -1;
2132 }
2133 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2134 _outputFileRecording = true;
2135
2136 return 0;
2137}
2138
2139int Channel::StartRecordingPlayout(OutStream* stream,
2140 const CodecInst* codecInst) {
2141 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2142 "Channel::StartRecordingPlayout()");
2143
2144 if (_outputFileRecording) {
2145 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2146 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002147 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002148 }
2149
2150 FileFormats format;
2151 const uint32_t notificationTime(0); // Not supported in VoE
2152 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2153
2154 if (codecInst != NULL && codecInst->channels != 1) {
2155 _engineStatisticsPtr->SetLastError(
2156 VE_BAD_ARGUMENT, kTraceError,
2157 "StartRecordingPlayout() invalid compression");
2158 return (-1);
2159 }
2160 if (codecInst == NULL) {
2161 format = kFileFormatPcm16kHzFile;
2162 codecInst = &dummyCodec;
2163 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2164 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2165 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2166 format = kFileFormatWavFile;
2167 } else {
2168 format = kFileFormatCompressedFile;
2169 }
2170
2171 rtc::CritScope cs(&_fileCritSect);
2172
2173 // Destroy the old instance
2174 if (_outputFileRecorderPtr) {
2175 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2176 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2177 _outputFileRecorderPtr = NULL;
2178 }
2179
2180 _outputFileRecorderPtr = FileRecorder::CreateFileRecorder(
2181 _outputFileRecorderId, (const FileFormats)format);
2182 if (_outputFileRecorderPtr == NULL) {
2183 _engineStatisticsPtr->SetLastError(
2184 VE_INVALID_ARGUMENT, kTraceError,
2185 "StartRecordingPlayout() fileRecorder format isnot correct");
2186 return -1;
2187 }
2188
2189 if (_outputFileRecorderPtr->StartRecordingAudioFile(*stream, *codecInst,
2190 notificationTime) != 0) {
2191 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2192 "StartRecordingPlayout() failed to "
2193 "start file recording");
2194 _outputFileRecorderPtr->StopRecording();
2195 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2196 _outputFileRecorderPtr = NULL;
2197 return -1;
2198 }
2199
2200 _outputFileRecorderPtr->RegisterModuleFileCallback(this);
2201 _outputFileRecording = true;
2202
2203 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002204}
2205
kwiberg55b97fe2016-01-28 05:22:45 -08002206int Channel::StopRecordingPlayout() {
2207 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2208 "Channel::StopRecordingPlayout()");
2209
2210 if (!_outputFileRecording) {
2211 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2212 "StopRecordingPlayout() isnot recording");
2213 return -1;
2214 }
2215
2216 rtc::CritScope cs(&_fileCritSect);
2217
2218 if (_outputFileRecorderPtr->StopRecording() != 0) {
2219 _engineStatisticsPtr->SetLastError(
2220 VE_STOP_RECORDING_FAILED, kTraceError,
2221 "StopRecording() could not stop recording");
2222 return (-1);
2223 }
2224 _outputFileRecorderPtr->RegisterModuleFileCallback(NULL);
2225 FileRecorder::DestroyFileRecorder(_outputFileRecorderPtr);
2226 _outputFileRecorderPtr = NULL;
2227 _outputFileRecording = false;
2228
2229 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002230}
2231
kwiberg55b97fe2016-01-28 05:22:45 -08002232void Channel::SetMixWithMicStatus(bool mix) {
2233 rtc::CritScope cs(&_fileCritSect);
2234 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002235}
2236
kwiberg55b97fe2016-01-28 05:22:45 -08002237int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2238 int8_t currentLevel = _outputAudioLevel.Level();
2239 level = static_cast<int32_t>(currentLevel);
2240 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002241}
2242
kwiberg55b97fe2016-01-28 05:22:45 -08002243int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2244 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2245 level = static_cast<int32_t>(currentLevel);
2246 return 0;
2247}
2248
solenberg1c2af8e2016-03-24 10:36:00 -07002249int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002250 rtc::CritScope cs(&volume_settings_critsect_);
2251 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002252 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002253 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002254 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002255}
2256
solenberg1c2af8e2016-03-24 10:36:00 -07002257bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002258 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002259 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002260}
2261
kwiberg55b97fe2016-01-28 05:22:45 -08002262int Channel::SetOutputVolumePan(float left, float right) {
2263 rtc::CritScope cs(&volume_settings_critsect_);
2264 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002265 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002266 _panLeft = left;
2267 _panRight = right;
2268 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002269}
2270
kwiberg55b97fe2016-01-28 05:22:45 -08002271int Channel::GetOutputVolumePan(float& left, float& right) const {
2272 rtc::CritScope cs(&volume_settings_critsect_);
2273 left = _panLeft;
2274 right = _panRight;
2275 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002276}
2277
kwiberg55b97fe2016-01-28 05:22:45 -08002278int Channel::SetChannelOutputVolumeScaling(float scaling) {
2279 rtc::CritScope cs(&volume_settings_critsect_);
2280 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002281 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002282 _outputGain = scaling;
2283 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002284}
2285
kwiberg55b97fe2016-01-28 05:22:45 -08002286int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2287 rtc::CritScope cs(&volume_settings_critsect_);
2288 scaling = _outputGain;
2289 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002290}
2291
solenberg8842c3e2016-03-11 03:06:41 -08002292int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002293 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002294 "Channel::SendTelephoneEventOutband(...)");
2295 RTC_DCHECK_LE(0, event);
2296 RTC_DCHECK_GE(255, event);
2297 RTC_DCHECK_LE(0, duration_ms);
2298 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002299 if (!Sending()) {
2300 return -1;
2301 }
solenberg8842c3e2016-03-11 03:06:41 -08002302 if (_rtpRtcpModule->SendTelephoneEventOutband(
2303 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002304 _engineStatisticsPtr->SetLastError(
2305 VE_SEND_DTMF_FAILED, kTraceWarning,
2306 "SendTelephoneEventOutband() failed to send event");
2307 return -1;
2308 }
2309 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002310}
2311
solenberg31642aa2016-03-14 08:00:37 -07002312int Channel::SetSendTelephoneEventPayloadType(int payload_type) {
kwiberg55b97fe2016-01-28 05:22:45 -08002313 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002314 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002315 RTC_DCHECK_LE(0, payload_type);
2316 RTC_DCHECK_GE(127, payload_type);
2317 CodecInst codec = {0};
kwiberg55b97fe2016-01-28 05:22:45 -08002318 codec.plfreq = 8000;
solenberg31642aa2016-03-14 08:00:37 -07002319 codec.pltype = payload_type;
kwiberg55b97fe2016-01-28 05:22:45 -08002320 memcpy(codec.plname, "telephone-event", 16);
2321 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2322 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2323 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2324 _engineStatisticsPtr->SetLastError(
2325 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2326 "SetSendTelephoneEventPayloadType() failed to register send"
2327 "payload type");
2328 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002329 }
kwiberg55b97fe2016-01-28 05:22:45 -08002330 }
kwiberg55b97fe2016-01-28 05:22:45 -08002331 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002332}
2333
kwiberg55b97fe2016-01-28 05:22:45 -08002334int Channel::UpdateRxVadDetection(AudioFrame& audioFrame) {
2335 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2336 "Channel::UpdateRxVadDetection()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002337
kwiberg55b97fe2016-01-28 05:22:45 -08002338 int vadDecision = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002339
kwiberg55b97fe2016-01-28 05:22:45 -08002340 vadDecision = (audioFrame.vad_activity_ == AudioFrame::kVadActive) ? 1 : 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002341
kwiberg55b97fe2016-01-28 05:22:45 -08002342 if ((vadDecision != _oldVadDecision) && _rxVadObserverPtr) {
2343 OnRxVadDetected(vadDecision);
2344 _oldVadDecision = vadDecision;
2345 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002346
kwiberg55b97fe2016-01-28 05:22:45 -08002347 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2348 "Channel::UpdateRxVadDetection() => vadDecision=%d",
2349 vadDecision);
2350 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002351}
2352
kwiberg55b97fe2016-01-28 05:22:45 -08002353int Channel::RegisterRxVadObserver(VoERxVadCallback& observer) {
2354 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2355 "Channel::RegisterRxVadObserver()");
2356 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002357
kwiberg55b97fe2016-01-28 05:22:45 -08002358 if (_rxVadObserverPtr) {
2359 _engineStatisticsPtr->SetLastError(
2360 VE_INVALID_OPERATION, kTraceError,
2361 "RegisterRxVadObserver() observer already enabled");
2362 return -1;
2363 }
2364 _rxVadObserverPtr = &observer;
2365 _RxVadDetection = true;
2366 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002367}
2368
kwiberg55b97fe2016-01-28 05:22:45 -08002369int Channel::DeRegisterRxVadObserver() {
2370 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2371 "Channel::DeRegisterRxVadObserver()");
2372 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002373
kwiberg55b97fe2016-01-28 05:22:45 -08002374 if (!_rxVadObserverPtr) {
2375 _engineStatisticsPtr->SetLastError(
2376 VE_INVALID_OPERATION, kTraceWarning,
2377 "DeRegisterRxVadObserver() observer already disabled");
niklase@google.com470e71d2011-07-07 08:21:25 +00002378 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002379 }
2380 _rxVadObserverPtr = NULL;
2381 _RxVadDetection = false;
2382 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002383}
2384
kwiberg55b97fe2016-01-28 05:22:45 -08002385int Channel::VoiceActivityIndicator(int& activity) {
2386 activity = _sendFrameType;
2387 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002388}
2389
2390#ifdef WEBRTC_VOICE_ENGINE_AGC
2391
kwiberg55b97fe2016-01-28 05:22:45 -08002392int Channel::SetRxAgcStatus(bool enable, AgcModes mode) {
2393 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2394 "Channel::SetRxAgcStatus(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 GainControl::Mode agcMode = kDefaultRxAgcMode;
2398 switch (mode) {
2399 case kAgcDefault:
2400 break;
2401 case kAgcUnchanged:
2402 agcMode = rx_audioproc_->gain_control()->mode();
2403 break;
2404 case kAgcFixedDigital:
2405 agcMode = GainControl::kFixedDigital;
2406 break;
2407 case kAgcAdaptiveDigital:
2408 agcMode = GainControl::kAdaptiveDigital;
2409 break;
2410 default:
2411 _engineStatisticsPtr->SetLastError(VE_INVALID_ARGUMENT, kTraceError,
2412 "SetRxAgcStatus() invalid Agc mode");
2413 return -1;
2414 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002415
kwiberg55b97fe2016-01-28 05:22:45 -08002416 if (rx_audioproc_->gain_control()->set_mode(agcMode) != 0) {
2417 _engineStatisticsPtr->SetLastError(
2418 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc mode");
2419 return -1;
2420 }
2421 if (rx_audioproc_->gain_control()->Enable(enable) != 0) {
2422 _engineStatisticsPtr->SetLastError(
2423 VE_APM_ERROR, kTraceError, "SetRxAgcStatus() failed to set Agc state");
2424 return -1;
2425 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002426
kwiberg55b97fe2016-01-28 05:22:45 -08002427 _rxAgcIsEnabled = enable;
2428 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002429
kwiberg55b97fe2016-01-28 05:22:45 -08002430 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002431}
2432
kwiberg55b97fe2016-01-28 05:22:45 -08002433int Channel::GetRxAgcStatus(bool& enabled, AgcModes& mode) {
2434 bool enable = rx_audioproc_->gain_control()->is_enabled();
2435 GainControl::Mode agcMode = rx_audioproc_->gain_control()->mode();
niklase@google.com470e71d2011-07-07 08:21:25 +00002436
kwiberg55b97fe2016-01-28 05:22:45 -08002437 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002438
kwiberg55b97fe2016-01-28 05:22:45 -08002439 switch (agcMode) {
2440 case GainControl::kFixedDigital:
2441 mode = kAgcFixedDigital;
2442 break;
2443 case GainControl::kAdaptiveDigital:
2444 mode = kAgcAdaptiveDigital;
2445 break;
2446 default:
2447 _engineStatisticsPtr->SetLastError(VE_APM_ERROR, kTraceError,
2448 "GetRxAgcStatus() invalid Agc mode");
2449 return -1;
2450 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002451
kwiberg55b97fe2016-01-28 05:22:45 -08002452 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002453}
2454
kwiberg55b97fe2016-01-28 05:22:45 -08002455int Channel::SetRxAgcConfig(AgcConfig config) {
2456 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2457 "Channel::SetRxAgcConfig()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002458
kwiberg55b97fe2016-01-28 05:22:45 -08002459 if (rx_audioproc_->gain_control()->set_target_level_dbfs(
2460 config.targetLeveldBOv) != 0) {
2461 _engineStatisticsPtr->SetLastError(
2462 VE_APM_ERROR, kTraceError,
2463 "SetRxAgcConfig() failed to set target peak |level|"
2464 "(or envelope) of the Agc");
2465 return -1;
2466 }
2467 if (rx_audioproc_->gain_control()->set_compression_gain_db(
2468 config.digitalCompressionGaindB) != 0) {
2469 _engineStatisticsPtr->SetLastError(
2470 VE_APM_ERROR, kTraceError,
2471 "SetRxAgcConfig() failed to set the range in |gain| the"
2472 " digital compression stage may apply");
2473 return -1;
2474 }
2475 if (rx_audioproc_->gain_control()->enable_limiter(config.limiterEnable) !=
2476 0) {
2477 _engineStatisticsPtr->SetLastError(
2478 VE_APM_ERROR, kTraceError,
2479 "SetRxAgcConfig() failed to set hard limiter to the signal");
2480 return -1;
2481 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002482
kwiberg55b97fe2016-01-28 05:22:45 -08002483 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002484}
2485
kwiberg55b97fe2016-01-28 05:22:45 -08002486int Channel::GetRxAgcConfig(AgcConfig& config) {
2487 config.targetLeveldBOv = rx_audioproc_->gain_control()->target_level_dbfs();
2488 config.digitalCompressionGaindB =
2489 rx_audioproc_->gain_control()->compression_gain_db();
2490 config.limiterEnable = rx_audioproc_->gain_control()->is_limiter_enabled();
niklase@google.com470e71d2011-07-07 08:21:25 +00002491
kwiberg55b97fe2016-01-28 05:22:45 -08002492 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002493}
2494
kwiberg55b97fe2016-01-28 05:22:45 -08002495#endif // #ifdef WEBRTC_VOICE_ENGINE_AGC
niklase@google.com470e71d2011-07-07 08:21:25 +00002496
2497#ifdef WEBRTC_VOICE_ENGINE_NR
2498
kwiberg55b97fe2016-01-28 05:22:45 -08002499int Channel::SetRxNsStatus(bool enable, NsModes mode) {
2500 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2501 "Channel::SetRxNsStatus(enable=%d, mode=%d)", (int)enable,
2502 (int)mode);
niklase@google.com470e71d2011-07-07 08:21:25 +00002503
kwiberg55b97fe2016-01-28 05:22:45 -08002504 NoiseSuppression::Level nsLevel = kDefaultNsMode;
2505 switch (mode) {
2506 case kNsDefault:
2507 break;
2508 case kNsUnchanged:
2509 nsLevel = rx_audioproc_->noise_suppression()->level();
2510 break;
2511 case kNsConference:
2512 nsLevel = NoiseSuppression::kHigh;
2513 break;
2514 case kNsLowSuppression:
2515 nsLevel = NoiseSuppression::kLow;
2516 break;
2517 case kNsModerateSuppression:
2518 nsLevel = NoiseSuppression::kModerate;
2519 break;
2520 case kNsHighSuppression:
2521 nsLevel = NoiseSuppression::kHigh;
2522 break;
2523 case kNsVeryHighSuppression:
2524 nsLevel = NoiseSuppression::kVeryHigh;
2525 break;
2526 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002527
kwiberg55b97fe2016-01-28 05:22:45 -08002528 if (rx_audioproc_->noise_suppression()->set_level(nsLevel) != 0) {
2529 _engineStatisticsPtr->SetLastError(
2530 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS level");
2531 return -1;
2532 }
2533 if (rx_audioproc_->noise_suppression()->Enable(enable) != 0) {
2534 _engineStatisticsPtr->SetLastError(
2535 VE_APM_ERROR, kTraceError, "SetRxNsStatus() failed to set NS state");
2536 return -1;
2537 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002538
kwiberg55b97fe2016-01-28 05:22:45 -08002539 _rxNsIsEnabled = enable;
2540 channel_state_.SetRxApmIsEnabled(_rxAgcIsEnabled || _rxNsIsEnabled);
niklase@google.com470e71d2011-07-07 08:21:25 +00002541
kwiberg55b97fe2016-01-28 05:22:45 -08002542 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002543}
2544
kwiberg55b97fe2016-01-28 05:22:45 -08002545int Channel::GetRxNsStatus(bool& enabled, NsModes& mode) {
2546 bool enable = rx_audioproc_->noise_suppression()->is_enabled();
2547 NoiseSuppression::Level ncLevel = rx_audioproc_->noise_suppression()->level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002548
kwiberg55b97fe2016-01-28 05:22:45 -08002549 enabled = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002550
kwiberg55b97fe2016-01-28 05:22:45 -08002551 switch (ncLevel) {
2552 case NoiseSuppression::kLow:
2553 mode = kNsLowSuppression;
2554 break;
2555 case NoiseSuppression::kModerate:
2556 mode = kNsModerateSuppression;
2557 break;
2558 case NoiseSuppression::kHigh:
2559 mode = kNsHighSuppression;
2560 break;
2561 case NoiseSuppression::kVeryHigh:
2562 mode = kNsVeryHighSuppression;
2563 break;
2564 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002565
kwiberg55b97fe2016-01-28 05:22:45 -08002566 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002567}
2568
kwiberg55b97fe2016-01-28 05:22:45 -08002569#endif // #ifdef WEBRTC_VOICE_ENGINE_NR
niklase@google.com470e71d2011-07-07 08:21:25 +00002570
kwiberg55b97fe2016-01-28 05:22:45 -08002571int Channel::SetLocalSSRC(unsigned int ssrc) {
2572 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2573 "Channel::SetLocalSSRC()");
2574 if (channel_state_.Get().sending) {
2575 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2576 "SetLocalSSRC() already sending");
2577 return -1;
2578 }
2579 _rtpRtcpModule->SetSSRC(ssrc);
2580 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002581}
2582
kwiberg55b97fe2016-01-28 05:22:45 -08002583int Channel::GetLocalSSRC(unsigned int& ssrc) {
2584 ssrc = _rtpRtcpModule->SSRC();
2585 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002586}
2587
kwiberg55b97fe2016-01-28 05:22:45 -08002588int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2589 ssrc = rtp_receiver_->SSRC();
2590 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002591}
2592
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002593int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002594 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002595 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002596}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002597
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002598int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2599 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002600 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2601 if (enable &&
2602 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2603 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002604 return -1;
2605 }
2606 return 0;
2607}
2608
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002609int Channel::SetSendAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2610 return SetSendRtpHeaderExtension(enable, kRtpExtensionAbsoluteSendTime, id);
2611}
2612
2613int Channel::SetReceiveAbsoluteSenderTimeStatus(bool enable, unsigned char id) {
2614 rtp_header_parser_->DeregisterRtpHeaderExtension(
2615 kRtpExtensionAbsoluteSendTime);
kwiberg55b97fe2016-01-28 05:22:45 -08002616 if (enable &&
2617 !rtp_header_parser_->RegisterRtpHeaderExtension(
2618 kRtpExtensionAbsoluteSendTime, id)) {
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00002619 return -1;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002620 }
2621 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002622}
2623
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002624void Channel::EnableSendTransportSequenceNumber(int id) {
2625 int ret =
2626 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2627 RTC_DCHECK_EQ(0, ret);
2628}
2629
stefan3313ec92016-01-21 06:32:43 -08002630void Channel::EnableReceiveTransportSequenceNumber(int id) {
2631 rtp_header_parser_->DeregisterRtpHeaderExtension(
2632 kRtpExtensionTransportSequenceNumber);
2633 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2634 kRtpExtensionTransportSequenceNumber, id);
2635 RTC_DCHECK(ret);
2636}
2637
stefanbba9dec2016-02-01 04:39:55 -08002638void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002639 RtpPacketSender* rtp_packet_sender,
2640 TransportFeedbackObserver* transport_feedback_observer,
2641 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002642 RTC_DCHECK(rtp_packet_sender);
2643 RTC_DCHECK(transport_feedback_observer);
2644 RTC_DCHECK(packet_router && !packet_router_);
2645 feedback_observer_proxy_->SetTransportFeedbackObserver(
2646 transport_feedback_observer);
2647 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2648 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2649 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002650 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002651 packet_router_ = packet_router;
2652}
2653
stefanbba9dec2016-02-01 04:39:55 -08002654void Channel::RegisterReceiverCongestionControlObjects(
2655 PacketRouter* packet_router) {
2656 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002657 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002658 packet_router_ = packet_router;
2659}
2660
2661void Channel::ResetCongestionControlObjects() {
2662 RTC_DCHECK(packet_router_);
2663 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2664 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2665 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002666 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002667 packet_router_ = nullptr;
2668 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2669}
2670
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002671void Channel::SetRTCPStatus(bool enable) {
2672 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2673 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002674 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002675}
2676
kwiberg55b97fe2016-01-28 05:22:45 -08002677int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002678 RtcpMode method = _rtpRtcpModule->RTCP();
2679 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002680 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002681}
2682
kwiberg55b97fe2016-01-28 05:22:45 -08002683int Channel::SetRTCP_CNAME(const char cName[256]) {
2684 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2685 "Channel::SetRTCP_CNAME()");
2686 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2687 _engineStatisticsPtr->SetLastError(
2688 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2689 "SetRTCP_CNAME() failed to set RTCP CNAME");
2690 return -1;
2691 }
2692 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002693}
2694
kwiberg55b97fe2016-01-28 05:22:45 -08002695int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2696 if (cName == NULL) {
2697 _engineStatisticsPtr->SetLastError(
2698 VE_INVALID_ARGUMENT, kTraceError,
2699 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2700 return -1;
2701 }
2702 char cname[RTCP_CNAME_SIZE];
2703 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2704 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2705 _engineStatisticsPtr->SetLastError(
2706 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2707 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2708 return -1;
2709 }
2710 strcpy(cName, cname);
2711 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002712}
2713
kwiberg55b97fe2016-01-28 05:22:45 -08002714int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2715 unsigned int& NTPLow,
2716 unsigned int& timestamp,
2717 unsigned int& playoutTimestamp,
2718 unsigned int* jitter,
2719 unsigned short* fractionLost) {
2720 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002721
kwiberg55b97fe2016-01-28 05:22:45 -08002722 RTCPSenderInfo senderInfo;
2723 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2724 _engineStatisticsPtr->SetLastError(
2725 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2726 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2727 "side");
2728 return -1;
2729 }
2730
2731 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2732 // and octet count)
2733 NTPHigh = senderInfo.NTPseconds;
2734 NTPLow = senderInfo.NTPfraction;
2735 timestamp = senderInfo.RTPtimeStamp;
2736
2737 // --- Locally derived information
2738
2739 // This value is updated on each incoming RTCP packet (0 when no packet
2740 // has been received)
2741 playoutTimestamp = playout_timestamp_rtcp_;
2742
2743 if (NULL != jitter || NULL != fractionLost) {
2744 // Get all RTCP receiver report blocks that have been received on this
2745 // channel. If we receive RTP packets from a remote source we know the
2746 // remote SSRC and use the report block from him.
2747 // Otherwise use the first report block.
2748 std::vector<RTCPReportBlock> remote_stats;
2749 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2750 remote_stats.empty()) {
2751 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2752 "GetRemoteRTCPData() failed to measure statistics due"
2753 " to lack of received RTP and/or RTCP packets");
2754 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002755 }
2756
kwiberg55b97fe2016-01-28 05:22:45 -08002757 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2758 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2759 for (; it != remote_stats.end(); ++it) {
2760 if (it->remoteSSRC == remoteSSRC)
2761 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002762 }
kwiberg55b97fe2016-01-28 05:22:45 -08002763
2764 if (it == remote_stats.end()) {
2765 // If we have not received any RTCP packets from this SSRC it probably
2766 // means that we have not received any RTP packets.
2767 // Use the first received report block instead.
2768 it = remote_stats.begin();
2769 remoteSSRC = it->remoteSSRC;
2770 }
2771
2772 if (jitter) {
2773 *jitter = it->jitter;
2774 }
2775
2776 if (fractionLost) {
2777 *fractionLost = it->fractionLost;
2778 }
2779 }
2780 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002781}
2782
kwiberg55b97fe2016-01-28 05:22:45 -08002783int Channel::SendApplicationDefinedRTCPPacket(
2784 unsigned char subType,
2785 unsigned int name,
2786 const char* data,
2787 unsigned short dataLengthInBytes) {
2788 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2789 "Channel::SendApplicationDefinedRTCPPacket()");
2790 if (!channel_state_.Get().sending) {
2791 _engineStatisticsPtr->SetLastError(
2792 VE_NOT_SENDING, kTraceError,
2793 "SendApplicationDefinedRTCPPacket() not sending");
2794 return -1;
2795 }
2796 if (NULL == data) {
2797 _engineStatisticsPtr->SetLastError(
2798 VE_INVALID_ARGUMENT, kTraceError,
2799 "SendApplicationDefinedRTCPPacket() invalid data value");
2800 return -1;
2801 }
2802 if (dataLengthInBytes % 4 != 0) {
2803 _engineStatisticsPtr->SetLastError(
2804 VE_INVALID_ARGUMENT, kTraceError,
2805 "SendApplicationDefinedRTCPPacket() invalid length value");
2806 return -1;
2807 }
2808 RtcpMode status = _rtpRtcpModule->RTCP();
2809 if (status == RtcpMode::kOff) {
2810 _engineStatisticsPtr->SetLastError(
2811 VE_RTCP_ERROR, kTraceError,
2812 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2813 return -1;
2814 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002815
kwiberg55b97fe2016-01-28 05:22:45 -08002816 // Create and schedule the RTCP APP packet for transmission
2817 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2818 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2819 _engineStatisticsPtr->SetLastError(
2820 VE_SEND_ERROR, kTraceError,
2821 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2822 return -1;
2823 }
2824 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002825}
2826
kwiberg55b97fe2016-01-28 05:22:45 -08002827int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2828 unsigned int& maxJitterMs,
2829 unsigned int& discardedPackets) {
2830 // The jitter statistics is updated for each received RTP packet and is
2831 // based on received packets.
2832 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2833 // If RTCP is off, there is no timed thread in the RTCP module regularly
2834 // generating new stats, trigger the update manually here instead.
2835 StreamStatistician* statistician =
2836 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2837 if (statistician) {
2838 // Don't use returned statistics, use data from proxy instead so that
2839 // max jitter can be fetched atomically.
2840 RtcpStatistics s;
2841 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002842 }
kwiberg55b97fe2016-01-28 05:22:45 -08002843 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002844
kwiberg55b97fe2016-01-28 05:22:45 -08002845 ChannelStatistics stats = statistics_proxy_->GetStats();
2846 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2847 if (playoutFrequency > 0) {
2848 // Scale RTP statistics given the current playout frequency
2849 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2850 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2851 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002852
kwiberg55b97fe2016-01-28 05:22:45 -08002853 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002854
kwiberg55b97fe2016-01-28 05:22:45 -08002855 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002856}
2857
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002858int Channel::GetRemoteRTCPReportBlocks(
2859 std::vector<ReportBlock>* report_blocks) {
2860 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002861 _engineStatisticsPtr->SetLastError(
2862 VE_INVALID_ARGUMENT, kTraceError,
2863 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002864 return -1;
2865 }
2866
2867 // Get the report blocks from the latest received RTCP Sender or Receiver
2868 // Report. Each element in the vector contains the sender's SSRC and a
2869 // report block according to RFC 3550.
2870 std::vector<RTCPReportBlock> rtcp_report_blocks;
2871 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002872 return -1;
2873 }
2874
2875 if (rtcp_report_blocks.empty())
2876 return 0;
2877
2878 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2879 for (; it != rtcp_report_blocks.end(); ++it) {
2880 ReportBlock report_block;
2881 report_block.sender_SSRC = it->remoteSSRC;
2882 report_block.source_SSRC = it->sourceSSRC;
2883 report_block.fraction_lost = it->fractionLost;
2884 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2885 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2886 report_block.interarrival_jitter = it->jitter;
2887 report_block.last_SR_timestamp = it->lastSR;
2888 report_block.delay_since_last_SR = it->delaySinceLastSR;
2889 report_blocks->push_back(report_block);
2890 }
2891 return 0;
2892}
2893
kwiberg55b97fe2016-01-28 05:22:45 -08002894int Channel::GetRTPStatistics(CallStatistics& stats) {
2895 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002896
kwiberg55b97fe2016-01-28 05:22:45 -08002897 // The jitter statistics is updated for each received RTP packet and is
2898 // based on received packets.
2899 RtcpStatistics statistics;
2900 StreamStatistician* statistician =
2901 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002902 if (statistician) {
2903 statistician->GetStatistics(&statistics,
2904 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002905 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002906
kwiberg55b97fe2016-01-28 05:22:45 -08002907 stats.fractionLost = statistics.fraction_lost;
2908 stats.cumulativeLost = statistics.cumulative_lost;
2909 stats.extendedMax = statistics.extended_max_sequence_number;
2910 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002911
kwiberg55b97fe2016-01-28 05:22:45 -08002912 // --- RTT
2913 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002914
kwiberg55b97fe2016-01-28 05:22:45 -08002915 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002916
kwiberg55b97fe2016-01-28 05:22:45 -08002917 size_t bytesSent(0);
2918 uint32_t packetsSent(0);
2919 size_t bytesReceived(0);
2920 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002921
kwiberg55b97fe2016-01-28 05:22:45 -08002922 if (statistician) {
2923 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2924 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002925
kwiberg55b97fe2016-01-28 05:22:45 -08002926 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2927 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2928 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2929 " output will not be complete");
2930 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002931
kwiberg55b97fe2016-01-28 05:22:45 -08002932 stats.bytesSent = bytesSent;
2933 stats.packetsSent = packetsSent;
2934 stats.bytesReceived = bytesReceived;
2935 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002936
kwiberg55b97fe2016-01-28 05:22:45 -08002937 // --- Timestamps
2938 {
2939 rtc::CritScope lock(&ts_stats_lock_);
2940 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2941 }
2942 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002943}
2944
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002945int Channel::SetCodecFECStatus(bool enable) {
2946 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2947 "Channel::SetCodecFECStatus()");
2948
kwibergc8d071e2016-04-06 12:22:38 -07002949 if (!codec_manager_.SetCodecFEC(enable) ||
2950 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002951 _engineStatisticsPtr->SetLastError(
2952 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2953 "SetCodecFECStatus() failed to set FEC state");
2954 return -1;
2955 }
2956 return 0;
2957}
2958
2959bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002960 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002961}
2962
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002963void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2964 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002965 // If pacing is enabled we always store packets.
2966 if (!pacing_enabled_)
2967 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002968 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002969 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002970 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002971 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002972 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002973}
2974
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002975// Called when we are missing one or more packets.
2976int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002977 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2978}
2979
kwiberg55b97fe2016-01-28 05:22:45 -08002980uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2981 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2982 "Channel::Demultiplex()");
2983 _audioFrame.CopyFrom(audioFrame);
2984 _audioFrame.id_ = _channelId;
2985 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002986}
2987
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002988void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002989 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002990 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002991 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002992 CodecInst codec;
2993 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002994
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002995 // Never upsample or upmix the capture signal here. This should be done at the
2996 // end of the send chain.
2997 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2998 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2999 RemixAndResample(audio_data, number_of_frames, number_of_channels,
3000 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00003001}
3002
kwiberg55b97fe2016-01-28 05:22:45 -08003003uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
3004 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
3005 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003006
kwiberg55b97fe2016-01-28 05:22:45 -08003007 if (_audioFrame.samples_per_channel_ == 0) {
3008 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3009 "Channel::PrepareEncodeAndSend() invalid audio frame");
3010 return 0xFFFFFFFF;
3011 }
3012
3013 if (channel_state_.Get().input_file_playing) {
3014 MixOrReplaceAudioWithFile(mixingFrequency);
3015 }
3016
solenberg1c2af8e2016-03-24 10:36:00 -07003017 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
3018 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08003019
3020 if (channel_state_.Get().input_external_media) {
3021 rtc::CritScope cs(&_callbackCritSect);
3022 const bool isStereo = (_audioFrame.num_channels_ == 2);
3023 if (_inputExternalMediaCallbackPtr) {
3024 _inputExternalMediaCallbackPtr->Process(
3025 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
3026 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
3027 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00003028 }
kwiberg55b97fe2016-01-28 05:22:45 -08003029 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003030
kwiberg55b97fe2016-01-28 05:22:45 -08003031 if (_includeAudioLevelIndication) {
3032 size_t length =
3033 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02003034 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07003035 if (is_muted && previous_frame_muted_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003036 rms_level_.ProcessMuted(length);
3037 } else {
3038 rms_level_.Process(_audioFrame.data_, length);
niklase@google.com470e71d2011-07-07 08:21:25 +00003039 }
kwiberg55b97fe2016-01-28 05:22:45 -08003040 }
solenberg1c2af8e2016-03-24 10:36:00 -07003041 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00003042
kwiberg55b97fe2016-01-28 05:22:45 -08003043 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003044}
3045
kwiberg55b97fe2016-01-28 05:22:45 -08003046uint32_t Channel::EncodeAndSend() {
3047 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
3048 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003049
kwiberg55b97fe2016-01-28 05:22:45 -08003050 assert(_audioFrame.num_channels_ <= 2);
3051 if (_audioFrame.samples_per_channel_ == 0) {
3052 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3053 "Channel::EncodeAndSend() invalid audio frame");
3054 return 0xFFFFFFFF;
3055 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003056
kwiberg55b97fe2016-01-28 05:22:45 -08003057 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00003058
kwiberg55b97fe2016-01-28 05:22:45 -08003059 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00003060
kwiberg55b97fe2016-01-28 05:22:45 -08003061 // The ACM resamples internally.
3062 _audioFrame.timestamp_ = _timeStamp;
3063 // This call will trigger AudioPacketizationCallback::SendData if encoding
3064 // is done and payload is ready for packetization and transmission.
3065 // Otherwise, it will return without invoking the callback.
3066 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
3067 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
3068 "Channel::EncodeAndSend() ACM encoding failed");
3069 return 0xFFFFFFFF;
3070 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003071
kwiberg55b97fe2016-01-28 05:22:45 -08003072 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
3073 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003074}
3075
Minyue2013aec2015-05-13 14:14:42 +02003076void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08003077 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003078 Channel* channel = associate_send_channel_.channel();
3079 if (channel && channel->ChannelId() == channel_id) {
3080 // If this channel is associated with a send channel of the specified
3081 // Channel ID, disassociate with it.
3082 ChannelOwner ref(NULL);
3083 associate_send_channel_ = ref;
3084 }
3085}
3086
ivoc14d5dbe2016-07-04 07:06:55 -07003087void Channel::SetRtcEventLog(RtcEventLog* event_log) {
3088 event_log_proxy_->SetEventLog(event_log);
3089}
3090
kwiberg55b97fe2016-01-28 05:22:45 -08003091int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
3092 VoEMediaProcess& processObject) {
3093 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3094 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003095
kwiberg55b97fe2016-01-28 05:22:45 -08003096 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003097
kwiberg55b97fe2016-01-28 05:22:45 -08003098 if (kPlaybackPerChannel == type) {
3099 if (_outputExternalMediaCallbackPtr) {
3100 _engineStatisticsPtr->SetLastError(
3101 VE_INVALID_OPERATION, kTraceError,
3102 "Channel::RegisterExternalMediaProcessing() "
3103 "output external media already enabled");
3104 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003105 }
kwiberg55b97fe2016-01-28 05:22:45 -08003106 _outputExternalMediaCallbackPtr = &processObject;
3107 _outputExternalMedia = true;
3108 } else if (kRecordingPerChannel == type) {
3109 if (_inputExternalMediaCallbackPtr) {
3110 _engineStatisticsPtr->SetLastError(
3111 VE_INVALID_OPERATION, kTraceError,
3112 "Channel::RegisterExternalMediaProcessing() "
3113 "output external media already enabled");
3114 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003115 }
kwiberg55b97fe2016-01-28 05:22:45 -08003116 _inputExternalMediaCallbackPtr = &processObject;
3117 channel_state_.SetInputExternalMedia(true);
3118 }
3119 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003120}
3121
kwiberg55b97fe2016-01-28 05:22:45 -08003122int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
3123 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3124 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003125
kwiberg55b97fe2016-01-28 05:22:45 -08003126 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003127
kwiberg55b97fe2016-01-28 05:22:45 -08003128 if (kPlaybackPerChannel == type) {
3129 if (!_outputExternalMediaCallbackPtr) {
3130 _engineStatisticsPtr->SetLastError(
3131 VE_INVALID_OPERATION, kTraceWarning,
3132 "Channel::DeRegisterExternalMediaProcessing() "
3133 "output external media already disabled");
3134 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003135 }
kwiberg55b97fe2016-01-28 05:22:45 -08003136 _outputExternalMedia = false;
3137 _outputExternalMediaCallbackPtr = NULL;
3138 } else if (kRecordingPerChannel == type) {
3139 if (!_inputExternalMediaCallbackPtr) {
3140 _engineStatisticsPtr->SetLastError(
3141 VE_INVALID_OPERATION, kTraceWarning,
3142 "Channel::DeRegisterExternalMediaProcessing() "
3143 "input external media already disabled");
3144 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003145 }
kwiberg55b97fe2016-01-28 05:22:45 -08003146 channel_state_.SetInputExternalMedia(false);
3147 _inputExternalMediaCallbackPtr = NULL;
3148 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003149
kwiberg55b97fe2016-01-28 05:22:45 -08003150 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003151}
3152
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003153int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08003154 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3155 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003156
kwiberg55b97fe2016-01-28 05:22:45 -08003157 if (channel_state_.Get().playing) {
3158 _engineStatisticsPtr->SetLastError(
3159 VE_INVALID_OPERATION, kTraceError,
3160 "Channel::SetExternalMixing() "
3161 "external mixing cannot be changed while playing.");
3162 return -1;
3163 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003164
kwiberg55b97fe2016-01-28 05:22:45 -08003165 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003166
kwiberg55b97fe2016-01-28 05:22:45 -08003167 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003168}
3169
kwiberg55b97fe2016-01-28 05:22:45 -08003170int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3171 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003172}
3173
wu@webrtc.org24301a62013-12-13 19:17:43 +00003174void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3175 audio_coding_->GetDecodingCallStatistics(stats);
3176}
3177
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003178bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3179 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003180 rtc::CritScope lock(&video_sync_lock_);
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003181 if (_average_jitter_buffer_delay_us == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003182 return false;
3183 }
kwiberg55b97fe2016-01-28 05:22:45 -08003184 *jitter_buffer_delay_ms =
3185 (_average_jitter_buffer_delay_us + 500) / 1000 + _recPacketDelayMs;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003186 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003187 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003188}
3189
solenberg358057b2015-11-27 10:46:42 -08003190uint32_t Channel::GetDelayEstimate() const {
3191 int jitter_buffer_delay_ms = 0;
3192 int playout_buffer_delay_ms = 0;
3193 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3194 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3195}
3196
deadbeef74375882015-08-13 12:09:10 -07003197int Channel::LeastRequiredDelayMs() const {
3198 return audio_coding_->LeastRequiredDelayMs();
3199}
3200
kwiberg55b97fe2016-01-28 05:22:45 -08003201int Channel::SetMinimumPlayoutDelay(int delayMs) {
3202 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3203 "Channel::SetMinimumPlayoutDelay()");
3204 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3205 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3206 _engineStatisticsPtr->SetLastError(
3207 VE_INVALID_ARGUMENT, kTraceError,
3208 "SetMinimumPlayoutDelay() invalid min delay");
3209 return -1;
3210 }
3211 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3212 _engineStatisticsPtr->SetLastError(
3213 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3214 "SetMinimumPlayoutDelay() failed to set min playout delay");
3215 return -1;
3216 }
3217 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003218}
3219
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003220int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003221 uint32_t playout_timestamp_rtp = 0;
3222 {
tommi31fc21f2016-01-21 10:37:37 -08003223 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003224 playout_timestamp_rtp = playout_timestamp_rtp_;
3225 }
kwiberg55b97fe2016-01-28 05:22:45 -08003226 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003227 _engineStatisticsPtr->SetLastError(
3228 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3229 "GetPlayoutTimestamp() failed to retrieve timestamp");
3230 return -1;
3231 }
deadbeef74375882015-08-13 12:09:10 -07003232 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003233 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003234}
3235
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003236int Channel::SetInitTimestamp(unsigned int timestamp) {
3237 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003238 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003239 if (channel_state_.Get().sending) {
3240 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3241 "SetInitTimestamp() already sending");
3242 return -1;
3243 }
3244 _rtpRtcpModule->SetStartTimestamp(timestamp);
3245 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003246}
3247
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003248int Channel::SetInitSequenceNumber(short sequenceNumber) {
3249 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3250 "Channel::SetInitSequenceNumber()");
3251 if (channel_state_.Get().sending) {
3252 _engineStatisticsPtr->SetLastError(
3253 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3254 return -1;
3255 }
3256 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3257 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003258}
3259
kwiberg55b97fe2016-01-28 05:22:45 -08003260int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3261 RtpReceiver** rtp_receiver) const {
3262 *rtpRtcpModule = _rtpRtcpModule.get();
3263 *rtp_receiver = rtp_receiver_.get();
3264 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003265}
3266
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003267// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3268// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003269int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003270 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003271 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003272
kwiberg55b97fe2016-01-28 05:22:45 -08003273 {
3274 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003275
kwiberg55b97fe2016-01-28 05:22:45 -08003276 if (_inputFilePlayerPtr == NULL) {
3277 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3278 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3279 " doesnt exist");
3280 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003281 }
3282
kwiberg55b97fe2016-01-28 05:22:45 -08003283 if (_inputFilePlayerPtr->Get10msAudioFromFile(fileBuffer.get(), fileSamples,
3284 mixingFrequency) == -1) {
3285 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3286 "Channel::MixOrReplaceAudioWithFile() file mixing "
3287 "failed");
3288 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003289 }
kwiberg55b97fe2016-01-28 05:22:45 -08003290 if (fileSamples == 0) {
3291 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3292 "Channel::MixOrReplaceAudioWithFile() file is ended");
3293 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003294 }
kwiberg55b97fe2016-01-28 05:22:45 -08003295 }
3296
3297 assert(_audioFrame.samples_per_channel_ == fileSamples);
3298
3299 if (_mixFileWithMicrophone) {
3300 // Currently file stream is always mono.
3301 // TODO(xians): Change the code when FilePlayer supports real stereo.
3302 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3303 1, fileSamples);
3304 } else {
3305 // Replace ACM audio with file.
3306 // Currently file stream is always mono.
3307 // TODO(xians): Change the code when FilePlayer supports real stereo.
3308 _audioFrame.UpdateFrame(
3309 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3310 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3311 }
3312 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003313}
3314
kwiberg55b97fe2016-01-28 05:22:45 -08003315int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3316 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003317
kwibergb7f89d62016-02-17 10:04:18 -08003318 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003319 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003320
kwiberg55b97fe2016-01-28 05:22:45 -08003321 {
3322 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003323
kwiberg55b97fe2016-01-28 05:22:45 -08003324 if (_outputFilePlayerPtr == NULL) {
3325 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3326 "Channel::MixAudioWithFile() file mixing failed");
3327 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003328 }
3329
kwiberg55b97fe2016-01-28 05:22:45 -08003330 // We should get the frequency we ask for.
3331 if (_outputFilePlayerPtr->Get10msAudioFromFile(
3332 fileBuffer.get(), fileSamples, mixingFrequency) == -1) {
3333 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3334 "Channel::MixAudioWithFile() file mixing failed");
3335 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003336 }
kwiberg55b97fe2016-01-28 05:22:45 -08003337 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003338
kwiberg55b97fe2016-01-28 05:22:45 -08003339 if (audioFrame.samples_per_channel_ == fileSamples) {
3340 // Currently file stream is always mono.
3341 // TODO(xians): Change the code when FilePlayer supports real stereo.
3342 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3343 fileSamples);
3344 } else {
3345 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3346 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3347 ") != "
3348 "fileSamples(%" PRIuS ")",
3349 audioFrame.samples_per_channel_, fileSamples);
3350 return -1;
3351 }
3352
3353 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003354}
3355
deadbeef74375882015-08-13 12:09:10 -07003356void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003357 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003358
henrik.lundin96bd5022016-04-06 04:13:56 -07003359 if (!jitter_buffer_playout_timestamp_) {
3360 // This can happen if this channel has not received any RTP packets. In
3361 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003362 return;
3363 }
3364
3365 uint16_t delay_ms = 0;
3366 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003367 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003368 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3369 " delay from the ADM");
3370 _engineStatisticsPtr->SetLastError(
3371 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3372 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3373 return;
3374 }
3375
henrik.lundin96bd5022016-04-06 04:13:56 -07003376 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3377 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003378
3379 // Remove the playout delay.
henrik.lundin96bd5022016-04-06 04:13:56 -07003380 playout_timestamp -= (delay_ms * (GetPlayoutFrequency() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003381
kwiberg55b97fe2016-01-28 05:22:45 -08003382 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003383 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003384 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003385
3386 {
tommi31fc21f2016-01-21 10:37:37 -08003387 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003388 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003389 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003390 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003391 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003392 }
3393 playout_delay_ms_ = delay_ms;
3394 }
3395}
3396
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003397// Called for incoming RTP packets after successful RTP header parsing.
3398void Channel::UpdatePacketDelay(uint32_t rtp_timestamp,
3399 uint16_t sequence_number) {
kwiberg55b97fe2016-01-28 05:22:45 -08003400 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003401 "Channel::UpdatePacketDelay(timestamp=%lu, sequenceNumber=%u)",
3402 rtp_timestamp, sequence_number);
niklase@google.com470e71d2011-07-07 08:21:25 +00003403
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003404 // Get frequency of last received payload
wu@webrtc.org94454b72014-06-05 20:34:08 +00003405 int rtp_receive_frequency = GetPlayoutFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +00003406
turaj@webrtc.org167b6df2013-12-13 21:05:07 +00003407 // |jitter_buffer_playout_timestamp_| updated in UpdatePlayoutTimestamp for
henrik.lundin96bd5022016-04-06 04:13:56 -07003408 // every incoming packet. May be empty if no valid playout timestamp is
3409 // available.
3410 // If |rtp_timestamp| is newer than |jitter_buffer_playout_timestamp_|, the
3411 // resulting difference is positive and will be used. When the inverse is
3412 // true (can happen when a network glitch causes a packet to arrive late,
3413 // and during long comfort noise periods with clock drift), or when
3414 // |jitter_buffer_playout_timestamp_| has no value, the difference is not
3415 // changed from the initial 0.
3416 uint32_t timestamp_diff_ms = 0;
3417 if (jitter_buffer_playout_timestamp_ &&
3418 IsNewerTimestamp(rtp_timestamp, *jitter_buffer_playout_timestamp_)) {
3419 timestamp_diff_ms = (rtp_timestamp - *jitter_buffer_playout_timestamp_) /
3420 (rtp_receive_frequency / 1000);
3421 if (timestamp_diff_ms > (2 * kVoiceEngineMaxMinPlayoutDelayMs)) {
3422 // Diff is too large; set it to zero instead.
3423 timestamp_diff_ms = 0;
3424 }
henrik.lundin@webrtc.orgd6692992014-03-20 12:04:09 +00003425 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003426
kwiberg55b97fe2016-01-28 05:22:45 -08003427 uint16_t packet_delay_ms =
3428 (rtp_timestamp - _previousTimestamp) / (rtp_receive_frequency / 1000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003429
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003430 _previousTimestamp = rtp_timestamp;
niklase@google.com470e71d2011-07-07 08:21:25 +00003431
kwiberg55b97fe2016-01-28 05:22:45 -08003432 if (timestamp_diff_ms == 0)
3433 return;
niklase@google.com470e71d2011-07-07 08:21:25 +00003434
deadbeef74375882015-08-13 12:09:10 -07003435 {
tommi31fc21f2016-01-21 10:37:37 -08003436 rtc::CritScope lock(&video_sync_lock_);
niklase@google.com470e71d2011-07-07 08:21:25 +00003437
deadbeef74375882015-08-13 12:09:10 -07003438 if (packet_delay_ms >= 10 && packet_delay_ms <= 60) {
3439 _recPacketDelayMs = packet_delay_ms;
3440 }
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003441
deadbeef74375882015-08-13 12:09:10 -07003442 if (_average_jitter_buffer_delay_us == 0) {
3443 _average_jitter_buffer_delay_us = timestamp_diff_ms * 1000;
3444 return;
3445 }
3446
3447 // Filter average delay value using exponential filter (alpha is
3448 // 7/8). We derive 1000 *_average_jitter_buffer_delay_us here (reduces
3449 // risk of rounding error) and compensate for it in GetDelayEstimate()
3450 // later.
kwiberg55b97fe2016-01-28 05:22:45 -08003451 _average_jitter_buffer_delay_us =
3452 (_average_jitter_buffer_delay_us * 7 + 1000 * timestamp_diff_ms + 500) /
3453 8;
deadbeef74375882015-08-13 12:09:10 -07003454 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003455}
3456
kwiberg55b97fe2016-01-28 05:22:45 -08003457void Channel::RegisterReceiveCodecsToRTPModule() {
3458 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3459 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003460
kwiberg55b97fe2016-01-28 05:22:45 -08003461 CodecInst codec;
3462 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003463
kwiberg55b97fe2016-01-28 05:22:45 -08003464 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3465 // Open up the RTP/RTCP receiver for all supported codecs
3466 if ((audio_coding_->Codec(idx, &codec) == -1) ||
3467 (rtp_receiver_->RegisterReceivePayload(
3468 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3469 (codec.rate < 0) ? 0 : codec.rate) == -1)) {
3470 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3471 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3472 " to register %s (%d/%d/%" PRIuS
3473 "/%d) to RTP/RTCP "
3474 "receiver",
3475 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3476 codec.rate);
3477 } else {
3478 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3479 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3480 "(%d/%d/%" PRIuS
3481 "/%d) has been added to the RTP/RTCP "
3482 "receiver",
3483 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3484 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003485 }
kwiberg55b97fe2016-01-28 05:22:45 -08003486 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003487}
3488
kwiberg55b97fe2016-01-28 05:22:45 -08003489int Channel::SetSendRtpHeaderExtension(bool enable,
3490 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003491 unsigned char id) {
3492 int error = 0;
3493 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3494 if (enable) {
3495 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3496 }
3497 return error;
3498}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003499
wu@webrtc.org94454b72014-06-05 20:34:08 +00003500int32_t Channel::GetPlayoutFrequency() {
3501 int32_t playout_frequency = audio_coding_->PlayoutFrequency();
3502 CodecInst current_recive_codec;
3503 if (audio_coding_->ReceiveCodec(&current_recive_codec) == 0) {
3504 if (STR_CASE_CMP("G722", current_recive_codec.plname) == 0) {
3505 // Even though the actual sampling rate for G.722 audio is
3506 // 16,000 Hz, the RTP clock rate for the G722 payload format is
3507 // 8,000 Hz because that value was erroneously assigned in
3508 // RFC 1890 and must remain unchanged for backward compatibility.
3509 playout_frequency = 8000;
3510 } else if (STR_CASE_CMP("opus", current_recive_codec.plname) == 0) {
3511 // We are resampling Opus internally to 32,000 Hz until all our
3512 // DSP routines can operate at 48,000 Hz, but the RTP clock
3513 // rate for the Opus payload format is standardized to 48,000 Hz,
3514 // because that is the maximum supported decoding sampling rate.
3515 playout_frequency = 48000;
3516 }
3517 }
3518 return playout_frequency;
3519}
3520
Minyue2013aec2015-05-13 14:14:42 +02003521int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003522 RtcpMode method = _rtpRtcpModule->RTCP();
3523 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003524 return 0;
3525 }
3526 std::vector<RTCPReportBlock> report_blocks;
3527 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003528
3529 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003530 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003531 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003532 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003533 Channel* channel = associate_send_channel_.channel();
3534 // Tries to get RTT from an associated channel. This is important for
3535 // receive-only channels.
3536 if (channel) {
3537 // To prevent infinite recursion and deadlock, calling GetRTT of
3538 // associate channel should always use "false" for argument:
3539 // |allow_associate_channel|.
3540 rtt = channel->GetRTT(false);
3541 }
3542 }
3543 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003544 }
3545
3546 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3547 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3548 for (; it != report_blocks.end(); ++it) {
3549 if (it->remoteSSRC == remoteSSRC)
3550 break;
3551 }
3552 if (it == report_blocks.end()) {
3553 // We have not received packets with SSRC matching the report blocks.
3554 // To calculate RTT we try with the SSRC of the first report block.
3555 // This is very important for send-only channels where we don't know
3556 // the SSRC of the other end.
3557 remoteSSRC = report_blocks[0].remoteSSRC;
3558 }
Minyue2013aec2015-05-13 14:14:42 +02003559
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003560 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003561 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003562 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003563 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3564 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003565 return 0;
3566 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003567 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003568}
3569
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003570} // namespace voe
3571} // namespace webrtc