blob: 2791f7f8b4ed555ed9da3e8d3f45ab6b9fa18171 [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
aleloi6321b492016-12-05 01:46:09 -080016#include "webrtc/audio/utility/audio_frame_operations.h"
henrik.lundin50499422016-11-29 04:26:24 -080017#include "webrtc/base/array_view.h"
Ivo Creusenae856f22015-09-17 16:30:16 +020018#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080019#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000020#include "webrtc/base/format_macros.h"
pbosad856222015-11-27 09:48:36 -080021#include "webrtc/base/logging.h"
Erik Språng737336d2016-07-29 12:59:36 +020022#include "webrtc/base/rate_limiter.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010023#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000024#include "webrtc/base/timeutils.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020025#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070026#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070027#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000028#include "webrtc/modules/audio_device/include/audio_device.h"
29#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010030#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010031#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010032#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
33#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
34#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000035#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010036#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010037#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000038#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
Erik Språng737336d2016-07-29 12:59:36 +020050constexpr int64_t kMaxRetransmissionWindowMs = 1000;
51constexpr int64_t kMinRetransmissionWindowMs = 30;
52
kwibergc8d071e2016-04-06 12:22:38 -070053} // namespace
54
solenberg8842c3e2016-03-11 03:06:41 -080055const int kTelephoneEventAttenuationdB = 10;
56
ivoc14d5dbe2016-07-04 07:06:55 -070057class RtcEventLogProxy final : public webrtc::RtcEventLog {
58 public:
59 RtcEventLogProxy() : event_log_(nullptr) {}
60
61 bool StartLogging(const std::string& file_name,
62 int64_t max_size_bytes) override {
63 RTC_NOTREACHED();
64 return false;
65 }
66
67 bool StartLogging(rtc::PlatformFile log_file,
68 int64_t max_size_bytes) override {
69 RTC_NOTREACHED();
70 return false;
71 }
72
73 void StopLogging() override { RTC_NOTREACHED(); }
74
75 void LogVideoReceiveStreamConfig(
76 const webrtc::VideoReceiveStream::Config& config) override {
77 rtc::CritScope lock(&crit_);
78 if (event_log_) {
79 event_log_->LogVideoReceiveStreamConfig(config);
80 }
81 }
82
83 void LogVideoSendStreamConfig(
84 const webrtc::VideoSendStream::Config& config) override {
85 rtc::CritScope lock(&crit_);
86 if (event_log_) {
87 event_log_->LogVideoSendStreamConfig(config);
88 }
89 }
90
ivoce0928d82016-10-10 05:12:51 -070091 void LogAudioReceiveStreamConfig(
92 const webrtc::AudioReceiveStream::Config& config) override {
93 rtc::CritScope lock(&crit_);
94 if (event_log_) {
95 event_log_->LogAudioReceiveStreamConfig(config);
96 }
97 }
98
99 void LogAudioSendStreamConfig(
100 const webrtc::AudioSendStream::Config& config) override {
101 rtc::CritScope lock(&crit_);
102 if (event_log_) {
103 event_log_->LogAudioSendStreamConfig(config);
104 }
105 }
106
ivoc14d5dbe2016-07-04 07:06:55 -0700107 void LogRtpHeader(webrtc::PacketDirection direction,
108 webrtc::MediaType media_type,
109 const uint8_t* header,
110 size_t packet_length) override {
111 rtc::CritScope lock(&crit_);
112 if (event_log_) {
113 event_log_->LogRtpHeader(direction, media_type, header, packet_length);
114 }
115 }
116
117 void LogRtcpPacket(webrtc::PacketDirection direction,
118 webrtc::MediaType media_type,
119 const uint8_t* packet,
120 size_t length) override {
121 rtc::CritScope lock(&crit_);
122 if (event_log_) {
123 event_log_->LogRtcpPacket(direction, media_type, packet, length);
124 }
125 }
126
127 void LogAudioPlayout(uint32_t ssrc) override {
128 rtc::CritScope lock(&crit_);
129 if (event_log_) {
130 event_log_->LogAudioPlayout(ssrc);
131 }
132 }
133
134 void LogBwePacketLossEvent(int32_t bitrate,
135 uint8_t fraction_loss,
136 int32_t total_packets) override {
137 rtc::CritScope lock(&crit_);
138 if (event_log_) {
139 event_log_->LogBwePacketLossEvent(bitrate, fraction_loss, total_packets);
140 }
141 }
142
minyue4b7c9522017-01-24 04:54:59 -0800143 void LogAudioNetworkAdaptation(
144 const AudioNetworkAdaptor::EncoderRuntimeConfig& config) override {
145 rtc::CritScope lock(&crit_);
146 if (event_log_) {
147 event_log_->LogAudioNetworkAdaptation(config);
148 }
149 }
150
ivoc14d5dbe2016-07-04 07:06:55 -0700151 void SetEventLog(RtcEventLog* event_log) {
152 rtc::CritScope lock(&crit_);
153 event_log_ = event_log;
154 }
155
156 private:
157 rtc::CriticalSection crit_;
158 RtcEventLog* event_log_ GUARDED_BY(crit_);
159 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
160};
161
michaelt9332b7d2016-11-30 07:51:13 -0800162class RtcpRttStatsProxy final : public RtcpRttStats {
163 public:
164 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
165
166 void OnRttUpdate(int64_t rtt) override {
167 rtc::CritScope lock(&crit_);
168 if (rtcp_rtt_stats_)
169 rtcp_rtt_stats_->OnRttUpdate(rtt);
170 }
171
172 int64_t LastProcessedRtt() const override {
173 rtc::CritScope lock(&crit_);
174 if (!rtcp_rtt_stats_)
175 return 0;
176 return rtcp_rtt_stats_->LastProcessedRtt();
177 }
178
179 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
180 rtc::CritScope lock(&crit_);
181 rtcp_rtt_stats_ = rtcp_rtt_stats;
182 }
183
184 private:
185 rtc::CriticalSection crit_;
186 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
187 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
188};
189
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100190class TransportFeedbackProxy : public TransportFeedbackObserver {
191 public:
192 TransportFeedbackProxy() : feedback_observer_(nullptr) {
193 pacer_thread_.DetachFromThread();
194 network_thread_.DetachFromThread();
195 }
196
197 void SetTransportFeedbackObserver(
198 TransportFeedbackObserver* feedback_observer) {
199 RTC_DCHECK(thread_checker_.CalledOnValidThread());
200 rtc::CritScope lock(&crit_);
201 feedback_observer_ = feedback_observer;
202 }
203
204 // Implements TransportFeedbackObserver.
205 void AddPacket(uint16_t sequence_number,
206 size_t length,
philipela1ed0b32016-06-01 06:31:17 -0700207 int probe_cluster_id) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100208 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
209 rtc::CritScope lock(&crit_);
210 if (feedback_observer_)
pbos2169d8b2016-06-20 11:53:02 -0700211 feedback_observer_->AddPacket(sequence_number, length, probe_cluster_id);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100212 }
213 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
214 RTC_DCHECK(network_thread_.CalledOnValidThread());
215 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700216 if (feedback_observer_)
217 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200218 }
219 std::vector<PacketInfo> GetTransportFeedbackVector() const override {
220 RTC_NOTREACHED();
221 return std::vector<PacketInfo>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100222 }
223
224 private:
225 rtc::CriticalSection crit_;
226 rtc::ThreadChecker thread_checker_;
227 rtc::ThreadChecker pacer_thread_;
228 rtc::ThreadChecker network_thread_;
229 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
230};
231
232class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
233 public:
234 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
235 pacer_thread_.DetachFromThread();
236 }
237
238 void SetSequenceNumberAllocator(
239 TransportSequenceNumberAllocator* seq_num_allocator) {
240 RTC_DCHECK(thread_checker_.CalledOnValidThread());
241 rtc::CritScope lock(&crit_);
242 seq_num_allocator_ = seq_num_allocator;
243 }
244
245 // Implements TransportSequenceNumberAllocator.
246 uint16_t AllocateSequenceNumber() override {
247 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
248 rtc::CritScope lock(&crit_);
249 if (!seq_num_allocator_)
250 return 0;
251 return seq_num_allocator_->AllocateSequenceNumber();
252 }
253
254 private:
255 rtc::CriticalSection crit_;
256 rtc::ThreadChecker thread_checker_;
257 rtc::ThreadChecker pacer_thread_;
258 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
259};
260
261class RtpPacketSenderProxy : public RtpPacketSender {
262 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800263 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100264
265 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
266 RTC_DCHECK(thread_checker_.CalledOnValidThread());
267 rtc::CritScope lock(&crit_);
268 rtp_packet_sender_ = rtp_packet_sender;
269 }
270
271 // Implements RtpPacketSender.
272 void InsertPacket(Priority priority,
273 uint32_t ssrc,
274 uint16_t sequence_number,
275 int64_t capture_time_ms,
276 size_t bytes,
277 bool retransmission) override {
278 rtc::CritScope lock(&crit_);
279 if (rtp_packet_sender_) {
280 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
281 capture_time_ms, bytes, retransmission);
282 }
283 }
284
285 private:
286 rtc::ThreadChecker thread_checker_;
287 rtc::CriticalSection crit_;
288 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
289};
290
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000291// Extend the default RTCP statistics struct with max_jitter, defined as the
292// maximum jitter value seen in an RTCP report block.
293struct ChannelStatistics : public RtcpStatistics {
294 ChannelStatistics() : rtcp(), max_jitter(0) {}
295
296 RtcpStatistics rtcp;
297 uint32_t max_jitter;
298};
299
300// Statistics callback, called at each generation of a new RTCP report block.
301class StatisticsProxy : public RtcpStatisticsCallback {
302 public:
tommi31fc21f2016-01-21 10:37:37 -0800303 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000304 virtual ~StatisticsProxy() {}
305
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000306 void StatisticsUpdated(const RtcpStatistics& statistics,
307 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000308 if (ssrc != ssrc_)
309 return;
310
tommi31fc21f2016-01-21 10:37:37 -0800311 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000312 stats_.rtcp = statistics;
313 if (statistics.jitter > stats_.max_jitter) {
314 stats_.max_jitter = statistics.jitter;
315 }
316 }
317
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000318 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000319
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000320 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800321 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000322 return stats_;
323 }
324
325 private:
326 // StatisticsUpdated calls are triggered from threads in the RTP module,
327 // while GetStats calls can be triggered from the public voice engine API,
328 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800329 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000330 const uint32_t ssrc_;
331 ChannelStatistics stats_;
332};
333
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000334class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000335 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000336 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
337 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000338
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000339 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
340 // Not used for Voice Engine.
341 }
342
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000343 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
344 int64_t rtt,
345 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000346 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
347 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
348 // report for VoiceEngine?
349 if (report_blocks.empty())
350 return;
351
352 int fraction_lost_aggregate = 0;
353 int total_number_of_packets = 0;
354
355 // If receiving multiple report blocks, calculate the weighted average based
356 // on the number of packets a report refers to.
357 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
358 block_it != report_blocks.end(); ++block_it) {
359 // Find the previous extended high sequence number for this remote SSRC,
360 // to calculate the number of RTP packets this report refers to. Ignore if
361 // we haven't seen this SSRC before.
362 std::map<uint32_t, uint32_t>::iterator seq_num_it =
363 extended_max_sequence_number_.find(block_it->sourceSSRC);
364 int number_of_packets = 0;
365 if (seq_num_it != extended_max_sequence_number_.end()) {
366 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
367 }
368 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
369 total_number_of_packets += number_of_packets;
370
371 extended_max_sequence_number_[block_it->sourceSSRC] =
372 block_it->extendedHighSeqNum;
373 }
374 int weighted_fraction_lost = 0;
375 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800376 weighted_fraction_lost =
377 (fraction_lost_aggregate + total_number_of_packets / 2) /
378 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000379 }
380 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000381 }
382
383 private:
384 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000385 // Maps remote side ssrc to extended highest sequence number received.
386 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000387};
388
kwiberg55b97fe2016-01-28 05:22:45 -0800389int32_t Channel::SendData(FrameType frameType,
390 uint8_t payloadType,
391 uint32_t timeStamp,
392 const uint8_t* payloadData,
393 size_t payloadSize,
394 const RTPFragmentationHeader* fragmentation) {
395 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
396 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
397 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
398 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000399
kwiberg55b97fe2016-01-28 05:22:45 -0800400 if (_includeAudioLevelIndication) {
401 // Store current audio level in the RTP/RTCP module.
402 // The level will be used in combination with voice-activity state
403 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800404 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800405 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000406
kwiberg55b97fe2016-01-28 05:22:45 -0800407 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
408 // packetization.
409 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700410 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800411 (FrameType&)frameType, payloadType, timeStamp,
412 // Leaving the time when this frame was
413 // received from the capture device as
414 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700415 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800416 _engineStatisticsPtr->SetLastError(
417 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
418 "Channel::SendData() failed to send data to RTP/RTCP module");
419 return -1;
420 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000421
kwiberg55b97fe2016-01-28 05:22:45 -0800422 _lastLocalTimeStamp = timeStamp;
423 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000424
kwiberg55b97fe2016-01-28 05:22:45 -0800425 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000426}
427
kwiberg55b97fe2016-01-28 05:22:45 -0800428int32_t Channel::InFrameType(FrameType frame_type) {
429 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
430 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000431
kwiberg55b97fe2016-01-28 05:22:45 -0800432 rtc::CritScope cs(&_callbackCritSect);
433 _sendFrameType = (frame_type == kAudioFrameSpeech);
434 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000435}
436
stefan1d8a5062015-10-02 03:39:33 -0700437bool Channel::SendRtp(const uint8_t* data,
438 size_t len,
439 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800440 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
441 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000442
kwiberg55b97fe2016-01-28 05:22:45 -0800443 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000444
kwiberg55b97fe2016-01-28 05:22:45 -0800445 if (_transportPtr == NULL) {
446 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
447 "Channel::SendPacket() failed to send RTP packet due to"
448 " invalid transport object");
449 return false;
450 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000451
kwiberg55b97fe2016-01-28 05:22:45 -0800452 uint8_t* bufferToSendPtr = (uint8_t*)data;
453 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000454
kwiberg55b97fe2016-01-28 05:22:45 -0800455 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
456 std::string transport_name =
457 _externalTransport ? "external transport" : "WebRtc sockets";
458 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
459 "Channel::SendPacket() RTP transmission using %s failed",
460 transport_name.c_str());
461 return false;
462 }
463 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000464}
465
kwiberg55b97fe2016-01-28 05:22:45 -0800466bool Channel::SendRtcp(const uint8_t* data, size_t len) {
467 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
468 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000469
kwiberg55b97fe2016-01-28 05:22:45 -0800470 rtc::CritScope cs(&_callbackCritSect);
471 if (_transportPtr == NULL) {
472 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
473 "Channel::SendRtcp() failed to send RTCP packet"
474 " due to invalid transport object");
475 return false;
476 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000477
kwiberg55b97fe2016-01-28 05:22:45 -0800478 uint8_t* bufferToSendPtr = (uint8_t*)data;
479 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000480
kwiberg55b97fe2016-01-28 05:22:45 -0800481 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
482 if (n < 0) {
483 std::string transport_name =
484 _externalTransport ? "external transport" : "WebRtc sockets";
485 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
486 "Channel::SendRtcp() transmission using %s failed",
487 transport_name.c_str());
488 return false;
489 }
490 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000491}
492
kwiberg55b97fe2016-01-28 05:22:45 -0800493void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
494 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
495 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000496
kwiberg55b97fe2016-01-28 05:22:45 -0800497 // Update ssrc so that NTP for AV sync can be updated.
498 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000499}
500
Peter Boströmac547a62015-09-17 23:03:57 +0200501void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
502 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
503 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
504 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000505}
506
Peter Boströmac547a62015-09-17 23:03:57 +0200507int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000508 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000509 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000510 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800511 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200512 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800513 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
514 "Channel::OnInitializeDecoder(payloadType=%d, "
515 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
516 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000517
kwiberg55b97fe2016-01-28 05:22:45 -0800518 CodecInst receiveCodec = {0};
519 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000520
kwiberg55b97fe2016-01-28 05:22:45 -0800521 receiveCodec.pltype = payloadType;
522 receiveCodec.plfreq = frequency;
523 receiveCodec.channels = channels;
524 receiveCodec.rate = rate;
525 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000526
kwiberg55b97fe2016-01-28 05:22:45 -0800527 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
528 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000529
kwiberg55b97fe2016-01-28 05:22:45 -0800530 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700531 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
532 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800533 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
534 "Channel::OnInitializeDecoder() invalid codec ("
535 "pt=%d, name=%s) received - 1",
536 payloadType, payloadName);
537 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
538 return -1;
539 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000540
kwiberg55b97fe2016-01-28 05:22:45 -0800541 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000542}
543
kwiberg55b97fe2016-01-28 05:22:45 -0800544int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
545 size_t payloadSize,
546 const WebRtcRTPHeader* rtpHeader) {
547 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
548 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
549 ","
550 " payloadType=%u, audioChannel=%" PRIuS ")",
551 payloadSize, rtpHeader->header.payloadType,
552 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000553
kwiberg55b97fe2016-01-28 05:22:45 -0800554 if (!channel_state_.Get().playing) {
555 // Avoid inserting into NetEQ when we are not playing. Count the
556 // packet as discarded.
557 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
558 "received packet is discarded since playing is not"
559 " activated");
560 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000561 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800562 }
563
564 // Push the incoming payload (parsed and ready for decoding) into the ACM
565 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
566 0) {
567 _engineStatisticsPtr->SetLastError(
568 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
569 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
570 return -1;
571 }
572
kwiberg55b97fe2016-01-28 05:22:45 -0800573 int64_t round_trip_time = 0;
574 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
575 NULL);
576
577 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
578 if (!nack_list.empty()) {
579 // Can't use nack_list.data() since it's not supported by all
580 // compilers.
581 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
582 }
583 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000584}
585
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000586bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000587 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000588 RTPHeader header;
589 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
590 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
591 "IncomingPacket invalid RTP header");
592 return false;
593 }
594 header.payload_type_frequency =
595 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
596 if (header.payload_type_frequency < 0)
597 return false;
598 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
599}
600
henrik.lundin42dda502016-05-18 05:36:01 -0700601MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
602 int32_t id,
603 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700604 unsigned int ssrc;
605 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
606 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800607 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700608 bool muted;
609 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
610 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800611 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
612 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
613 // In all likelihood, the audio in this frame is garbage. We return an
614 // error so that the audio mixer module doesn't add it to the mix. As
615 // a result, it won't be played out and the actions skipped here are
616 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700617 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800618 }
henrik.lundina89ab962016-05-18 08:52:45 -0700619
620 if (muted) {
621 // TODO(henrik.lundin): We should be able to do better than this. But we
622 // will have to go through all the cases below where the audio samples may
623 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800624 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700625 }
kwiberg55b97fe2016-01-28 05:22:45 -0800626
kwiberg55b97fe2016-01-28 05:22:45 -0800627 // Convert module ID to internal VoE channel ID
628 audioFrame->id_ = VoEChannelId(audioFrame->id_);
629 // Store speech type for dead-or-alive detection
630 _outputSpeechType = audioFrame->speech_type_;
631
632 ChannelState::State state = channel_state_.Get();
633
kwiberg55b97fe2016-01-28 05:22:45 -0800634 {
635 // Pass the audio buffers to an optional sink callback, before applying
636 // scaling/panning, as that applies to the mix operation.
637 // External recipients of the audio (e.g. via AudioTrack), will do their
638 // own mixing/dynamic processing.
639 rtc::CritScope cs(&_callbackCritSect);
640 if (audio_sink_) {
641 AudioSinkInterface::Data data(
642 &audioFrame->data_[0], audioFrame->samples_per_channel_,
643 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
644 audioFrame->timestamp_);
645 audio_sink_->OnData(data);
646 }
647 }
648
649 float output_gain = 1.0f;
650 float left_pan = 1.0f;
651 float right_pan = 1.0f;
652 {
653 rtc::CritScope cs(&volume_settings_critsect_);
654 output_gain = _outputGain;
655 left_pan = _panLeft;
656 right_pan = _panRight;
657 }
658
659 // Output volume scaling
660 if (output_gain < 0.99f || output_gain > 1.01f) {
661 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
662 }
663
664 // Scale left and/or right channel(s) if stereo and master balance is
665 // active
666
667 if (left_pan != 1.0f || right_pan != 1.0f) {
668 if (audioFrame->num_channels_ == 1) {
669 // Emulate stereo mode since panning is active.
670 // The mono signal is copied to both left and right channels here.
671 AudioFrameOperations::MonoToStereo(audioFrame);
672 }
673 // For true stereo mode (when we are receiving a stereo signal), no
674 // action is needed.
675
676 // Do the panning operation (the audio frame contains stereo at this
677 // stage)
678 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
679 }
680
681 // Mix decoded PCM output with file if file mixing is enabled
682 if (state.output_file_playing) {
683 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700684 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800685 }
686
687 // External media
688 if (_outputExternalMedia) {
689 rtc::CritScope cs(&_callbackCritSect);
690 const bool isStereo = (audioFrame->num_channels_ == 2);
691 if (_outputExternalMediaCallbackPtr) {
692 _outputExternalMediaCallbackPtr->Process(
693 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
694 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
695 isStereo);
696 }
697 }
698
699 // Record playout if enabled
700 {
701 rtc::CritScope cs(&_fileCritSect);
702
kwiberg5a25d952016-08-17 07:31:12 -0700703 if (_outputFileRecording && output_file_recorder_) {
704 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800705 }
706 }
707
708 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700709 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800710 _outputAudioLevel.ComputeLevel(*audioFrame);
711
712 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
713 // The first frame with a valid rtp timestamp.
714 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
715 }
716
717 if (capture_start_rtp_time_stamp_ >= 0) {
718 // audioFrame.timestamp_ should be valid from now on.
719
720 // Compute elapsed time.
721 int64_t unwrap_timestamp =
722 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
723 audioFrame->elapsed_time_ms_ =
724 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700725 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800726
niklase@google.com470e71d2011-07-07 08:21:25 +0000727 {
kwiberg55b97fe2016-01-28 05:22:45 -0800728 rtc::CritScope lock(&ts_stats_lock_);
729 // Compute ntp time.
730 audioFrame->ntp_time_ms_ =
731 ntp_estimator_.Estimate(audioFrame->timestamp_);
732 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
733 if (audioFrame->ntp_time_ms_ > 0) {
734 // Compute |capture_start_ntp_time_ms_| so that
735 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
736 capture_start_ntp_time_ms_ =
737 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000738 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000739 }
kwiberg55b97fe2016-01-28 05:22:45 -0800740 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000741
henrik.lundin42dda502016-05-18 05:36:01 -0700742 return muted ? MixerParticipant::AudioFrameInfo::kMuted
743 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
aleloi6c278492016-10-20 14:24:39 -0700746AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
747 int sample_rate_hz,
748 AudioFrame* audio_frame) {
749 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700750
aleloi6c278492016-10-20 14:24:39 -0700751 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700752
753 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
754 FrameInfo new_audio_frame_info = FrameInfo::kError;
755 switch (frame_info) {
756 case MixerParticipant::AudioFrameInfo::kNormal:
757 new_audio_frame_info = FrameInfo::kNormal;
758 break;
759 case MixerParticipant::AudioFrameInfo::kMuted:
760 new_audio_frame_info = FrameInfo::kMuted;
761 break;
762 case MixerParticipant::AudioFrameInfo::kError:
763 new_audio_frame_info = FrameInfo::kError;
764 break;
765 }
aleloi6c278492016-10-20 14:24:39 -0700766 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700767}
768
kwiberg55b97fe2016-01-28 05:22:45 -0800769int32_t Channel::NeededFrequency(int32_t id) const {
770 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
771 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000772
kwiberg55b97fe2016-01-28 05:22:45 -0800773 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000774
kwiberg55b97fe2016-01-28 05:22:45 -0800775 // Determine highest needed receive frequency
776 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000777
kwiberg55b97fe2016-01-28 05:22:45 -0800778 // Return the bigger of playout and receive frequency in the ACM.
779 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
780 highestNeeded = audio_coding_->PlayoutFrequency();
781 } else {
782 highestNeeded = receiveFrequency;
783 }
784
785 // Special case, if we're playing a file on the playout side
786 // we take that frequency into consideration as well
787 // This is not needed on sending side, since the codec will
788 // limit the spectrum anyway.
789 if (channel_state_.Get().output_file_playing) {
790 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700791 if (output_file_player_) {
792 if (output_file_player_->Frequency() > highestNeeded) {
793 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800794 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000795 }
kwiberg55b97fe2016-01-28 05:22:45 -0800796 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000797
kwiberg55b97fe2016-01-28 05:22:45 -0800798 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000799}
800
ossu5f7cfa52016-05-30 08:11:28 -0700801int32_t Channel::CreateChannel(
802 Channel*& channel,
803 int32_t channelId,
804 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700805 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800806 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
807 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
808 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000809
solenberg88499ec2016-09-07 07:34:41 -0700810 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800811 if (channel == NULL) {
812 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
813 "Channel::CreateChannel() unable to allocate memory for"
814 " channel");
815 return -1;
816 }
817 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000818}
819
kwiberg55b97fe2016-01-28 05:22:45 -0800820void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
821 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
822 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
823 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000824
kwiberg55b97fe2016-01-28 05:22:45 -0800825 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000826}
827
kwiberg55b97fe2016-01-28 05:22:45 -0800828void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
829 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
830 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
831 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000832
kwiberg55b97fe2016-01-28 05:22:45 -0800833 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000834}
835
kwiberg55b97fe2016-01-28 05:22:45 -0800836void Channel::PlayFileEnded(int32_t id) {
837 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
838 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000839
kwiberg55b97fe2016-01-28 05:22:45 -0800840 if (id == _inputFilePlayerId) {
841 channel_state_.SetInputFilePlaying(false);
842 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
843 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000844 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800845 } else if (id == _outputFilePlayerId) {
846 channel_state_.SetOutputFilePlaying(false);
847 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
848 "Channel::PlayFileEnded() => output file player module is"
849 " shutdown");
850 }
851}
852
853void Channel::RecordFileEnded(int32_t id) {
854 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
855 "Channel::RecordFileEnded(id=%d)", id);
856
857 assert(id == _outputFileRecorderId);
858
859 rtc::CritScope cs(&_fileCritSect);
860
861 _outputFileRecording = false;
862 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
863 "Channel::RecordFileEnded() => output file recorder module is"
864 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000865}
866
pbos@webrtc.org92135212013-05-14 08:31:39 +0000867Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000868 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700869 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800870 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100871 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700872 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800873 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100874 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800875 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 rtp_receive_statistics_(
877 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
878 rtp_receiver_(
879 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100880 this,
881 this,
882 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700883 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100884 _outputAudioLevel(),
885 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100886 // Avoid conflict with other channels by adding 1024 - 1026,
887 // won't use as much as 1024 channels.
888 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
889 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
890 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
891 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100892 _outputExternalMedia(false),
893 _inputExternalMediaCallbackPtr(NULL),
894 _outputExternalMediaCallbackPtr(NULL),
895 _timeStamp(0), // This is just an offset, RTP module will add it's own
896 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100897 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100898 playout_timestamp_rtp_(0),
899 playout_timestamp_rtcp_(0),
900 playout_delay_ms_(0),
901 _numberOfDiscardedPackets(0),
902 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100903 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
904 capture_start_rtp_time_stamp_(-1),
905 capture_start_ntp_time_ms_(-1),
906 _engineStatisticsPtr(NULL),
907 _outputMixerPtr(NULL),
908 _transmitMixerPtr(NULL),
909 _moduleProcessThreadPtr(NULL),
910 _audioDeviceModulePtr(NULL),
911 _voiceEngineObserverPtr(NULL),
912 _callbackCritSectPtr(NULL),
913 _transportPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100914 _sendFrameType(0),
915 _externalMixing(false),
916 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700917 input_mute_(false),
918 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100919 _panLeft(1.0f),
920 _panRight(1.0f),
921 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100922 _lastLocalTimeStamp(0),
923 _lastPayloadType(0),
924 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800925 transport_overhead_per_packet_(0),
926 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100927 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100928 restored_packet_in_use_(false),
929 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100930 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700931 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800932 feedback_observer_proxy_(new TransportFeedbackProxy()),
933 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700934 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200935 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
936 kMaxRetransmissionWindowMs)),
michaelt566d8202017-01-12 10:17:38 -0800937 decoder_factory_(config.acm_config.decoder_factory) {
kwiberg55b97fe2016-01-28 05:22:45 -0800938 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
939 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700940 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800941 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700942 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800943 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200944
kwiberg55b97fe2016-01-28 05:22:45 -0800945 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000946
kwiberg55b97fe2016-01-28 05:22:45 -0800947 RtpRtcp::Configuration configuration;
948 configuration.audio = true;
949 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800950 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800951 configuration.receive_statistics = rtp_receive_statistics_.get();
952 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800953 if (pacing_enabled_) {
954 configuration.paced_sender = rtp_packet_sender_proxy_.get();
955 configuration.transport_sequence_number_allocator =
956 seq_num_allocator_proxy_.get();
957 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
958 }
ivoc14d5dbe2016-07-04 07:06:55 -0700959 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800960 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200961 configuration.retransmission_rate_limiter =
962 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000963
kwiberg55b97fe2016-01-28 05:22:45 -0800964 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100965 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000966
kwiberg55b97fe2016-01-28 05:22:45 -0800967 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
968 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
969 statistics_proxy_.get());
niklase@google.com470e71d2011-07-07 08:21:25 +0000970}
971
kwiberg55b97fe2016-01-28 05:22:45 -0800972Channel::~Channel() {
973 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
974 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
975 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000976
kwiberg55b97fe2016-01-28 05:22:45 -0800977 if (_outputExternalMedia) {
978 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
979 }
980 if (channel_state_.Get().input_external_media) {
981 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
982 }
983 StopSend();
984 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000985
kwiberg55b97fe2016-01-28 05:22:45 -0800986 {
987 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700988 if (input_file_player_) {
989 input_file_player_->RegisterModuleFileCallback(NULL);
990 input_file_player_->StopPlayingFile();
niklase@google.com470e71d2011-07-07 08:21:25 +0000991 }
kwiberg5a25d952016-08-17 07:31:12 -0700992 if (output_file_player_) {
993 output_file_player_->RegisterModuleFileCallback(NULL);
994 output_file_player_->StopPlayingFile();
kwiberg55b97fe2016-01-28 05:22:45 -0800995 }
kwiberg5a25d952016-08-17 07:31:12 -0700996 if (output_file_recorder_) {
997 output_file_recorder_->RegisterModuleFileCallback(NULL);
998 output_file_recorder_->StopRecording();
kwiberg55b97fe2016-01-28 05:22:45 -0800999 }
1000 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001001
kwiberg55b97fe2016-01-28 05:22:45 -08001002 // The order to safely shutdown modules in a channel is:
1003 // 1. De-register callbacks in modules
1004 // 2. De-register modules in process thread
1005 // 3. Destroy modules
1006 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1007 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1008 "~Channel() failed to de-register transport callback"
1009 " (Audio coding module)");
1010 }
1011 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1012 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1013 "~Channel() failed to de-register VAD callback"
1014 " (Audio coding module)");
1015 }
1016 // De-register modules in process thread
1017 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +00001018
kwiberg55b97fe2016-01-28 05:22:45 -08001019 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +00001020}
1021
kwiberg55b97fe2016-01-28 05:22:45 -08001022int32_t Channel::Init() {
1023 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1024 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001025
kwiberg55b97fe2016-01-28 05:22:45 -08001026 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001027
kwiberg55b97fe2016-01-28 05:22:45 -08001028 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +00001029
kwiberg55b97fe2016-01-28 05:22:45 -08001030 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
1031 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1032 "Channel::Init() must call SetEngineInformation() first");
1033 return -1;
1034 }
1035
1036 // --- Add modules to process thread (for periodic schedulation)
1037
1038 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
1039
1040 // --- ACM initialization
1041
1042 if (audio_coding_->InitializeReceiver() == -1) {
1043 _engineStatisticsPtr->SetLastError(
1044 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1045 "Channel::Init() unable to initialize the ACM - 1");
1046 return -1;
1047 }
1048
1049 // --- RTP/RTCP module initialization
1050
1051 // Ensure that RTCP is enabled by default for the created channel.
1052 // Note that, the module will keep generating RTCP until it is explicitly
1053 // disabled by the user.
1054 // After StopListen (when no sockets exists), RTCP packets will no longer
1055 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -07001056 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001057 // RTCP is enabled by default.
1058 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1059 // --- Register all permanent callbacks
1060 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
1061 (audio_coding_->RegisterVADCallback(this) == -1);
1062
1063 if (fail) {
1064 _engineStatisticsPtr->SetLastError(
1065 VE_CANNOT_INIT_CHANNEL, kTraceError,
1066 "Channel::Init() callbacks not registered");
1067 return -1;
1068 }
1069
1070 // --- Register all supported codecs to the receiving side of the
1071 // RTP/RTCP module
1072
1073 CodecInst codec;
1074 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1075
1076 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1077 // Open up the RTP/RTCP receiver for all supported codecs
1078 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001079 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001080 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1081 "Channel::Init() unable to register %s "
1082 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1083 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1084 codec.rate);
1085 } else {
1086 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1087 "Channel::Init() %s (%d/%d/%" PRIuS
1088 "/%d) has been "
1089 "added to the RTP/RTCP receiver",
1090 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1091 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001092 }
1093
kwiberg55b97fe2016-01-28 05:22:45 -08001094 // Ensure that PCMU is used as default codec on the sending side
1095 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1096 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001097 }
1098
kwiberg55b97fe2016-01-28 05:22:45 -08001099 // Register default PT for outband 'telephone-event'
1100 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001101 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
kwibergda2bf4e2016-10-24 13:47:09 -07001102 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1103 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001104 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1105 "Channel::Init() failed to register outband "
1106 "'telephone-event' (%d/%d) correctly",
1107 codec.pltype, codec.plfreq);
1108 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001109 }
1110
kwiberg55b97fe2016-01-28 05:22:45 -08001111 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001112 if (!codec_manager_.RegisterEncoder(codec) ||
1113 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
kwibergda2bf4e2016-10-24 13:47:09 -07001114 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1115 CodecInstToSdp(codec)) ||
kwibergc8d071e2016-04-06 12:22:38 -07001116 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001117 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1118 "Channel::Init() failed to register CN (%d/%d) "
1119 "correctly - 1",
1120 codec.pltype, codec.plfreq);
1121 }
1122 }
kwiberg55b97fe2016-01-28 05:22:45 -08001123 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001124
kwiberg55b97fe2016-01-28 05:22:45 -08001125 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001126}
1127
kwiberg55b97fe2016-01-28 05:22:45 -08001128int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1129 OutputMixer& outputMixer,
1130 voe::TransmitMixer& transmitMixer,
1131 ProcessThread& moduleProcessThread,
1132 AudioDeviceModule& audioDeviceModule,
1133 VoiceEngineObserver* voiceEngineObserver,
1134 rtc::CriticalSection* callbackCritSect) {
1135 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1136 "Channel::SetEngineInformation()");
1137 _engineStatisticsPtr = &engineStatistics;
1138 _outputMixerPtr = &outputMixer;
1139 _transmitMixerPtr = &transmitMixer,
1140 _moduleProcessThreadPtr = &moduleProcessThread;
1141 _audioDeviceModulePtr = &audioDeviceModule;
1142 _voiceEngineObserverPtr = voiceEngineObserver;
1143 _callbackCritSectPtr = callbackCritSect;
1144 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001145}
1146
kwiberg55b97fe2016-01-28 05:22:45 -08001147int32_t Channel::UpdateLocalTimeStamp() {
1148 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1149 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001150}
1151
kwibergb7f89d62016-02-17 10:04:18 -08001152void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001153 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001154 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001155}
1156
ossu29b1a8d2016-06-13 07:34:51 -07001157const rtc::scoped_refptr<AudioDecoderFactory>&
1158Channel::GetAudioDecoderFactory() const {
1159 return decoder_factory_;
1160}
1161
kwiberg55b97fe2016-01-28 05:22:45 -08001162int32_t Channel::StartPlayout() {
1163 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1164 "Channel::StartPlayout()");
1165 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001166 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001167 }
1168
1169 if (!_externalMixing) {
1170 // Add participant as candidates for mixing.
1171 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1172 _engineStatisticsPtr->SetLastError(
1173 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1174 "StartPlayout() failed to add participant to mixer");
1175 return -1;
1176 }
1177 }
1178
1179 channel_state_.SetPlaying(true);
1180 if (RegisterFilePlayingToMixer() != 0)
1181 return -1;
1182
1183 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001184}
1185
kwiberg55b97fe2016-01-28 05:22:45 -08001186int32_t Channel::StopPlayout() {
1187 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1188 "Channel::StopPlayout()");
1189 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001190 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001191 }
1192
1193 if (!_externalMixing) {
1194 // Remove participant as candidates for mixing
1195 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1196 _engineStatisticsPtr->SetLastError(
1197 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1198 "StopPlayout() failed to remove participant from mixer");
1199 return -1;
1200 }
1201 }
1202
1203 channel_state_.SetPlaying(false);
1204 _outputAudioLevel.Clear();
1205
1206 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001207}
1208
kwiberg55b97fe2016-01-28 05:22:45 -08001209int32_t Channel::StartSend() {
1210 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1211 "Channel::StartSend()");
1212 // Resume the previous sequence number which was reset by StopSend().
1213 // This needs to be done before |sending| is set to true.
1214 if (send_sequence_number_)
1215 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001216
kwiberg55b97fe2016-01-28 05:22:45 -08001217 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001218 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001219 }
1220 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001221
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001222 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001223 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1224 _engineStatisticsPtr->SetLastError(
1225 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1226 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001227 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001228 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001229 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001230 return -1;
1231 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001232
kwiberg55b97fe2016-01-28 05:22:45 -08001233 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001234}
1235
kwiberg55b97fe2016-01-28 05:22:45 -08001236int32_t Channel::StopSend() {
1237 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1238 "Channel::StopSend()");
1239 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001240 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001241 }
1242 channel_state_.SetSending(false);
1243
1244 // Store the sequence number to be able to pick up the same sequence for
1245 // the next StartSend(). This is needed for restarting device, otherwise
1246 // it might cause libSRTP to complain about packets being replayed.
1247 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1248 // CL is landed. See issue
1249 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1250 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1251
1252 // Reset sending SSRC and sequence number and triggers direct transmission
1253 // of RTCP BYE
1254 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1255 _engineStatisticsPtr->SetLastError(
1256 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1257 "StartSend() RTP/RTCP failed to stop sending");
1258 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001259 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001260
1261 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001262}
1263
solenberge566ac72016-10-31 12:52:33 -07001264void Channel::ResetDiscardedPacketCount() {
kwiberg55b97fe2016-01-28 05:22:45 -08001265 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberge566ac72016-10-31 12:52:33 -07001266 "Channel::ResetDiscardedPacketCount()");
kwiberg55b97fe2016-01-28 05:22:45 -08001267 _numberOfDiscardedPackets = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001268}
1269
kwiberg55b97fe2016-01-28 05:22:45 -08001270int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1271 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1272 "Channel::RegisterVoiceEngineObserver()");
1273 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001274
kwiberg55b97fe2016-01-28 05:22:45 -08001275 if (_voiceEngineObserverPtr) {
1276 _engineStatisticsPtr->SetLastError(
1277 VE_INVALID_OPERATION, kTraceError,
1278 "RegisterVoiceEngineObserver() observer already enabled");
1279 return -1;
1280 }
1281 _voiceEngineObserverPtr = &observer;
1282 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001283}
1284
kwiberg55b97fe2016-01-28 05:22:45 -08001285int32_t Channel::DeRegisterVoiceEngineObserver() {
1286 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1287 "Channel::DeRegisterVoiceEngineObserver()");
1288 rtc::CritScope cs(&_callbackCritSect);
1289
1290 if (!_voiceEngineObserverPtr) {
1291 _engineStatisticsPtr->SetLastError(
1292 VE_INVALID_OPERATION, kTraceWarning,
1293 "DeRegisterVoiceEngineObserver() observer already disabled");
1294 return 0;
1295 }
1296 _voiceEngineObserverPtr = NULL;
1297 return 0;
1298}
1299
1300int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001301 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001302 if (send_codec) {
1303 codec = *send_codec;
1304 return 0;
1305 }
1306 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001307}
1308
kwiberg55b97fe2016-01-28 05:22:45 -08001309int32_t Channel::GetRecCodec(CodecInst& codec) {
1310 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001311}
1312
kwiberg55b97fe2016-01-28 05:22:45 -08001313int32_t Channel::SetSendCodec(const CodecInst& codec) {
1314 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1315 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001316
kwibergc8d071e2016-04-06 12:22:38 -07001317 if (!codec_manager_.RegisterEncoder(codec) ||
1318 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001319 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1320 "SetSendCodec() failed to register codec to ACM");
1321 return -1;
1322 }
1323
1324 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1325 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1326 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1327 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1328 "SetSendCodec() failed to register codec to"
1329 " RTP/RTCP module");
1330 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001331 }
kwiberg55b97fe2016-01-28 05:22:45 -08001332 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001333
kwiberg55b97fe2016-01-28 05:22:45 -08001334 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001335}
1336
minyue78b4d562016-11-30 04:47:39 -08001337void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001338 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1339 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001340 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001341 if (*encoder) {
1342 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001343 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001344 }
1345 });
michaelt566d8202017-01-12 10:17:38 -08001346 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001347}
1348
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001349void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue7e304322016-10-12 05:00:55 -07001350 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1351 if (*encoder)
1352 (*encoder)->OnReceivedUplinkPacketLossFraction(fraction_lost / 255.0f);
1353 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001354}
1355
kwiberg55b97fe2016-01-28 05:22:45 -08001356int32_t Channel::SetVADStatus(bool enableVAD,
1357 ACMVADMode mode,
1358 bool disableDTX) {
1359 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1360 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001361 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1362 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1363 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001364 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1365 kTraceError,
1366 "SetVADStatus() failed to set VAD");
1367 return -1;
1368 }
1369 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001370}
1371
kwiberg55b97fe2016-01-28 05:22:45 -08001372int32_t Channel::GetVADStatus(bool& enabledVAD,
1373 ACMVADMode& mode,
1374 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001375 const auto* params = codec_manager_.GetStackParams();
1376 enabledVAD = params->use_cng;
1377 mode = params->vad_mode;
1378 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001379 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001380}
1381
kwiberg55b97fe2016-01-28 05:22:45 -08001382int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001383 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1384}
1385
1386int32_t Channel::SetRecPayloadType(int payload_type,
1387 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001388 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1389 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001390
kwiberg55b97fe2016-01-28 05:22:45 -08001391 if (channel_state_.Get().playing) {
1392 _engineStatisticsPtr->SetLastError(
1393 VE_ALREADY_PLAYING, kTraceError,
1394 "SetRecPayloadType() unable to set PT while playing");
1395 return -1;
1396 }
kwiberg55b97fe2016-01-28 05:22:45 -08001397
kwibergd32bf752017-01-19 07:03:59 -08001398 const CodecInst codec = [&] {
1399 CodecInst c = SdpToCodecInst(payload_type, format);
1400
1401 // Bug 6986: Emulate an old bug that caused us to always choose to decode
1402 // Opus in stereo. To be able to remove this, we first need to fix the
1403 // other half of bug 6986, which is about losing the Opus "stereo"
1404 // parameter.
1405 // TODO(kwiberg): Remove this special case, a.k.a. fix bug 6986.
1406 if (STR_CASE_CMP(codec.plname, "opus") == 0) {
1407 c.channels = 2;
1408 }
1409
1410 return c;
1411 }();
1412
1413 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001414 // De-register the selected codec (RTP/RTCP module and ACM)
1415
1416 int8_t pltype(-1);
1417 CodecInst rxCodec = codec;
1418
1419 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001420 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001421 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
magjed56124bd2016-11-24 09:34:46 -08001439 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001440 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001441 // TODO(kwiberg): Retrying is probably not necessary, since
1442 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001443 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001444 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001445 _engineStatisticsPtr->SetLastError(
1446 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1447 "SetRecPayloadType() RTP/RTCP-module registration failed");
1448 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001449 }
kwiberg55b97fe2016-01-28 05:22:45 -08001450 }
kwibergd32bf752017-01-19 07:03:59 -08001451 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1452 audio_coding_->UnregisterReceiveCodec(payload_type);
1453 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001454 _engineStatisticsPtr->SetLastError(
1455 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1456 "SetRecPayloadType() ACM registration failed - 1");
1457 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001458 }
kwiberg55b97fe2016-01-28 05:22:45 -08001459 }
1460 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001461}
1462
kwiberg55b97fe2016-01-28 05:22:45 -08001463int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1464 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001465 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001466 _engineStatisticsPtr->SetLastError(
1467 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1468 "GetRecPayloadType() failed to retrieve RX payload type");
1469 return -1;
1470 }
1471 codec.pltype = payloadType;
1472 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001473}
1474
kwiberg55b97fe2016-01-28 05:22:45 -08001475int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1476 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1477 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001478
kwiberg55b97fe2016-01-28 05:22:45 -08001479 CodecInst codec;
1480 int32_t samplingFreqHz(-1);
1481 const size_t kMono = 1;
1482 if (frequency == kFreq32000Hz)
1483 samplingFreqHz = 32000;
1484 else if (frequency == kFreq16000Hz)
1485 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001486
kwiberg55b97fe2016-01-28 05:22:45 -08001487 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1488 _engineStatisticsPtr->SetLastError(
1489 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1490 "SetSendCNPayloadType() failed to retrieve default CN codec "
1491 "settings");
1492 return -1;
1493 }
1494
1495 // Modify the payload type (must be set to dynamic range)
1496 codec.pltype = type;
1497
kwibergc8d071e2016-04-06 12:22:38 -07001498 if (!codec_manager_.RegisterEncoder(codec) ||
1499 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001500 _engineStatisticsPtr->SetLastError(
1501 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1502 "SetSendCNPayloadType() failed to register CN to ACM");
1503 return -1;
1504 }
1505
1506 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1507 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1508 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1509 _engineStatisticsPtr->SetLastError(
1510 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1511 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1512 "module");
1513 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001514 }
kwiberg55b97fe2016-01-28 05:22:45 -08001515 }
1516 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001517}
1518
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001519int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001520 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001521 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001522
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001523 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001524 _engineStatisticsPtr->SetLastError(
1525 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001526 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001527 return -1;
1528 }
1529 return 0;
1530}
1531
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001532int Channel::SetOpusDtx(bool enable_dtx) {
1533 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1534 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001535 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001536 : audio_coding_->DisableOpusDtx();
1537 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001538 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1539 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001540 return -1;
1541 }
1542 return 0;
1543}
1544
ivoc85228d62016-07-27 04:53:47 -07001545int Channel::GetOpusDtx(bool* enabled) {
1546 int success = -1;
1547 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1548 if (encoder) {
1549 *enabled = encoder->GetDtx();
1550 success = 0;
1551 }
1552 });
1553 return success;
1554}
1555
minyue7e304322016-10-12 05:00:55 -07001556bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1557 bool success = false;
1558 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1559 if (*encoder) {
1560 success = (*encoder)->EnableAudioNetworkAdaptor(
michaeltbf279fc2017-01-13 06:02:29 -08001561 config_string, event_log_proxy_.get(), Clock::GetRealTimeClock());
minyue7e304322016-10-12 05:00:55 -07001562 }
1563 });
1564 return success;
1565}
1566
1567void Channel::DisableAudioNetworkAdaptor() {
1568 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1569 if (*encoder)
1570 (*encoder)->DisableAudioNetworkAdaptor();
1571 });
1572}
1573
1574void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1575 int max_frame_length_ms) {
1576 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1577 if (*encoder) {
1578 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1579 max_frame_length_ms);
1580 }
1581 });
1582}
1583
mflodman3d7db262016-04-29 00:57:13 -07001584int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001585 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001586 "Channel::RegisterExternalTransport()");
1587
kwiberg55b97fe2016-01-28 05:22:45 -08001588 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001589 if (_externalTransport) {
1590 _engineStatisticsPtr->SetLastError(
1591 VE_INVALID_OPERATION, kTraceError,
1592 "RegisterExternalTransport() external transport already enabled");
1593 return -1;
1594 }
1595 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001596 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001597 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001598}
1599
kwiberg55b97fe2016-01-28 05:22:45 -08001600int32_t Channel::DeRegisterExternalTransport() {
1601 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1602 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001603
kwiberg55b97fe2016-01-28 05:22:45 -08001604 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001605 if (_transportPtr) {
1606 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1607 "DeRegisterExternalTransport() all transport is disabled");
1608 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001609 _engineStatisticsPtr->SetLastError(
1610 VE_INVALID_OPERATION, kTraceWarning,
1611 "DeRegisterExternalTransport() external transport already "
1612 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001613 }
1614 _externalTransport = false;
1615 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001616 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001617}
1618
mflodman3d7db262016-04-29 00:57:13 -07001619int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001620 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001621 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001622 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001623 "Channel::ReceivedRTPPacket()");
1624
1625 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001626 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001627
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001628 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001629 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1630 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1631 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001632 return -1;
1633 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001634 header.payload_type_frequency =
1635 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001636 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001637 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001638 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001639 rtp_receive_statistics_->IncomingPacket(
1640 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001641 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001642
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001643 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001644}
1645
1646bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001647 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001648 const RTPHeader& header,
1649 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001650 if (rtp_payload_registry_->IsRtx(header)) {
1651 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001652 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001653 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001654 assert(packet_length >= header.headerLength);
1655 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001656 PayloadUnion payload_specific;
1657 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001658 &payload_specific)) {
1659 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001660 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001661 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1662 payload_specific, in_order);
1663}
1664
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001665bool Channel::HandleRtxPacket(const uint8_t* packet,
1666 size_t packet_length,
1667 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001668 if (!rtp_payload_registry_->IsRtx(header))
1669 return false;
1670
1671 // Remove the RTX header and parse the original RTP header.
1672 if (packet_length < header.headerLength)
1673 return false;
1674 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1675 return false;
1676 if (restored_packet_in_use_) {
1677 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1678 "Multiple RTX headers detected, dropping packet");
1679 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001680 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001681 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001682 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1683 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001684 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1685 "Incoming RTX packet: invalid RTP header");
1686 return false;
1687 }
1688 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001689 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001690 restored_packet_in_use_ = false;
1691 return ret;
1692}
1693
1694bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1695 StreamStatistician* statistician =
1696 rtp_receive_statistics_->GetStatistician(header.ssrc);
1697 if (!statistician)
1698 return false;
1699 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001700}
1701
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001702bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1703 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001704 // Retransmissions are handled separately if RTX is enabled.
1705 if (rtp_payload_registry_->RtxEnabled())
1706 return false;
1707 StreamStatistician* statistician =
1708 rtp_receive_statistics_->GetStatistician(header.ssrc);
1709 if (!statistician)
1710 return false;
1711 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001712 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001713 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001714 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001715}
1716
mflodman3d7db262016-04-29 00:57:13 -07001717int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001718 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001719 "Channel::ReceivedRTCPPacket()");
1720 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001721 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001722
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001723 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001724 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001725 _engineStatisticsPtr->SetLastError(
1726 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1727 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1728 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001729
Minyue2013aec2015-05-13 14:14:42 +02001730 int64_t rtt = GetRTT(true);
1731 if (rtt == 0) {
1732 // Waiting for valid RTT.
1733 return 0;
1734 }
Erik Språng737336d2016-07-29 12:59:36 +02001735
1736 int64_t nack_window_ms = rtt;
1737 if (nack_window_ms < kMinRetransmissionWindowMs) {
1738 nack_window_ms = kMinRetransmissionWindowMs;
1739 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1740 nack_window_ms = kMaxRetransmissionWindowMs;
1741 }
1742 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1743
minyue7e304322016-10-12 05:00:55 -07001744 // Invoke audio encoders OnReceivedRtt().
1745 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1746 if (*encoder)
1747 (*encoder)->OnReceivedRtt(rtt);
1748 });
1749
Minyue2013aec2015-05-13 14:14:42 +02001750 uint32_t ntp_secs = 0;
1751 uint32_t ntp_frac = 0;
1752 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001753 if (0 !=
1754 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1755 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001756 // Waiting for RTCP.
1757 return 0;
1758 }
1759
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001760 {
tommi31fc21f2016-01-21 10:37:37 -08001761 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001762 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001763 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001764 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001765}
1766
niklase@google.com470e71d2011-07-07 08:21:25 +00001767int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001768 bool loop,
1769 FileFormats format,
1770 int startPosition,
1771 float volumeScaling,
1772 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001773 const CodecInst* codecInst) {
1774 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1775 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1776 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1777 "stopPosition=%d)",
1778 fileName, loop, format, volumeScaling, startPosition,
1779 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001780
kwiberg55b97fe2016-01-28 05:22:45 -08001781 if (channel_state_.Get().output_file_playing) {
1782 _engineStatisticsPtr->SetLastError(
1783 VE_ALREADY_PLAYING, kTraceError,
1784 "StartPlayingFileLocally() is already playing");
1785 return -1;
1786 }
1787
1788 {
1789 rtc::CritScope cs(&_fileCritSect);
1790
kwiberg5a25d952016-08-17 07:31:12 -07001791 if (output_file_player_) {
1792 output_file_player_->RegisterModuleFileCallback(NULL);
1793 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001794 }
1795
kwiberg5b356f42016-09-08 04:32:33 -07001796 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001797 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001798
kwiberg5a25d952016-08-17 07:31:12 -07001799 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001800 _engineStatisticsPtr->SetLastError(
1801 VE_INVALID_ARGUMENT, kTraceError,
1802 "StartPlayingFileLocally() filePlayer format is not correct");
1803 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001804 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001805
kwiberg55b97fe2016-01-28 05:22:45 -08001806 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001807
kwiberg5a25d952016-08-17 07:31:12 -07001808 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001809 fileName, loop, startPosition, volumeScaling, notificationTime,
1810 stopPosition, (const CodecInst*)codecInst) != 0) {
1811 _engineStatisticsPtr->SetLastError(
1812 VE_BAD_FILE, kTraceError,
1813 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001814 output_file_player_->StopPlayingFile();
1815 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001816 return -1;
1817 }
kwiberg5a25d952016-08-17 07:31:12 -07001818 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001819 channel_state_.SetOutputFilePlaying(true);
1820 }
1821
1822 if (RegisterFilePlayingToMixer() != 0)
1823 return -1;
1824
1825 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001826}
1827
1828int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001829 FileFormats format,
1830 int startPosition,
1831 float volumeScaling,
1832 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001833 const CodecInst* codecInst) {
1834 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1835 "Channel::StartPlayingFileLocally(format=%d,"
1836 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1837 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001838
kwiberg55b97fe2016-01-28 05:22:45 -08001839 if (stream == NULL) {
1840 _engineStatisticsPtr->SetLastError(
1841 VE_BAD_FILE, kTraceError,
1842 "StartPlayingFileLocally() NULL as input stream");
1843 return -1;
1844 }
1845
1846 if (channel_state_.Get().output_file_playing) {
1847 _engineStatisticsPtr->SetLastError(
1848 VE_ALREADY_PLAYING, kTraceError,
1849 "StartPlayingFileLocally() is already playing");
1850 return -1;
1851 }
1852
1853 {
1854 rtc::CritScope cs(&_fileCritSect);
1855
1856 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001857 if (output_file_player_) {
1858 output_file_player_->RegisterModuleFileCallback(NULL);
1859 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001860 }
1861
kwiberg55b97fe2016-01-28 05:22:45 -08001862 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001863 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001864 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001865
kwiberg5a25d952016-08-17 07:31:12 -07001866 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001867 _engineStatisticsPtr->SetLastError(
1868 VE_INVALID_ARGUMENT, kTraceError,
1869 "StartPlayingFileLocally() filePlayer format isnot correct");
1870 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001871 }
1872
kwiberg55b97fe2016-01-28 05:22:45 -08001873 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001874
kwiberg4ec01d92016-08-22 08:43:54 -07001875 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001876 volumeScaling, notificationTime,
1877 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001878 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1879 "StartPlayingFile() failed to "
1880 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001881 output_file_player_->StopPlayingFile();
1882 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001883 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001884 }
kwiberg5a25d952016-08-17 07:31:12 -07001885 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001886 channel_state_.SetOutputFilePlaying(true);
1887 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001888
kwiberg55b97fe2016-01-28 05:22:45 -08001889 if (RegisterFilePlayingToMixer() != 0)
1890 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001891
kwiberg55b97fe2016-01-28 05:22:45 -08001892 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001893}
1894
kwiberg55b97fe2016-01-28 05:22:45 -08001895int Channel::StopPlayingFileLocally() {
1896 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1897 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001898
kwiberg55b97fe2016-01-28 05:22:45 -08001899 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001900 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001901 }
1902
1903 {
1904 rtc::CritScope cs(&_fileCritSect);
1905
kwiberg5a25d952016-08-17 07:31:12 -07001906 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001907 _engineStatisticsPtr->SetLastError(
1908 VE_STOP_RECORDING_FAILED, kTraceError,
1909 "StopPlayingFile() could not stop playing");
1910 return -1;
1911 }
kwiberg5a25d952016-08-17 07:31:12 -07001912 output_file_player_->RegisterModuleFileCallback(NULL);
1913 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001914 channel_state_.SetOutputFilePlaying(false);
1915 }
1916 // _fileCritSect cannot be taken while calling
1917 // SetAnonymousMixibilityStatus. Refer to comments in
1918 // StartPlayingFileLocally(const char* ...) for more details.
1919 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1920 _engineStatisticsPtr->SetLastError(
1921 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1922 "StopPlayingFile() failed to stop participant from playing as"
1923 "file in the mixer");
1924 return -1;
1925 }
1926
1927 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001928}
1929
kwiberg55b97fe2016-01-28 05:22:45 -08001930int Channel::IsPlayingFileLocally() const {
1931 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001932}
1933
kwiberg55b97fe2016-01-28 05:22:45 -08001934int Channel::RegisterFilePlayingToMixer() {
1935 // Return success for not registering for file playing to mixer if:
1936 // 1. playing file before playout is started on that channel.
1937 // 2. starting playout without file playing on that channel.
1938 if (!channel_state_.Get().playing ||
1939 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001940 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001941 }
1942
1943 // |_fileCritSect| cannot be taken while calling
1944 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1945 // frames can be pulled by the mixer. Since the frames are generated from
1946 // the file, _fileCritSect will be taken. This would result in a deadlock.
1947 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1948 channel_state_.SetOutputFilePlaying(false);
1949 rtc::CritScope cs(&_fileCritSect);
1950 _engineStatisticsPtr->SetLastError(
1951 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1952 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001953 output_file_player_->StopPlayingFile();
1954 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001955 return -1;
1956 }
1957
1958 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001959}
1960
niklase@google.com470e71d2011-07-07 08:21:25 +00001961int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001962 bool loop,
1963 FileFormats format,
1964 int startPosition,
1965 float volumeScaling,
1966 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001967 const CodecInst* codecInst) {
1968 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1969 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1970 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1971 "stopPosition=%d)",
1972 fileName, loop, format, volumeScaling, startPosition,
1973 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001974
kwiberg55b97fe2016-01-28 05:22:45 -08001975 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001976
kwiberg55b97fe2016-01-28 05:22:45 -08001977 if (channel_state_.Get().input_file_playing) {
1978 _engineStatisticsPtr->SetLastError(
1979 VE_ALREADY_PLAYING, kTraceWarning,
1980 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001981 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001982 }
1983
1984 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001985 if (input_file_player_) {
1986 input_file_player_->RegisterModuleFileCallback(NULL);
1987 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001988 }
1989
1990 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001991 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07001992 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08001993
kwiberg5a25d952016-08-17 07:31:12 -07001994 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001995 _engineStatisticsPtr->SetLastError(
1996 VE_INVALID_ARGUMENT, kTraceError,
1997 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1998 return -1;
1999 }
2000
2001 const uint32_t notificationTime(0);
2002
kwiberg5a25d952016-08-17 07:31:12 -07002003 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002004 fileName, loop, startPosition, volumeScaling, notificationTime,
2005 stopPosition, (const CodecInst*)codecInst) != 0) {
2006 _engineStatisticsPtr->SetLastError(
2007 VE_BAD_FILE, kTraceError,
2008 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002009 input_file_player_->StopPlayingFile();
2010 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002011 return -1;
2012 }
kwiberg5a25d952016-08-17 07:31:12 -07002013 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002014 channel_state_.SetInputFilePlaying(true);
2015
2016 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002017}
2018
2019int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002020 FileFormats format,
2021 int startPosition,
2022 float volumeScaling,
2023 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002024 const CodecInst* codecInst) {
2025 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2026 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2027 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2028 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002029
kwiberg55b97fe2016-01-28 05:22:45 -08002030 if (stream == NULL) {
2031 _engineStatisticsPtr->SetLastError(
2032 VE_BAD_FILE, kTraceError,
2033 "StartPlayingFileAsMicrophone NULL as input stream");
2034 return -1;
2035 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002036
kwiberg55b97fe2016-01-28 05:22:45 -08002037 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002038
kwiberg55b97fe2016-01-28 05:22:45 -08002039 if (channel_state_.Get().input_file_playing) {
2040 _engineStatisticsPtr->SetLastError(
2041 VE_ALREADY_PLAYING, kTraceWarning,
2042 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002043 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002044 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002045
kwiberg55b97fe2016-01-28 05:22:45 -08002046 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002047 if (input_file_player_) {
2048 input_file_player_->RegisterModuleFileCallback(NULL);
2049 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002050 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002051
kwiberg55b97fe2016-01-28 05:22:45 -08002052 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002053 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002054 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002055
kwiberg5a25d952016-08-17 07:31:12 -07002056 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002057 _engineStatisticsPtr->SetLastError(
2058 VE_INVALID_ARGUMENT, kTraceError,
2059 "StartPlayingInputFile() filePlayer format isnot correct");
2060 return -1;
2061 }
2062
2063 const uint32_t notificationTime(0);
2064
kwiberg4ec01d92016-08-22 08:43:54 -07002065 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2066 notificationTime, stopPosition,
2067 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002068 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2069 "StartPlayingFile() failed to start "
2070 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002071 input_file_player_->StopPlayingFile();
2072 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002073 return -1;
2074 }
2075
kwiberg5a25d952016-08-17 07:31:12 -07002076 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002077 channel_state_.SetInputFilePlaying(true);
2078
2079 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002080}
2081
kwiberg55b97fe2016-01-28 05:22:45 -08002082int Channel::StopPlayingFileAsMicrophone() {
2083 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2084 "Channel::StopPlayingFileAsMicrophone()");
2085
2086 rtc::CritScope cs(&_fileCritSect);
2087
2088 if (!channel_state_.Get().input_file_playing) {
2089 return 0;
2090 }
2091
kwiberg5a25d952016-08-17 07:31:12 -07002092 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002093 _engineStatisticsPtr->SetLastError(
2094 VE_STOP_RECORDING_FAILED, kTraceError,
2095 "StopPlayingFile() could not stop playing");
2096 return -1;
2097 }
kwiberg5a25d952016-08-17 07:31:12 -07002098 input_file_player_->RegisterModuleFileCallback(NULL);
2099 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002100 channel_state_.SetInputFilePlaying(false);
2101
2102 return 0;
2103}
2104
2105int Channel::IsPlayingFileAsMicrophone() const {
2106 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002107}
2108
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002109int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002110 const CodecInst* codecInst) {
2111 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2112 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002113
kwiberg55b97fe2016-01-28 05:22:45 -08002114 if (_outputFileRecording) {
2115 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2116 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002117 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002118 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002119
kwiberg55b97fe2016-01-28 05:22:45 -08002120 FileFormats format;
2121 const uint32_t notificationTime(0); // Not supported in VoE
2122 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002123
kwiberg55b97fe2016-01-28 05:22:45 -08002124 if ((codecInst != NULL) &&
2125 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2126 _engineStatisticsPtr->SetLastError(
2127 VE_BAD_ARGUMENT, kTraceError,
2128 "StartRecordingPlayout() invalid compression");
2129 return (-1);
2130 }
2131 if (codecInst == NULL) {
2132 format = kFileFormatPcm16kHzFile;
2133 codecInst = &dummyCodec;
2134 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2135 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2136 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2137 format = kFileFormatWavFile;
2138 } else {
2139 format = kFileFormatCompressedFile;
2140 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002141
kwiberg55b97fe2016-01-28 05:22:45 -08002142 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002143
kwiberg55b97fe2016-01-28 05:22:45 -08002144 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002145 if (output_file_recorder_) {
2146 output_file_recorder_->RegisterModuleFileCallback(NULL);
2147 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002148 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002149
kwiberg5a25d952016-08-17 07:31:12 -07002150 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002151 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002152 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002153 _engineStatisticsPtr->SetLastError(
2154 VE_INVALID_ARGUMENT, kTraceError,
2155 "StartRecordingPlayout() fileRecorder format isnot correct");
2156 return -1;
2157 }
2158
kwiberg5a25d952016-08-17 07:31:12 -07002159 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002160 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2161 _engineStatisticsPtr->SetLastError(
2162 VE_BAD_FILE, kTraceError,
2163 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002164 output_file_recorder_->StopRecording();
2165 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002166 return -1;
2167 }
kwiberg5a25d952016-08-17 07:31:12 -07002168 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002169 _outputFileRecording = true;
2170
2171 return 0;
2172}
2173
2174int Channel::StartRecordingPlayout(OutStream* stream,
2175 const CodecInst* codecInst) {
2176 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2177 "Channel::StartRecordingPlayout()");
2178
2179 if (_outputFileRecording) {
2180 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2181 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002182 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002183 }
2184
2185 FileFormats format;
2186 const uint32_t notificationTime(0); // Not supported in VoE
2187 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2188
2189 if (codecInst != NULL && codecInst->channels != 1) {
2190 _engineStatisticsPtr->SetLastError(
2191 VE_BAD_ARGUMENT, kTraceError,
2192 "StartRecordingPlayout() invalid compression");
2193 return (-1);
2194 }
2195 if (codecInst == NULL) {
2196 format = kFileFormatPcm16kHzFile;
2197 codecInst = &dummyCodec;
2198 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2199 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2200 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2201 format = kFileFormatWavFile;
2202 } else {
2203 format = kFileFormatCompressedFile;
2204 }
2205
2206 rtc::CritScope cs(&_fileCritSect);
2207
2208 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002209 if (output_file_recorder_) {
2210 output_file_recorder_->RegisterModuleFileCallback(NULL);
2211 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002212 }
2213
kwiberg5a25d952016-08-17 07:31:12 -07002214 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002215 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002216 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002217 _engineStatisticsPtr->SetLastError(
2218 VE_INVALID_ARGUMENT, kTraceError,
2219 "StartRecordingPlayout() fileRecorder format isnot correct");
2220 return -1;
2221 }
2222
kwiberg4ec01d92016-08-22 08:43:54 -07002223 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002224 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002225 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2226 "StartRecordingPlayout() failed to "
2227 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002228 output_file_recorder_->StopRecording();
2229 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002230 return -1;
2231 }
2232
kwiberg5a25d952016-08-17 07:31:12 -07002233 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002234 _outputFileRecording = true;
2235
2236 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002237}
2238
kwiberg55b97fe2016-01-28 05:22:45 -08002239int Channel::StopRecordingPlayout() {
2240 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2241 "Channel::StopRecordingPlayout()");
2242
2243 if (!_outputFileRecording) {
2244 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2245 "StopRecordingPlayout() isnot recording");
2246 return -1;
2247 }
2248
2249 rtc::CritScope cs(&_fileCritSect);
2250
kwiberg5a25d952016-08-17 07:31:12 -07002251 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002252 _engineStatisticsPtr->SetLastError(
2253 VE_STOP_RECORDING_FAILED, kTraceError,
2254 "StopRecording() could not stop recording");
2255 return (-1);
2256 }
kwiberg5a25d952016-08-17 07:31:12 -07002257 output_file_recorder_->RegisterModuleFileCallback(NULL);
2258 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002259 _outputFileRecording = false;
2260
2261 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002262}
2263
kwiberg55b97fe2016-01-28 05:22:45 -08002264void Channel::SetMixWithMicStatus(bool mix) {
2265 rtc::CritScope cs(&_fileCritSect);
2266 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002267}
2268
kwiberg55b97fe2016-01-28 05:22:45 -08002269int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2270 int8_t currentLevel = _outputAudioLevel.Level();
2271 level = static_cast<int32_t>(currentLevel);
2272 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002273}
2274
kwiberg55b97fe2016-01-28 05:22:45 -08002275int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2276 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2277 level = static_cast<int32_t>(currentLevel);
2278 return 0;
2279}
2280
solenberg1c2af8e2016-03-24 10:36:00 -07002281int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002282 rtc::CritScope cs(&volume_settings_critsect_);
2283 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002284 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002285 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002286 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002287}
2288
solenberg1c2af8e2016-03-24 10:36:00 -07002289bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002290 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002291 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002292}
2293
kwiberg55b97fe2016-01-28 05:22:45 -08002294int Channel::SetOutputVolumePan(float left, float right) {
2295 rtc::CritScope cs(&volume_settings_critsect_);
2296 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002297 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002298 _panLeft = left;
2299 _panRight = right;
2300 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002301}
2302
kwiberg55b97fe2016-01-28 05:22:45 -08002303int Channel::GetOutputVolumePan(float& left, float& right) const {
2304 rtc::CritScope cs(&volume_settings_critsect_);
2305 left = _panLeft;
2306 right = _panRight;
2307 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002308}
2309
kwiberg55b97fe2016-01-28 05:22:45 -08002310int Channel::SetChannelOutputVolumeScaling(float scaling) {
2311 rtc::CritScope cs(&volume_settings_critsect_);
2312 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002313 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002314 _outputGain = scaling;
2315 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002316}
2317
kwiberg55b97fe2016-01-28 05:22:45 -08002318int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2319 rtc::CritScope cs(&volume_settings_critsect_);
2320 scaling = _outputGain;
2321 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002322}
2323
solenberg8842c3e2016-03-11 03:06:41 -08002324int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002325 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002326 "Channel::SendTelephoneEventOutband(...)");
2327 RTC_DCHECK_LE(0, event);
2328 RTC_DCHECK_GE(255, event);
2329 RTC_DCHECK_LE(0, duration_ms);
2330 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002331 if (!Sending()) {
2332 return -1;
2333 }
solenberg8842c3e2016-03-11 03:06:41 -08002334 if (_rtpRtcpModule->SendTelephoneEventOutband(
2335 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002336 _engineStatisticsPtr->SetLastError(
2337 VE_SEND_DTMF_FAILED, kTraceWarning,
2338 "SendTelephoneEventOutband() failed to send event");
2339 return -1;
2340 }
2341 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002342}
2343
solenbergffbbcac2016-11-17 05:25:37 -08002344int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2345 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002346 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002347 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002348 RTC_DCHECK_LE(0, payload_type);
2349 RTC_DCHECK_GE(127, payload_type);
2350 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002351 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002352 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002353 memcpy(codec.plname, "telephone-event", 16);
2354 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2355 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2356 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2357 _engineStatisticsPtr->SetLastError(
2358 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2359 "SetSendTelephoneEventPayloadType() failed to register send"
2360 "payload type");
2361 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002362 }
kwiberg55b97fe2016-01-28 05:22:45 -08002363 }
kwiberg55b97fe2016-01-28 05:22:45 -08002364 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002365}
2366
kwiberg55b97fe2016-01-28 05:22:45 -08002367int Channel::VoiceActivityIndicator(int& activity) {
2368 activity = _sendFrameType;
2369 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002370}
2371
kwiberg55b97fe2016-01-28 05:22:45 -08002372int Channel::SetLocalSSRC(unsigned int ssrc) {
2373 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2374 "Channel::SetLocalSSRC()");
2375 if (channel_state_.Get().sending) {
2376 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2377 "SetLocalSSRC() already sending");
2378 return -1;
2379 }
2380 _rtpRtcpModule->SetSSRC(ssrc);
2381 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002382}
2383
kwiberg55b97fe2016-01-28 05:22:45 -08002384int Channel::GetLocalSSRC(unsigned int& ssrc) {
2385 ssrc = _rtpRtcpModule->SSRC();
2386 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002387}
2388
kwiberg55b97fe2016-01-28 05:22:45 -08002389int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2390 ssrc = rtp_receiver_->SSRC();
2391 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002392}
2393
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002394int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002395 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002396 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002397}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002398
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002399int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2400 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002401 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2402 if (enable &&
2403 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2404 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002405 return -1;
2406 }
2407 return 0;
2408}
2409
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002410void Channel::EnableSendTransportSequenceNumber(int id) {
2411 int ret =
2412 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2413 RTC_DCHECK_EQ(0, ret);
2414}
2415
stefan3313ec92016-01-21 06:32:43 -08002416void Channel::EnableReceiveTransportSequenceNumber(int id) {
2417 rtp_header_parser_->DeregisterRtpHeaderExtension(
2418 kRtpExtensionTransportSequenceNumber);
2419 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2420 kRtpExtensionTransportSequenceNumber, id);
2421 RTC_DCHECK(ret);
2422}
2423
stefanbba9dec2016-02-01 04:39:55 -08002424void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002425 RtpPacketSender* rtp_packet_sender,
2426 TransportFeedbackObserver* transport_feedback_observer,
2427 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002428 RTC_DCHECK(rtp_packet_sender);
2429 RTC_DCHECK(transport_feedback_observer);
2430 RTC_DCHECK(packet_router && !packet_router_);
2431 feedback_observer_proxy_->SetTransportFeedbackObserver(
2432 transport_feedback_observer);
2433 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2434 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2435 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002436 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002437 packet_router_ = packet_router;
2438}
2439
stefanbba9dec2016-02-01 04:39:55 -08002440void Channel::RegisterReceiverCongestionControlObjects(
2441 PacketRouter* packet_router) {
2442 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002443 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002444 packet_router_ = packet_router;
2445}
2446
2447void Channel::ResetCongestionControlObjects() {
2448 RTC_DCHECK(packet_router_);
2449 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2450 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2451 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002452 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002453 packet_router_ = nullptr;
2454 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2455}
2456
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002457void Channel::SetRTCPStatus(bool enable) {
2458 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2459 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002460 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002461}
2462
kwiberg55b97fe2016-01-28 05:22:45 -08002463int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002464 RtcpMode method = _rtpRtcpModule->RTCP();
2465 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002466 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002467}
2468
kwiberg55b97fe2016-01-28 05:22:45 -08002469int Channel::SetRTCP_CNAME(const char cName[256]) {
2470 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2471 "Channel::SetRTCP_CNAME()");
2472 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2473 _engineStatisticsPtr->SetLastError(
2474 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2475 "SetRTCP_CNAME() failed to set RTCP CNAME");
2476 return -1;
2477 }
2478 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002479}
2480
kwiberg55b97fe2016-01-28 05:22:45 -08002481int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2482 if (cName == NULL) {
2483 _engineStatisticsPtr->SetLastError(
2484 VE_INVALID_ARGUMENT, kTraceError,
2485 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2486 return -1;
2487 }
2488 char cname[RTCP_CNAME_SIZE];
2489 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2490 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2491 _engineStatisticsPtr->SetLastError(
2492 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2493 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2494 return -1;
2495 }
2496 strcpy(cName, cname);
2497 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002498}
2499
kwiberg55b97fe2016-01-28 05:22:45 -08002500int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2501 unsigned int& NTPLow,
2502 unsigned int& timestamp,
2503 unsigned int& playoutTimestamp,
2504 unsigned int* jitter,
2505 unsigned short* fractionLost) {
2506 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002507
kwiberg55b97fe2016-01-28 05:22:45 -08002508 RTCPSenderInfo senderInfo;
2509 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2510 _engineStatisticsPtr->SetLastError(
2511 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2512 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2513 "side");
2514 return -1;
2515 }
2516
2517 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2518 // and octet count)
2519 NTPHigh = senderInfo.NTPseconds;
2520 NTPLow = senderInfo.NTPfraction;
2521 timestamp = senderInfo.RTPtimeStamp;
2522
2523 // --- Locally derived information
2524
2525 // This value is updated on each incoming RTCP packet (0 when no packet
2526 // has been received)
2527 playoutTimestamp = playout_timestamp_rtcp_;
2528
2529 if (NULL != jitter || NULL != fractionLost) {
2530 // Get all RTCP receiver report blocks that have been received on this
2531 // channel. If we receive RTP packets from a remote source we know the
2532 // remote SSRC and use the report block from him.
2533 // Otherwise use the first report block.
2534 std::vector<RTCPReportBlock> remote_stats;
2535 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2536 remote_stats.empty()) {
2537 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2538 "GetRemoteRTCPData() failed to measure statistics due"
2539 " to lack of received RTP and/or RTCP packets");
2540 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002541 }
2542
kwiberg55b97fe2016-01-28 05:22:45 -08002543 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2544 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2545 for (; it != remote_stats.end(); ++it) {
2546 if (it->remoteSSRC == remoteSSRC)
2547 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002548 }
kwiberg55b97fe2016-01-28 05:22:45 -08002549
2550 if (it == remote_stats.end()) {
2551 // If we have not received any RTCP packets from this SSRC it probably
2552 // means that we have not received any RTP packets.
2553 // Use the first received report block instead.
2554 it = remote_stats.begin();
2555 remoteSSRC = it->remoteSSRC;
2556 }
2557
2558 if (jitter) {
2559 *jitter = it->jitter;
2560 }
2561
2562 if (fractionLost) {
2563 *fractionLost = it->fractionLost;
2564 }
2565 }
2566 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002567}
2568
kwiberg55b97fe2016-01-28 05:22:45 -08002569int Channel::SendApplicationDefinedRTCPPacket(
2570 unsigned char subType,
2571 unsigned int name,
2572 const char* data,
2573 unsigned short dataLengthInBytes) {
2574 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2575 "Channel::SendApplicationDefinedRTCPPacket()");
2576 if (!channel_state_.Get().sending) {
2577 _engineStatisticsPtr->SetLastError(
2578 VE_NOT_SENDING, kTraceError,
2579 "SendApplicationDefinedRTCPPacket() not sending");
2580 return -1;
2581 }
2582 if (NULL == data) {
2583 _engineStatisticsPtr->SetLastError(
2584 VE_INVALID_ARGUMENT, kTraceError,
2585 "SendApplicationDefinedRTCPPacket() invalid data value");
2586 return -1;
2587 }
2588 if (dataLengthInBytes % 4 != 0) {
2589 _engineStatisticsPtr->SetLastError(
2590 VE_INVALID_ARGUMENT, kTraceError,
2591 "SendApplicationDefinedRTCPPacket() invalid length value");
2592 return -1;
2593 }
2594 RtcpMode status = _rtpRtcpModule->RTCP();
2595 if (status == RtcpMode::kOff) {
2596 _engineStatisticsPtr->SetLastError(
2597 VE_RTCP_ERROR, kTraceError,
2598 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2599 return -1;
2600 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002601
kwiberg55b97fe2016-01-28 05:22:45 -08002602 // Create and schedule the RTCP APP packet for transmission
2603 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2604 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2605 _engineStatisticsPtr->SetLastError(
2606 VE_SEND_ERROR, kTraceError,
2607 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2608 return -1;
2609 }
2610 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002611}
2612
kwiberg55b97fe2016-01-28 05:22:45 -08002613int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2614 unsigned int& maxJitterMs,
2615 unsigned int& discardedPackets) {
2616 // The jitter statistics is updated for each received RTP packet and is
2617 // based on received packets.
2618 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2619 // If RTCP is off, there is no timed thread in the RTCP module regularly
2620 // generating new stats, trigger the update manually here instead.
2621 StreamStatistician* statistician =
2622 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2623 if (statistician) {
2624 // Don't use returned statistics, use data from proxy instead so that
2625 // max jitter can be fetched atomically.
2626 RtcpStatistics s;
2627 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002628 }
kwiberg55b97fe2016-01-28 05:22:45 -08002629 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002630
kwiberg55b97fe2016-01-28 05:22:45 -08002631 ChannelStatistics stats = statistics_proxy_->GetStats();
2632 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2633 if (playoutFrequency > 0) {
2634 // Scale RTP statistics given the current playout frequency
2635 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2636 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2637 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002638
kwiberg55b97fe2016-01-28 05:22:45 -08002639 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002640
kwiberg55b97fe2016-01-28 05:22:45 -08002641 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002642}
2643
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002644int Channel::GetRemoteRTCPReportBlocks(
2645 std::vector<ReportBlock>* report_blocks) {
2646 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002647 _engineStatisticsPtr->SetLastError(
2648 VE_INVALID_ARGUMENT, kTraceError,
2649 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002650 return -1;
2651 }
2652
2653 // Get the report blocks from the latest received RTCP Sender or Receiver
2654 // Report. Each element in the vector contains the sender's SSRC and a
2655 // report block according to RFC 3550.
2656 std::vector<RTCPReportBlock> rtcp_report_blocks;
2657 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002658 return -1;
2659 }
2660
2661 if (rtcp_report_blocks.empty())
2662 return 0;
2663
2664 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2665 for (; it != rtcp_report_blocks.end(); ++it) {
2666 ReportBlock report_block;
2667 report_block.sender_SSRC = it->remoteSSRC;
2668 report_block.source_SSRC = it->sourceSSRC;
2669 report_block.fraction_lost = it->fractionLost;
2670 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2671 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2672 report_block.interarrival_jitter = it->jitter;
2673 report_block.last_SR_timestamp = it->lastSR;
2674 report_block.delay_since_last_SR = it->delaySinceLastSR;
2675 report_blocks->push_back(report_block);
2676 }
2677 return 0;
2678}
2679
kwiberg55b97fe2016-01-28 05:22:45 -08002680int Channel::GetRTPStatistics(CallStatistics& stats) {
2681 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002682
kwiberg55b97fe2016-01-28 05:22:45 -08002683 // The jitter statistics is updated for each received RTP packet and is
2684 // based on received packets.
2685 RtcpStatistics statistics;
2686 StreamStatistician* statistician =
2687 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002688 if (statistician) {
2689 statistician->GetStatistics(&statistics,
2690 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002691 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002692
kwiberg55b97fe2016-01-28 05:22:45 -08002693 stats.fractionLost = statistics.fraction_lost;
2694 stats.cumulativeLost = statistics.cumulative_lost;
2695 stats.extendedMax = statistics.extended_max_sequence_number;
2696 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002697
kwiberg55b97fe2016-01-28 05:22:45 -08002698 // --- RTT
2699 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002700
kwiberg55b97fe2016-01-28 05:22:45 -08002701 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002702
kwiberg55b97fe2016-01-28 05:22:45 -08002703 size_t bytesSent(0);
2704 uint32_t packetsSent(0);
2705 size_t bytesReceived(0);
2706 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002707
kwiberg55b97fe2016-01-28 05:22:45 -08002708 if (statistician) {
2709 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2710 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002711
kwiberg55b97fe2016-01-28 05:22:45 -08002712 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2713 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2714 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2715 " output will not be complete");
2716 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002717
kwiberg55b97fe2016-01-28 05:22:45 -08002718 stats.bytesSent = bytesSent;
2719 stats.packetsSent = packetsSent;
2720 stats.bytesReceived = bytesReceived;
2721 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002722
kwiberg55b97fe2016-01-28 05:22:45 -08002723 // --- Timestamps
2724 {
2725 rtc::CritScope lock(&ts_stats_lock_);
2726 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2727 }
2728 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002729}
2730
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002731int Channel::SetCodecFECStatus(bool enable) {
2732 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2733 "Channel::SetCodecFECStatus()");
2734
kwibergc8d071e2016-04-06 12:22:38 -07002735 if (!codec_manager_.SetCodecFEC(enable) ||
2736 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002737 _engineStatisticsPtr->SetLastError(
2738 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2739 "SetCodecFECStatus() failed to set FEC state");
2740 return -1;
2741 }
2742 return 0;
2743}
2744
2745bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002746 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002747}
2748
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002749void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2750 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002751 // If pacing is enabled we always store packets.
2752 if (!pacing_enabled_)
2753 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002754 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002755 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002756 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002757 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002758 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002759}
2760
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002761// Called when we are missing one or more packets.
2762int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002763 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2764}
2765
kwiberg55b97fe2016-01-28 05:22:45 -08002766uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2767 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2768 "Channel::Demultiplex()");
2769 _audioFrame.CopyFrom(audioFrame);
2770 _audioFrame.id_ = _channelId;
2771 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002772}
2773
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002774void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002775 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002776 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002777 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002778 CodecInst codec;
2779 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002780
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002781 // Never upsample or upmix the capture signal here. This should be done at the
2782 // end of the send chain.
2783 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2784 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2785 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2786 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002787}
2788
kwiberg55b97fe2016-01-28 05:22:45 -08002789uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2790 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2791 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002792
kwiberg55b97fe2016-01-28 05:22:45 -08002793 if (_audioFrame.samples_per_channel_ == 0) {
2794 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2795 "Channel::PrepareEncodeAndSend() invalid audio frame");
2796 return 0xFFFFFFFF;
2797 }
2798
2799 if (channel_state_.Get().input_file_playing) {
2800 MixOrReplaceAudioWithFile(mixingFrequency);
2801 }
2802
solenberg1c2af8e2016-03-24 10:36:00 -07002803 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2804 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002805
2806 if (channel_state_.Get().input_external_media) {
2807 rtc::CritScope cs(&_callbackCritSect);
2808 const bool isStereo = (_audioFrame.num_channels_ == 2);
2809 if (_inputExternalMediaCallbackPtr) {
2810 _inputExternalMediaCallbackPtr->Process(
2811 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2812 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2813 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002814 }
kwiberg55b97fe2016-01-28 05:22:45 -08002815 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002816
kwiberg55b97fe2016-01-28 05:22:45 -08002817 if (_includeAudioLevelIndication) {
2818 size_t length =
2819 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002820 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002821 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002822 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002823 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002824 rms_level_.Analyze(
2825 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002826 }
kwiberg55b97fe2016-01-28 05:22:45 -08002827 }
solenberg1c2af8e2016-03-24 10:36:00 -07002828 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002829
kwiberg55b97fe2016-01-28 05:22:45 -08002830 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002831}
2832
kwiberg55b97fe2016-01-28 05:22:45 -08002833uint32_t Channel::EncodeAndSend() {
2834 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2835 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002836
kwiberg55b97fe2016-01-28 05:22:45 -08002837 assert(_audioFrame.num_channels_ <= 2);
2838 if (_audioFrame.samples_per_channel_ == 0) {
2839 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2840 "Channel::EncodeAndSend() invalid audio frame");
2841 return 0xFFFFFFFF;
2842 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002843
kwiberg55b97fe2016-01-28 05:22:45 -08002844 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002845
kwiberg55b97fe2016-01-28 05:22:45 -08002846 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002847
kwiberg55b97fe2016-01-28 05:22:45 -08002848 // The ACM resamples internally.
2849 _audioFrame.timestamp_ = _timeStamp;
2850 // This call will trigger AudioPacketizationCallback::SendData if encoding
2851 // is done and payload is ready for packetization and transmission.
2852 // Otherwise, it will return without invoking the callback.
2853 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2854 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2855 "Channel::EncodeAndSend() ACM encoding failed");
2856 return 0xFFFFFFFF;
2857 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002858
kwiberg55b97fe2016-01-28 05:22:45 -08002859 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2860 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002861}
2862
solenberg7602aab2016-11-14 11:30:07 -08002863void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2864 RTC_DCHECK(!channel.channel() ||
2865 channel.channel()->ChannelId() != _channelId);
2866 rtc::CritScope lock(&assoc_send_channel_lock_);
2867 associate_send_channel_ = channel;
2868}
2869
Minyue2013aec2015-05-13 14:14:42 +02002870void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002871 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002872 Channel* channel = associate_send_channel_.channel();
2873 if (channel && channel->ChannelId() == channel_id) {
2874 // If this channel is associated with a send channel of the specified
2875 // Channel ID, disassociate with it.
2876 ChannelOwner ref(NULL);
2877 associate_send_channel_ = ref;
2878 }
2879}
2880
ivoc14d5dbe2016-07-04 07:06:55 -07002881void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2882 event_log_proxy_->SetEventLog(event_log);
2883}
2884
michaelt9332b7d2016-11-30 07:51:13 -08002885void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2886 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2887}
2888
nisse284542b2017-01-10 08:58:32 -08002889void Channel::UpdateOverheadForEncoder() {
2890 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2891 if (*encoder) {
2892 (*encoder)->OnReceivedOverhead(transport_overhead_per_packet_ +
2893 rtp_overhead_per_packet_);
2894 }
2895 });
2896}
2897
2898void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
2899 transport_overhead_per_packet_ = transport_overhead_per_packet;
2900 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002901}
2902
michaeltbf65be52016-12-15 06:24:49 -08002903void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
nisse284542b2017-01-10 08:58:32 -08002904 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2905 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002906}
2907
kwiberg55b97fe2016-01-28 05:22:45 -08002908int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
2909 VoEMediaProcess& processObject) {
2910 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2911 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002912
kwiberg55b97fe2016-01-28 05:22:45 -08002913 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002914
kwiberg55b97fe2016-01-28 05:22:45 -08002915 if (kPlaybackPerChannel == type) {
2916 if (_outputExternalMediaCallbackPtr) {
2917 _engineStatisticsPtr->SetLastError(
2918 VE_INVALID_OPERATION, kTraceError,
2919 "Channel::RegisterExternalMediaProcessing() "
2920 "output external media already enabled");
2921 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002922 }
kwiberg55b97fe2016-01-28 05:22:45 -08002923 _outputExternalMediaCallbackPtr = &processObject;
2924 _outputExternalMedia = true;
2925 } else if (kRecordingPerChannel == type) {
2926 if (_inputExternalMediaCallbackPtr) {
2927 _engineStatisticsPtr->SetLastError(
2928 VE_INVALID_OPERATION, kTraceError,
2929 "Channel::RegisterExternalMediaProcessing() "
2930 "output external media already enabled");
2931 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002932 }
kwiberg55b97fe2016-01-28 05:22:45 -08002933 _inputExternalMediaCallbackPtr = &processObject;
2934 channel_state_.SetInputExternalMedia(true);
2935 }
2936 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002937}
2938
kwiberg55b97fe2016-01-28 05:22:45 -08002939int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
2940 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2941 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002942
kwiberg55b97fe2016-01-28 05:22:45 -08002943 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002944
kwiberg55b97fe2016-01-28 05:22:45 -08002945 if (kPlaybackPerChannel == type) {
2946 if (!_outputExternalMediaCallbackPtr) {
2947 _engineStatisticsPtr->SetLastError(
2948 VE_INVALID_OPERATION, kTraceWarning,
2949 "Channel::DeRegisterExternalMediaProcessing() "
2950 "output external media already disabled");
2951 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002952 }
kwiberg55b97fe2016-01-28 05:22:45 -08002953 _outputExternalMedia = false;
2954 _outputExternalMediaCallbackPtr = NULL;
2955 } else if (kRecordingPerChannel == type) {
2956 if (!_inputExternalMediaCallbackPtr) {
2957 _engineStatisticsPtr->SetLastError(
2958 VE_INVALID_OPERATION, kTraceWarning,
2959 "Channel::DeRegisterExternalMediaProcessing() "
2960 "input external media already disabled");
2961 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002962 }
kwiberg55b97fe2016-01-28 05:22:45 -08002963 channel_state_.SetInputExternalMedia(false);
2964 _inputExternalMediaCallbackPtr = NULL;
2965 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002966
kwiberg55b97fe2016-01-28 05:22:45 -08002967 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002968}
2969
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002970int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08002971 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2972 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002973
kwiberg55b97fe2016-01-28 05:22:45 -08002974 if (channel_state_.Get().playing) {
2975 _engineStatisticsPtr->SetLastError(
2976 VE_INVALID_OPERATION, kTraceError,
2977 "Channel::SetExternalMixing() "
2978 "external mixing cannot be changed while playing.");
2979 return -1;
2980 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002981
kwiberg55b97fe2016-01-28 05:22:45 -08002982 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002983
kwiberg55b97fe2016-01-28 05:22:45 -08002984 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002985}
2986
kwiberg55b97fe2016-01-28 05:22:45 -08002987int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2988 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002989}
2990
wu@webrtc.org24301a62013-12-13 19:17:43 +00002991void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2992 audio_coding_->GetDecodingCallStatistics(stats);
2993}
2994
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002995bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
2996 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08002997 rtc::CritScope lock(&video_sync_lock_);
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07002998 *jitter_buffer_delay_ms = audio_coding_->FilteredCurrentDelayMs();
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002999 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003000 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003001}
3002
solenberg358057b2015-11-27 10:46:42 -08003003uint32_t Channel::GetDelayEstimate() const {
3004 int jitter_buffer_delay_ms = 0;
3005 int playout_buffer_delay_ms = 0;
3006 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3007 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3008}
3009
deadbeef74375882015-08-13 12:09:10 -07003010int Channel::LeastRequiredDelayMs() const {
3011 return audio_coding_->LeastRequiredDelayMs();
3012}
3013
kwiberg55b97fe2016-01-28 05:22:45 -08003014int Channel::SetMinimumPlayoutDelay(int delayMs) {
3015 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3016 "Channel::SetMinimumPlayoutDelay()");
3017 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3018 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3019 _engineStatisticsPtr->SetLastError(
3020 VE_INVALID_ARGUMENT, kTraceError,
3021 "SetMinimumPlayoutDelay() invalid min delay");
3022 return -1;
3023 }
3024 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3025 _engineStatisticsPtr->SetLastError(
3026 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3027 "SetMinimumPlayoutDelay() failed to set min playout delay");
3028 return -1;
3029 }
3030 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003031}
3032
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003033int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003034 uint32_t playout_timestamp_rtp = 0;
3035 {
tommi31fc21f2016-01-21 10:37:37 -08003036 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003037 playout_timestamp_rtp = playout_timestamp_rtp_;
3038 }
kwiberg55b97fe2016-01-28 05:22:45 -08003039 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003040 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07003041 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003042 "GetPlayoutTimestamp() failed to retrieve timestamp");
3043 return -1;
3044 }
deadbeef74375882015-08-13 12:09:10 -07003045 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003046 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003047}
3048
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003049int Channel::SetInitTimestamp(unsigned int timestamp) {
3050 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003051 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003052 if (channel_state_.Get().sending) {
3053 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3054 "SetInitTimestamp() already sending");
3055 return -1;
3056 }
3057 _rtpRtcpModule->SetStartTimestamp(timestamp);
3058 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003059}
3060
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003061int Channel::SetInitSequenceNumber(short sequenceNumber) {
3062 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3063 "Channel::SetInitSequenceNumber()");
3064 if (channel_state_.Get().sending) {
3065 _engineStatisticsPtr->SetLastError(
3066 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3067 return -1;
3068 }
3069 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3070 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003071}
3072
kwiberg55b97fe2016-01-28 05:22:45 -08003073int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3074 RtpReceiver** rtp_receiver) const {
3075 *rtpRtcpModule = _rtpRtcpModule.get();
3076 *rtp_receiver = rtp_receiver_.get();
3077 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003078}
3079
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003080// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3081// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003082int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003083 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003084 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003085
kwiberg55b97fe2016-01-28 05:22:45 -08003086 {
3087 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003088
kwiberg5a25d952016-08-17 07:31:12 -07003089 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003090 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3091 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3092 " doesnt exist");
3093 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003094 }
3095
kwiberg4ec01d92016-08-22 08:43:54 -07003096 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07003097 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003098 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3099 "Channel::MixOrReplaceAudioWithFile() file mixing "
3100 "failed");
3101 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003102 }
kwiberg55b97fe2016-01-28 05:22:45 -08003103 if (fileSamples == 0) {
3104 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3105 "Channel::MixOrReplaceAudioWithFile() file is ended");
3106 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003107 }
kwiberg55b97fe2016-01-28 05:22:45 -08003108 }
3109
3110 assert(_audioFrame.samples_per_channel_ == fileSamples);
3111
3112 if (_mixFileWithMicrophone) {
3113 // Currently file stream is always mono.
3114 // TODO(xians): Change the code when FilePlayer supports real stereo.
3115 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3116 1, fileSamples);
3117 } else {
3118 // Replace ACM audio with file.
3119 // Currently file stream is always mono.
3120 // TODO(xians): Change the code when FilePlayer supports real stereo.
3121 _audioFrame.UpdateFrame(
3122 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3123 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3124 }
3125 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003126}
3127
kwiberg55b97fe2016-01-28 05:22:45 -08003128int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3129 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003130
kwibergb7f89d62016-02-17 10:04:18 -08003131 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003132 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003133
kwiberg55b97fe2016-01-28 05:22:45 -08003134 {
3135 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003136
kwiberg5a25d952016-08-17 07:31:12 -07003137 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003138 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3139 "Channel::MixAudioWithFile() file mixing failed");
3140 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003141 }
3142
kwiberg55b97fe2016-01-28 05:22:45 -08003143 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07003144 if (output_file_player_->Get10msAudioFromFile(
3145 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003146 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3147 "Channel::MixAudioWithFile() file mixing failed");
3148 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003149 }
kwiberg55b97fe2016-01-28 05:22:45 -08003150 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003151
kwiberg55b97fe2016-01-28 05:22:45 -08003152 if (audioFrame.samples_per_channel_ == fileSamples) {
3153 // Currently file stream is always mono.
3154 // TODO(xians): Change the code when FilePlayer supports real stereo.
3155 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3156 fileSamples);
3157 } else {
3158 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3159 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3160 ") != "
3161 "fileSamples(%" PRIuS ")",
3162 audioFrame.samples_per_channel_, fileSamples);
3163 return -1;
3164 }
3165
3166 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003167}
3168
deadbeef74375882015-08-13 12:09:10 -07003169void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003170 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003171
henrik.lundin96bd5022016-04-06 04:13:56 -07003172 if (!jitter_buffer_playout_timestamp_) {
3173 // This can happen if this channel has not received any RTP packets. In
3174 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003175 return;
3176 }
3177
3178 uint16_t delay_ms = 0;
3179 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003180 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003181 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3182 " delay from the ADM");
3183 _engineStatisticsPtr->SetLastError(
3184 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3185 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3186 return;
3187 }
3188
henrik.lundin96bd5022016-04-06 04:13:56 -07003189 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3190 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003191
3192 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003193 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003194
kwiberg55b97fe2016-01-28 05:22:45 -08003195 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003196 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003197 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003198
3199 {
tommi31fc21f2016-01-21 10:37:37 -08003200 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003201 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003202 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003203 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003204 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003205 }
3206 playout_delay_ms_ = delay_ms;
3207 }
3208}
3209
kwiberg55b97fe2016-01-28 05:22:45 -08003210void Channel::RegisterReceiveCodecsToRTPModule() {
3211 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3212 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003213
kwiberg55b97fe2016-01-28 05:22:45 -08003214 CodecInst codec;
3215 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003216
kwiberg55b97fe2016-01-28 05:22:45 -08003217 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3218 // Open up the RTP/RTCP receiver for all supported codecs
3219 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003220 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003221 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3222 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3223 " to register %s (%d/%d/%" PRIuS
3224 "/%d) to RTP/RTCP "
3225 "receiver",
3226 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3227 codec.rate);
3228 } else {
3229 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3230 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3231 "(%d/%d/%" PRIuS
3232 "/%d) has been added to the RTP/RTCP "
3233 "receiver",
3234 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3235 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003236 }
kwiberg55b97fe2016-01-28 05:22:45 -08003237 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003238}
3239
kwiberg55b97fe2016-01-28 05:22:45 -08003240int Channel::SetSendRtpHeaderExtension(bool enable,
3241 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003242 unsigned char id) {
3243 int error = 0;
3244 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3245 if (enable) {
3246 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3247 }
3248 return error;
3249}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003250
ossue280cde2016-10-12 11:04:10 -07003251int Channel::GetRtpTimestampRateHz() const {
3252 const auto format = audio_coding_->ReceiveFormat();
3253 // Default to the playout frequency if we've not gotten any packets yet.
3254 // TODO(ossu): Zero clockrate can only happen if we've added an external
3255 // decoder for a format we don't support internally. Remove once that way of
3256 // adding decoders is gone!
3257 return (format && format->clockrate_hz != 0)
3258 ? format->clockrate_hz
3259 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003260}
3261
Minyue2013aec2015-05-13 14:14:42 +02003262int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003263 RtcpMode method = _rtpRtcpModule->RTCP();
3264 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003265 return 0;
3266 }
3267 std::vector<RTCPReportBlock> report_blocks;
3268 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003269
3270 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003271 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003272 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003273 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003274 Channel* channel = associate_send_channel_.channel();
3275 // Tries to get RTT from an associated channel. This is important for
3276 // receive-only channels.
3277 if (channel) {
3278 // To prevent infinite recursion and deadlock, calling GetRTT of
3279 // associate channel should always use "false" for argument:
3280 // |allow_associate_channel|.
3281 rtt = channel->GetRTT(false);
3282 }
3283 }
3284 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003285 }
3286
3287 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3288 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3289 for (; it != report_blocks.end(); ++it) {
3290 if (it->remoteSSRC == remoteSSRC)
3291 break;
3292 }
3293 if (it == report_blocks.end()) {
3294 // We have not received packets with SSRC matching the report blocks.
3295 // To calculate RTT we try with the SSRC of the first report block.
3296 // This is very important for send-only channels where we don't know
3297 // the SSRC of the other end.
3298 remoteSSRC = report_blocks[0].remoteSSRC;
3299 }
Minyue2013aec2015-05-13 14:14:42 +02003300
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003301 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003302 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003303 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003304 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3305 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003306 return 0;
3307 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003308 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003309}
3310
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003311} // namespace voe
3312} // namespace webrtc