blob: 100832de3adeb2dc986cd255dc271a109ea6bbb7 [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
143 void SetEventLog(RtcEventLog* event_log) {
144 rtc::CritScope lock(&crit_);
145 event_log_ = event_log;
146 }
147
148 private:
149 rtc::CriticalSection crit_;
150 RtcEventLog* event_log_ GUARDED_BY(crit_);
151 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
152};
153
michaelt9332b7d2016-11-30 07:51:13 -0800154class RtcpRttStatsProxy final : public RtcpRttStats {
155 public:
156 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
157
158 void OnRttUpdate(int64_t rtt) override {
159 rtc::CritScope lock(&crit_);
160 if (rtcp_rtt_stats_)
161 rtcp_rtt_stats_->OnRttUpdate(rtt);
162 }
163
164 int64_t LastProcessedRtt() const override {
165 rtc::CritScope lock(&crit_);
166 if (!rtcp_rtt_stats_)
167 return 0;
168 return rtcp_rtt_stats_->LastProcessedRtt();
169 }
170
171 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
172 rtc::CritScope lock(&crit_);
173 rtcp_rtt_stats_ = rtcp_rtt_stats;
174 }
175
176 private:
177 rtc::CriticalSection crit_;
178 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
179 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
180};
181
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100182class TransportFeedbackProxy : public TransportFeedbackObserver {
183 public:
184 TransportFeedbackProxy() : feedback_observer_(nullptr) {
185 pacer_thread_.DetachFromThread();
186 network_thread_.DetachFromThread();
187 }
188
189 void SetTransportFeedbackObserver(
190 TransportFeedbackObserver* feedback_observer) {
191 RTC_DCHECK(thread_checker_.CalledOnValidThread());
192 rtc::CritScope lock(&crit_);
193 feedback_observer_ = feedback_observer;
194 }
195
196 // Implements TransportFeedbackObserver.
197 void AddPacket(uint16_t sequence_number,
198 size_t length,
philipela1ed0b32016-06-01 06:31:17 -0700199 int probe_cluster_id) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100200 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
201 rtc::CritScope lock(&crit_);
202 if (feedback_observer_)
pbos2169d8b2016-06-20 11:53:02 -0700203 feedback_observer_->AddPacket(sequence_number, length, probe_cluster_id);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100204 }
205 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
206 RTC_DCHECK(network_thread_.CalledOnValidThread());
207 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700208 if (feedback_observer_)
209 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200210 }
211 std::vector<PacketInfo> GetTransportFeedbackVector() const override {
212 RTC_NOTREACHED();
213 return std::vector<PacketInfo>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100214 }
215
216 private:
217 rtc::CriticalSection crit_;
218 rtc::ThreadChecker thread_checker_;
219 rtc::ThreadChecker pacer_thread_;
220 rtc::ThreadChecker network_thread_;
221 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
222};
223
224class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
225 public:
226 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
227 pacer_thread_.DetachFromThread();
228 }
229
230 void SetSequenceNumberAllocator(
231 TransportSequenceNumberAllocator* seq_num_allocator) {
232 RTC_DCHECK(thread_checker_.CalledOnValidThread());
233 rtc::CritScope lock(&crit_);
234 seq_num_allocator_ = seq_num_allocator;
235 }
236
237 // Implements TransportSequenceNumberAllocator.
238 uint16_t AllocateSequenceNumber() override {
239 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
240 rtc::CritScope lock(&crit_);
241 if (!seq_num_allocator_)
242 return 0;
243 return seq_num_allocator_->AllocateSequenceNumber();
244 }
245
246 private:
247 rtc::CriticalSection crit_;
248 rtc::ThreadChecker thread_checker_;
249 rtc::ThreadChecker pacer_thread_;
250 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
251};
252
253class RtpPacketSenderProxy : public RtpPacketSender {
254 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800255 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100256
257 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
258 RTC_DCHECK(thread_checker_.CalledOnValidThread());
259 rtc::CritScope lock(&crit_);
260 rtp_packet_sender_ = rtp_packet_sender;
261 }
262
263 // Implements RtpPacketSender.
264 void InsertPacket(Priority priority,
265 uint32_t ssrc,
266 uint16_t sequence_number,
267 int64_t capture_time_ms,
268 size_t bytes,
269 bool retransmission) override {
270 rtc::CritScope lock(&crit_);
271 if (rtp_packet_sender_) {
272 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
273 capture_time_ms, bytes, retransmission);
274 }
275 }
276
277 private:
278 rtc::ThreadChecker thread_checker_;
279 rtc::CriticalSection crit_;
280 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
281};
282
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000283// Extend the default RTCP statistics struct with max_jitter, defined as the
284// maximum jitter value seen in an RTCP report block.
285struct ChannelStatistics : public RtcpStatistics {
286 ChannelStatistics() : rtcp(), max_jitter(0) {}
287
288 RtcpStatistics rtcp;
289 uint32_t max_jitter;
290};
291
292// Statistics callback, called at each generation of a new RTCP report block.
293class StatisticsProxy : public RtcpStatisticsCallback {
294 public:
tommi31fc21f2016-01-21 10:37:37 -0800295 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000296 virtual ~StatisticsProxy() {}
297
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000298 void StatisticsUpdated(const RtcpStatistics& statistics,
299 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000300 if (ssrc != ssrc_)
301 return;
302
tommi31fc21f2016-01-21 10:37:37 -0800303 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000304 stats_.rtcp = statistics;
305 if (statistics.jitter > stats_.max_jitter) {
306 stats_.max_jitter = statistics.jitter;
307 }
308 }
309
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000310 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000311
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000312 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800313 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000314 return stats_;
315 }
316
317 private:
318 // StatisticsUpdated calls are triggered from threads in the RTP module,
319 // while GetStats calls can be triggered from the public voice engine API,
320 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800321 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000322 const uint32_t ssrc_;
323 ChannelStatistics stats_;
324};
325
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000326class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000327 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000328 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
329 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000330
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000331 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
332 // Not used for Voice Engine.
333 }
334
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000335 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
336 int64_t rtt,
337 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000338 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
339 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
340 // report for VoiceEngine?
341 if (report_blocks.empty())
342 return;
343
344 int fraction_lost_aggregate = 0;
345 int total_number_of_packets = 0;
346
347 // If receiving multiple report blocks, calculate the weighted average based
348 // on the number of packets a report refers to.
349 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
350 block_it != report_blocks.end(); ++block_it) {
351 // Find the previous extended high sequence number for this remote SSRC,
352 // to calculate the number of RTP packets this report refers to. Ignore if
353 // we haven't seen this SSRC before.
354 std::map<uint32_t, uint32_t>::iterator seq_num_it =
355 extended_max_sequence_number_.find(block_it->sourceSSRC);
356 int number_of_packets = 0;
357 if (seq_num_it != extended_max_sequence_number_.end()) {
358 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
359 }
360 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
361 total_number_of_packets += number_of_packets;
362
363 extended_max_sequence_number_[block_it->sourceSSRC] =
364 block_it->extendedHighSeqNum;
365 }
366 int weighted_fraction_lost = 0;
367 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800368 weighted_fraction_lost =
369 (fraction_lost_aggregate + total_number_of_packets / 2) /
370 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000371 }
372 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000373 }
374
375 private:
376 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000377 // Maps remote side ssrc to extended highest sequence number received.
378 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000379};
380
kwiberg55b97fe2016-01-28 05:22:45 -0800381int32_t Channel::SendData(FrameType frameType,
382 uint8_t payloadType,
383 uint32_t timeStamp,
384 const uint8_t* payloadData,
385 size_t payloadSize,
386 const RTPFragmentationHeader* fragmentation) {
387 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
388 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
389 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
390 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000391
kwiberg55b97fe2016-01-28 05:22:45 -0800392 if (_includeAudioLevelIndication) {
393 // Store current audio level in the RTP/RTCP module.
394 // The level will be used in combination with voice-activity state
395 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800396 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800397 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000398
kwiberg55b97fe2016-01-28 05:22:45 -0800399 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
400 // packetization.
401 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700402 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800403 (FrameType&)frameType, payloadType, timeStamp,
404 // Leaving the time when this frame was
405 // received from the capture device as
406 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700407 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800408 _engineStatisticsPtr->SetLastError(
409 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
410 "Channel::SendData() failed to send data to RTP/RTCP module");
411 return -1;
412 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000413
kwiberg55b97fe2016-01-28 05:22:45 -0800414 _lastLocalTimeStamp = timeStamp;
415 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000416
kwiberg55b97fe2016-01-28 05:22:45 -0800417 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000418}
419
kwiberg55b97fe2016-01-28 05:22:45 -0800420int32_t Channel::InFrameType(FrameType frame_type) {
421 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
422 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000423
kwiberg55b97fe2016-01-28 05:22:45 -0800424 rtc::CritScope cs(&_callbackCritSect);
425 _sendFrameType = (frame_type == kAudioFrameSpeech);
426 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000427}
428
stefan1d8a5062015-10-02 03:39:33 -0700429bool Channel::SendRtp(const uint8_t* data,
430 size_t len,
431 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800432 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
433 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000434
kwiberg55b97fe2016-01-28 05:22:45 -0800435 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000436
kwiberg55b97fe2016-01-28 05:22:45 -0800437 if (_transportPtr == NULL) {
438 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
439 "Channel::SendPacket() failed to send RTP packet due to"
440 " invalid transport object");
441 return false;
442 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000443
kwiberg55b97fe2016-01-28 05:22:45 -0800444 uint8_t* bufferToSendPtr = (uint8_t*)data;
445 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000446
kwiberg55b97fe2016-01-28 05:22:45 -0800447 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
448 std::string transport_name =
449 _externalTransport ? "external transport" : "WebRtc sockets";
450 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
451 "Channel::SendPacket() RTP transmission using %s failed",
452 transport_name.c_str());
453 return false;
454 }
455 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000456}
457
kwiberg55b97fe2016-01-28 05:22:45 -0800458bool Channel::SendRtcp(const uint8_t* data, size_t len) {
459 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
460 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000461
kwiberg55b97fe2016-01-28 05:22:45 -0800462 rtc::CritScope cs(&_callbackCritSect);
463 if (_transportPtr == NULL) {
464 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
465 "Channel::SendRtcp() failed to send RTCP packet"
466 " due to invalid transport object");
467 return false;
468 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000469
kwiberg55b97fe2016-01-28 05:22:45 -0800470 uint8_t* bufferToSendPtr = (uint8_t*)data;
471 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000472
kwiberg55b97fe2016-01-28 05:22:45 -0800473 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
474 if (n < 0) {
475 std::string transport_name =
476 _externalTransport ? "external transport" : "WebRtc sockets";
477 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
478 "Channel::SendRtcp() transmission using %s failed",
479 transport_name.c_str());
480 return false;
481 }
482 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000483}
484
kwiberg55b97fe2016-01-28 05:22:45 -0800485void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
486 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
487 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000488
kwiberg55b97fe2016-01-28 05:22:45 -0800489 // Update ssrc so that NTP for AV sync can be updated.
490 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000491}
492
Peter Boströmac547a62015-09-17 23:03:57 +0200493void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
494 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
495 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
496 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000497}
498
Peter Boströmac547a62015-09-17 23:03:57 +0200499int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000500 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000501 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000502 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800503 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200504 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800505 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
506 "Channel::OnInitializeDecoder(payloadType=%d, "
507 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
508 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000509
kwiberg55b97fe2016-01-28 05:22:45 -0800510 CodecInst receiveCodec = {0};
511 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000512
kwiberg55b97fe2016-01-28 05:22:45 -0800513 receiveCodec.pltype = payloadType;
514 receiveCodec.plfreq = frequency;
515 receiveCodec.channels = channels;
516 receiveCodec.rate = rate;
517 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000518
kwiberg55b97fe2016-01-28 05:22:45 -0800519 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
520 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000521
kwiberg55b97fe2016-01-28 05:22:45 -0800522 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700523 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
524 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800525 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
526 "Channel::OnInitializeDecoder() invalid codec ("
527 "pt=%d, name=%s) received - 1",
528 payloadType, payloadName);
529 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
530 return -1;
531 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000532
kwiberg55b97fe2016-01-28 05:22:45 -0800533 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000534}
535
kwiberg55b97fe2016-01-28 05:22:45 -0800536int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
537 size_t payloadSize,
538 const WebRtcRTPHeader* rtpHeader) {
539 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
540 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
541 ","
542 " payloadType=%u, audioChannel=%" PRIuS ")",
543 payloadSize, rtpHeader->header.payloadType,
544 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000545
kwiberg55b97fe2016-01-28 05:22:45 -0800546 if (!channel_state_.Get().playing) {
547 // Avoid inserting into NetEQ when we are not playing. Count the
548 // packet as discarded.
549 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
550 "received packet is discarded since playing is not"
551 " activated");
552 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000553 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800554 }
555
556 // Push the incoming payload (parsed and ready for decoding) into the ACM
557 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
558 0) {
559 _engineStatisticsPtr->SetLastError(
560 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
561 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
562 return -1;
563 }
564
kwiberg55b97fe2016-01-28 05:22:45 -0800565 int64_t round_trip_time = 0;
566 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
567 NULL);
568
569 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
570 if (!nack_list.empty()) {
571 // Can't use nack_list.data() since it's not supported by all
572 // compilers.
573 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
574 }
575 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000576}
577
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000578bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000579 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000580 RTPHeader header;
581 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
582 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
583 "IncomingPacket invalid RTP header");
584 return false;
585 }
586 header.payload_type_frequency =
587 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
588 if (header.payload_type_frequency < 0)
589 return false;
590 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
591}
592
henrik.lundin42dda502016-05-18 05:36:01 -0700593MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
594 int32_t id,
595 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700596 unsigned int ssrc;
597 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
598 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800599 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700600 bool muted;
601 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
602 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800603 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
604 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
605 // In all likelihood, the audio in this frame is garbage. We return an
606 // error so that the audio mixer module doesn't add it to the mix. As
607 // a result, it won't be played out and the actions skipped here are
608 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700609 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800610 }
henrik.lundina89ab962016-05-18 08:52:45 -0700611
612 if (muted) {
613 // TODO(henrik.lundin): We should be able to do better than this. But we
614 // will have to go through all the cases below where the audio samples may
615 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800616 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700617 }
kwiberg55b97fe2016-01-28 05:22:45 -0800618
kwiberg55b97fe2016-01-28 05:22:45 -0800619 // Convert module ID to internal VoE channel ID
620 audioFrame->id_ = VoEChannelId(audioFrame->id_);
621 // Store speech type for dead-or-alive detection
622 _outputSpeechType = audioFrame->speech_type_;
623
624 ChannelState::State state = channel_state_.Get();
625
kwiberg55b97fe2016-01-28 05:22:45 -0800626 {
627 // Pass the audio buffers to an optional sink callback, before applying
628 // scaling/panning, as that applies to the mix operation.
629 // External recipients of the audio (e.g. via AudioTrack), will do their
630 // own mixing/dynamic processing.
631 rtc::CritScope cs(&_callbackCritSect);
632 if (audio_sink_) {
633 AudioSinkInterface::Data data(
634 &audioFrame->data_[0], audioFrame->samples_per_channel_,
635 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
636 audioFrame->timestamp_);
637 audio_sink_->OnData(data);
638 }
639 }
640
641 float output_gain = 1.0f;
642 float left_pan = 1.0f;
643 float right_pan = 1.0f;
644 {
645 rtc::CritScope cs(&volume_settings_critsect_);
646 output_gain = _outputGain;
647 left_pan = _panLeft;
648 right_pan = _panRight;
649 }
650
651 // Output volume scaling
652 if (output_gain < 0.99f || output_gain > 1.01f) {
653 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
654 }
655
656 // Scale left and/or right channel(s) if stereo and master balance is
657 // active
658
659 if (left_pan != 1.0f || right_pan != 1.0f) {
660 if (audioFrame->num_channels_ == 1) {
661 // Emulate stereo mode since panning is active.
662 // The mono signal is copied to both left and right channels here.
663 AudioFrameOperations::MonoToStereo(audioFrame);
664 }
665 // For true stereo mode (when we are receiving a stereo signal), no
666 // action is needed.
667
668 // Do the panning operation (the audio frame contains stereo at this
669 // stage)
670 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
671 }
672
673 // Mix decoded PCM output with file if file mixing is enabled
674 if (state.output_file_playing) {
675 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700676 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800677 }
678
679 // External media
680 if (_outputExternalMedia) {
681 rtc::CritScope cs(&_callbackCritSect);
682 const bool isStereo = (audioFrame->num_channels_ == 2);
683 if (_outputExternalMediaCallbackPtr) {
684 _outputExternalMediaCallbackPtr->Process(
685 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
686 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
687 isStereo);
688 }
689 }
690
691 // Record playout if enabled
692 {
693 rtc::CritScope cs(&_fileCritSect);
694
kwiberg5a25d952016-08-17 07:31:12 -0700695 if (_outputFileRecording && output_file_recorder_) {
696 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800697 }
698 }
699
700 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700701 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800702 _outputAudioLevel.ComputeLevel(*audioFrame);
703
704 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
705 // The first frame with a valid rtp timestamp.
706 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
707 }
708
709 if (capture_start_rtp_time_stamp_ >= 0) {
710 // audioFrame.timestamp_ should be valid from now on.
711
712 // Compute elapsed time.
713 int64_t unwrap_timestamp =
714 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
715 audioFrame->elapsed_time_ms_ =
716 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700717 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800718
niklase@google.com470e71d2011-07-07 08:21:25 +0000719 {
kwiberg55b97fe2016-01-28 05:22:45 -0800720 rtc::CritScope lock(&ts_stats_lock_);
721 // Compute ntp time.
722 audioFrame->ntp_time_ms_ =
723 ntp_estimator_.Estimate(audioFrame->timestamp_);
724 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
725 if (audioFrame->ntp_time_ms_ > 0) {
726 // Compute |capture_start_ntp_time_ms_| so that
727 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
728 capture_start_ntp_time_ms_ =
729 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000730 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000731 }
kwiberg55b97fe2016-01-28 05:22:45 -0800732 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000733
henrik.lundin42dda502016-05-18 05:36:01 -0700734 return muted ? MixerParticipant::AudioFrameInfo::kMuted
735 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000736}
737
aleloi6c278492016-10-20 14:24:39 -0700738AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
739 int sample_rate_hz,
740 AudioFrame* audio_frame) {
741 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700742
aleloi6c278492016-10-20 14:24:39 -0700743 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700744
745 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
746 FrameInfo new_audio_frame_info = FrameInfo::kError;
747 switch (frame_info) {
748 case MixerParticipant::AudioFrameInfo::kNormal:
749 new_audio_frame_info = FrameInfo::kNormal;
750 break;
751 case MixerParticipant::AudioFrameInfo::kMuted:
752 new_audio_frame_info = FrameInfo::kMuted;
753 break;
754 case MixerParticipant::AudioFrameInfo::kError:
755 new_audio_frame_info = FrameInfo::kError;
756 break;
757 }
aleloi6c278492016-10-20 14:24:39 -0700758 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700759}
760
kwiberg55b97fe2016-01-28 05:22:45 -0800761int32_t Channel::NeededFrequency(int32_t id) const {
762 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
763 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000764
kwiberg55b97fe2016-01-28 05:22:45 -0800765 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000766
kwiberg55b97fe2016-01-28 05:22:45 -0800767 // Determine highest needed receive frequency
768 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000769
kwiberg55b97fe2016-01-28 05:22:45 -0800770 // Return the bigger of playout and receive frequency in the ACM.
771 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
772 highestNeeded = audio_coding_->PlayoutFrequency();
773 } else {
774 highestNeeded = receiveFrequency;
775 }
776
777 // Special case, if we're playing a file on the playout side
778 // we take that frequency into consideration as well
779 // This is not needed on sending side, since the codec will
780 // limit the spectrum anyway.
781 if (channel_state_.Get().output_file_playing) {
782 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700783 if (output_file_player_) {
784 if (output_file_player_->Frequency() > highestNeeded) {
785 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800786 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000787 }
kwiberg55b97fe2016-01-28 05:22:45 -0800788 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000789
kwiberg55b97fe2016-01-28 05:22:45 -0800790 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000791}
792
ossu5f7cfa52016-05-30 08:11:28 -0700793int32_t Channel::CreateChannel(
794 Channel*& channel,
795 int32_t channelId,
796 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700797 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800798 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
799 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
800 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000801
solenberg88499ec2016-09-07 07:34:41 -0700802 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800803 if (channel == NULL) {
804 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
805 "Channel::CreateChannel() unable to allocate memory for"
806 " channel");
807 return -1;
808 }
809 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000810}
811
kwiberg55b97fe2016-01-28 05:22:45 -0800812void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
813 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
814 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
815 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000816
kwiberg55b97fe2016-01-28 05:22:45 -0800817 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000818}
819
kwiberg55b97fe2016-01-28 05:22:45 -0800820void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
821 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
822 "Channel::RecordNotification(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::PlayFileEnded(int32_t id) {
829 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
830 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000831
kwiberg55b97fe2016-01-28 05:22:45 -0800832 if (id == _inputFilePlayerId) {
833 channel_state_.SetInputFilePlaying(false);
834 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
835 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000836 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800837 } else if (id == _outputFilePlayerId) {
838 channel_state_.SetOutputFilePlaying(false);
839 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
840 "Channel::PlayFileEnded() => output file player module is"
841 " shutdown");
842 }
843}
844
845void Channel::RecordFileEnded(int32_t id) {
846 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
847 "Channel::RecordFileEnded(id=%d)", id);
848
849 assert(id == _outputFileRecorderId);
850
851 rtc::CritScope cs(&_fileCritSect);
852
853 _outputFileRecording = false;
854 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
855 "Channel::RecordFileEnded() => output file recorder module is"
856 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000857}
858
pbos@webrtc.org92135212013-05-14 08:31:39 +0000859Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000860 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700861 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800862 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100863 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700864 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800865 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100866 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800867 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100868 rtp_receive_statistics_(
869 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
870 rtp_receiver_(
871 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100872 this,
873 this,
874 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700875 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 _outputAudioLevel(),
877 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100878 // Avoid conflict with other channels by adding 1024 - 1026,
879 // won't use as much as 1024 channels.
880 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
881 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
882 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
883 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100884 _outputExternalMedia(false),
885 _inputExternalMediaCallbackPtr(NULL),
886 _outputExternalMediaCallbackPtr(NULL),
887 _timeStamp(0), // This is just an offset, RTP module will add it's own
888 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100889 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100890 playout_timestamp_rtp_(0),
891 playout_timestamp_rtcp_(0),
892 playout_delay_ms_(0),
893 _numberOfDiscardedPackets(0),
894 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100895 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
896 capture_start_rtp_time_stamp_(-1),
897 capture_start_ntp_time_ms_(-1),
898 _engineStatisticsPtr(NULL),
899 _outputMixerPtr(NULL),
900 _transmitMixerPtr(NULL),
901 _moduleProcessThreadPtr(NULL),
902 _audioDeviceModulePtr(NULL),
903 _voiceEngineObserverPtr(NULL),
904 _callbackCritSectPtr(NULL),
905 _transportPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100906 _sendFrameType(0),
907 _externalMixing(false),
908 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700909 input_mute_(false),
910 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100911 _panLeft(1.0f),
912 _panRight(1.0f),
913 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100914 _lastLocalTimeStamp(0),
915 _lastPayloadType(0),
916 _includeAudioLevelIndication(false),
917 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100918 restored_packet_in_use_(false),
919 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100920 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700921 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800922 feedback_observer_proxy_(new TransportFeedbackProxy()),
923 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700924 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200925 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
926 kMaxRetransmissionWindowMs)),
michaelt2fedf9c2016-11-28 02:34:18 -0800927 decoder_factory_(config.acm_config.decoder_factory),
928 // Bitrate smoother can be initialized with arbitrary time constant
929 // (0 used here). The actual time constant will be set in SetBitRate.
930 bitrate_smoother_(0, Clock::GetRealTimeClock()) {
kwiberg55b97fe2016-01-28 05:22:45 -0800931 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
932 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700933 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800934 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700935 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800936 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200937
kwiberg55b97fe2016-01-28 05:22:45 -0800938 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000939
kwiberg55b97fe2016-01-28 05:22:45 -0800940 RtpRtcp::Configuration configuration;
941 configuration.audio = true;
942 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800943 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800944 configuration.receive_statistics = rtp_receive_statistics_.get();
945 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800946 if (pacing_enabled_) {
947 configuration.paced_sender = rtp_packet_sender_proxy_.get();
948 configuration.transport_sequence_number_allocator =
949 seq_num_allocator_proxy_.get();
950 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
951 }
ivoc14d5dbe2016-07-04 07:06:55 -0700952 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800953 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200954 configuration.retransmission_rate_limiter =
955 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000956
kwiberg55b97fe2016-01-28 05:22:45 -0800957 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100958 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000959
kwiberg55b97fe2016-01-28 05:22:45 -0800960 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
961 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
962 statistics_proxy_.get());
niklase@google.com470e71d2011-07-07 08:21:25 +0000963}
964
kwiberg55b97fe2016-01-28 05:22:45 -0800965Channel::~Channel() {
966 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
967 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
968 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000969
kwiberg55b97fe2016-01-28 05:22:45 -0800970 if (_outputExternalMedia) {
971 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
972 }
973 if (channel_state_.Get().input_external_media) {
974 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
975 }
976 StopSend();
977 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000978
kwiberg55b97fe2016-01-28 05:22:45 -0800979 {
980 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700981 if (input_file_player_) {
982 input_file_player_->RegisterModuleFileCallback(NULL);
983 input_file_player_->StopPlayingFile();
niklase@google.com470e71d2011-07-07 08:21:25 +0000984 }
kwiberg5a25d952016-08-17 07:31:12 -0700985 if (output_file_player_) {
986 output_file_player_->RegisterModuleFileCallback(NULL);
987 output_file_player_->StopPlayingFile();
kwiberg55b97fe2016-01-28 05:22:45 -0800988 }
kwiberg5a25d952016-08-17 07:31:12 -0700989 if (output_file_recorder_) {
990 output_file_recorder_->RegisterModuleFileCallback(NULL);
991 output_file_recorder_->StopRecording();
kwiberg55b97fe2016-01-28 05:22:45 -0800992 }
993 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000994
kwiberg55b97fe2016-01-28 05:22:45 -0800995 // The order to safely shutdown modules in a channel is:
996 // 1. De-register callbacks in modules
997 // 2. De-register modules in process thread
998 // 3. Destroy modules
999 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1000 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1001 "~Channel() failed to de-register transport callback"
1002 " (Audio coding module)");
1003 }
1004 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1005 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1006 "~Channel() failed to de-register VAD callback"
1007 " (Audio coding module)");
1008 }
1009 // De-register modules in process thread
1010 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +00001011
kwiberg55b97fe2016-01-28 05:22:45 -08001012 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +00001013}
1014
kwiberg55b97fe2016-01-28 05:22:45 -08001015int32_t Channel::Init() {
1016 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1017 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001018
kwiberg55b97fe2016-01-28 05:22:45 -08001019 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001020
kwiberg55b97fe2016-01-28 05:22:45 -08001021 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +00001022
kwiberg55b97fe2016-01-28 05:22:45 -08001023 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
1024 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1025 "Channel::Init() must call SetEngineInformation() first");
1026 return -1;
1027 }
1028
1029 // --- Add modules to process thread (for periodic schedulation)
1030
1031 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
1032
1033 // --- ACM initialization
1034
1035 if (audio_coding_->InitializeReceiver() == -1) {
1036 _engineStatisticsPtr->SetLastError(
1037 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1038 "Channel::Init() unable to initialize the ACM - 1");
1039 return -1;
1040 }
1041
1042 // --- RTP/RTCP module initialization
1043
1044 // Ensure that RTCP is enabled by default for the created channel.
1045 // Note that, the module will keep generating RTCP until it is explicitly
1046 // disabled by the user.
1047 // After StopListen (when no sockets exists), RTCP packets will no longer
1048 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -07001049 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001050 // RTCP is enabled by default.
1051 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1052 // --- Register all permanent callbacks
1053 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
1054 (audio_coding_->RegisterVADCallback(this) == -1);
1055
1056 if (fail) {
1057 _engineStatisticsPtr->SetLastError(
1058 VE_CANNOT_INIT_CHANNEL, kTraceError,
1059 "Channel::Init() callbacks not registered");
1060 return -1;
1061 }
1062
1063 // --- Register all supported codecs to the receiving side of the
1064 // RTP/RTCP module
1065
1066 CodecInst codec;
1067 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1068
1069 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1070 // Open up the RTP/RTCP receiver for all supported codecs
1071 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001072 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001073 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1074 "Channel::Init() unable to register %s "
1075 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1076 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1077 codec.rate);
1078 } else {
1079 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1080 "Channel::Init() %s (%d/%d/%" PRIuS
1081 "/%d) has been "
1082 "added to the RTP/RTCP receiver",
1083 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1084 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001085 }
1086
kwiberg55b97fe2016-01-28 05:22:45 -08001087 // Ensure that PCMU is used as default codec on the sending side
1088 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1089 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001090 }
1091
kwiberg55b97fe2016-01-28 05:22:45 -08001092 // Register default PT for outband 'telephone-event'
1093 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001094 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
kwibergda2bf4e2016-10-24 13:47:09 -07001095 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1096 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001097 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1098 "Channel::Init() failed to register outband "
1099 "'telephone-event' (%d/%d) correctly",
1100 codec.pltype, codec.plfreq);
1101 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001102 }
1103
kwiberg55b97fe2016-01-28 05:22:45 -08001104 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001105 if (!codec_manager_.RegisterEncoder(codec) ||
1106 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
kwibergda2bf4e2016-10-24 13:47:09 -07001107 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1108 CodecInstToSdp(codec)) ||
kwibergc8d071e2016-04-06 12:22:38 -07001109 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001110 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1111 "Channel::Init() failed to register CN (%d/%d) "
1112 "correctly - 1",
1113 codec.pltype, codec.plfreq);
1114 }
1115 }
kwiberg55b97fe2016-01-28 05:22:45 -08001116 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001117
kwiberg55b97fe2016-01-28 05:22:45 -08001118 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001119}
1120
kwiberg55b97fe2016-01-28 05:22:45 -08001121int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1122 OutputMixer& outputMixer,
1123 voe::TransmitMixer& transmitMixer,
1124 ProcessThread& moduleProcessThread,
1125 AudioDeviceModule& audioDeviceModule,
1126 VoiceEngineObserver* voiceEngineObserver,
1127 rtc::CriticalSection* callbackCritSect) {
1128 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1129 "Channel::SetEngineInformation()");
1130 _engineStatisticsPtr = &engineStatistics;
1131 _outputMixerPtr = &outputMixer;
1132 _transmitMixerPtr = &transmitMixer,
1133 _moduleProcessThreadPtr = &moduleProcessThread;
1134 _audioDeviceModulePtr = &audioDeviceModule;
1135 _voiceEngineObserverPtr = voiceEngineObserver;
1136 _callbackCritSectPtr = callbackCritSect;
1137 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001138}
1139
kwiberg55b97fe2016-01-28 05:22:45 -08001140int32_t Channel::UpdateLocalTimeStamp() {
1141 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1142 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001143}
1144
kwibergb7f89d62016-02-17 10:04:18 -08001145void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001146 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001147 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001148}
1149
ossu29b1a8d2016-06-13 07:34:51 -07001150const rtc::scoped_refptr<AudioDecoderFactory>&
1151Channel::GetAudioDecoderFactory() const {
1152 return decoder_factory_;
1153}
1154
kwiberg55b97fe2016-01-28 05:22:45 -08001155int32_t Channel::StartPlayout() {
1156 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1157 "Channel::StartPlayout()");
1158 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001159 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001160 }
1161
1162 if (!_externalMixing) {
1163 // Add participant as candidates for mixing.
1164 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1165 _engineStatisticsPtr->SetLastError(
1166 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1167 "StartPlayout() failed to add participant to mixer");
1168 return -1;
1169 }
1170 }
1171
1172 channel_state_.SetPlaying(true);
1173 if (RegisterFilePlayingToMixer() != 0)
1174 return -1;
1175
1176 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001177}
1178
kwiberg55b97fe2016-01-28 05:22:45 -08001179int32_t Channel::StopPlayout() {
1180 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1181 "Channel::StopPlayout()");
1182 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001183 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001184 }
1185
1186 if (!_externalMixing) {
1187 // Remove participant as candidates for mixing
1188 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1189 _engineStatisticsPtr->SetLastError(
1190 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1191 "StopPlayout() failed to remove participant from mixer");
1192 return -1;
1193 }
1194 }
1195
1196 channel_state_.SetPlaying(false);
1197 _outputAudioLevel.Clear();
1198
1199 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001200}
1201
kwiberg55b97fe2016-01-28 05:22:45 -08001202int32_t Channel::StartSend() {
1203 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1204 "Channel::StartSend()");
1205 // Resume the previous sequence number which was reset by StopSend().
1206 // This needs to be done before |sending| is set to true.
1207 if (send_sequence_number_)
1208 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001209
kwiberg55b97fe2016-01-28 05:22:45 -08001210 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001211 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001212 }
1213 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001214
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001215 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001216 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1217 _engineStatisticsPtr->SetLastError(
1218 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1219 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001220 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001221 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001222 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001223 return -1;
1224 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001225
kwiberg55b97fe2016-01-28 05:22:45 -08001226 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001227}
1228
kwiberg55b97fe2016-01-28 05:22:45 -08001229int32_t Channel::StopSend() {
1230 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1231 "Channel::StopSend()");
1232 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001233 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001234 }
1235 channel_state_.SetSending(false);
1236
1237 // Store the sequence number to be able to pick up the same sequence for
1238 // the next StartSend(). This is needed for restarting device, otherwise
1239 // it might cause libSRTP to complain about packets being replayed.
1240 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1241 // CL is landed. See issue
1242 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1243 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1244
1245 // Reset sending SSRC and sequence number and triggers direct transmission
1246 // of RTCP BYE
1247 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1248 _engineStatisticsPtr->SetLastError(
1249 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1250 "StartSend() RTP/RTCP failed to stop sending");
1251 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001252 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001253
1254 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001255}
1256
solenberge566ac72016-10-31 12:52:33 -07001257void Channel::ResetDiscardedPacketCount() {
kwiberg55b97fe2016-01-28 05:22:45 -08001258 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberge566ac72016-10-31 12:52:33 -07001259 "Channel::ResetDiscardedPacketCount()");
kwiberg55b97fe2016-01-28 05:22:45 -08001260 _numberOfDiscardedPackets = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001261}
1262
kwiberg55b97fe2016-01-28 05:22:45 -08001263int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1264 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1265 "Channel::RegisterVoiceEngineObserver()");
1266 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001267
kwiberg55b97fe2016-01-28 05:22:45 -08001268 if (_voiceEngineObserverPtr) {
1269 _engineStatisticsPtr->SetLastError(
1270 VE_INVALID_OPERATION, kTraceError,
1271 "RegisterVoiceEngineObserver() observer already enabled");
1272 return -1;
1273 }
1274 _voiceEngineObserverPtr = &observer;
1275 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001276}
1277
kwiberg55b97fe2016-01-28 05:22:45 -08001278int32_t Channel::DeRegisterVoiceEngineObserver() {
1279 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1280 "Channel::DeRegisterVoiceEngineObserver()");
1281 rtc::CritScope cs(&_callbackCritSect);
1282
1283 if (!_voiceEngineObserverPtr) {
1284 _engineStatisticsPtr->SetLastError(
1285 VE_INVALID_OPERATION, kTraceWarning,
1286 "DeRegisterVoiceEngineObserver() observer already disabled");
1287 return 0;
1288 }
1289 _voiceEngineObserverPtr = NULL;
1290 return 0;
1291}
1292
1293int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001294 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001295 if (send_codec) {
1296 codec = *send_codec;
1297 return 0;
1298 }
1299 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001300}
1301
kwiberg55b97fe2016-01-28 05:22:45 -08001302int32_t Channel::GetRecCodec(CodecInst& codec) {
1303 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001304}
1305
kwiberg55b97fe2016-01-28 05:22:45 -08001306int32_t Channel::SetSendCodec(const CodecInst& codec) {
1307 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1308 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001309
kwibergc8d071e2016-04-06 12:22:38 -07001310 if (!codec_manager_.RegisterEncoder(codec) ||
1311 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001312 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1313 "SetSendCodec() failed to register codec to ACM");
1314 return -1;
1315 }
1316
1317 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1318 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1319 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1320 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1321 "SetSendCodec() failed to register codec to"
1322 " RTP/RTCP module");
1323 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001324 }
kwiberg55b97fe2016-01-28 05:22:45 -08001325 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001326
kwiberg55b97fe2016-01-28 05:22:45 -08001327 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001328}
1329
minyue78b4d562016-11-30 04:47:39 -08001330void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001331 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1332 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001333 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1334 if (*encoder)
1335 (*encoder)->OnReceivedTargetAudioBitrate(bitrate_bps);
1336 });
Erik Språng737336d2016-07-29 12:59:36 +02001337 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
michaelt2fedf9c2016-11-28 02:34:18 -08001338
1339 // We give smoothed bitrate allocation to audio network adaptor as
1340 // the uplink bandwidth.
minyue78b4d562016-11-30 04:47:39 -08001341 // The probing spikes should not affect the bitrate smoother more than 25%.
1342 // To simplify the calculations we use a step response as input signal.
1343 // The step response of an exponential filter is
1344 // u(t) = 1 - e^(-t / time_constant).
1345 // In order to limit the affect of a BWE spike within 25% of its value before
1346 // the next probing, we would choose a time constant that fulfills
1347 // 1 - e^(-probing_interval_ms / time_constant) < 0.25
1348 // Then 4 * probing_interval_ms is a good choice.
1349 bitrate_smoother_.SetTimeConstantMs(probing_interval_ms * 4);
michaelt2fedf9c2016-11-28 02:34:18 -08001350 bitrate_smoother_.AddSample(bitrate_bps);
1351 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1352 if (*encoder) {
1353 (*encoder)->OnReceivedUplinkBandwidth(
1354 static_cast<int>(*bitrate_smoother_.GetAverage()));
1355 }
1356 });
Ivo Creusenadf89b72015-04-29 16:03:33 +02001357}
1358
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001359void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue7e304322016-10-12 05:00:55 -07001360 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1361 if (*encoder)
1362 (*encoder)->OnReceivedUplinkPacketLossFraction(fraction_lost / 255.0f);
1363 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001364}
1365
kwiberg55b97fe2016-01-28 05:22:45 -08001366int32_t Channel::SetVADStatus(bool enableVAD,
1367 ACMVADMode mode,
1368 bool disableDTX) {
1369 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1370 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001371 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1372 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1373 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001374 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1375 kTraceError,
1376 "SetVADStatus() failed to set VAD");
1377 return -1;
1378 }
1379 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001380}
1381
kwiberg55b97fe2016-01-28 05:22:45 -08001382int32_t Channel::GetVADStatus(bool& enabledVAD,
1383 ACMVADMode& mode,
1384 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001385 const auto* params = codec_manager_.GetStackParams();
1386 enabledVAD = params->use_cng;
1387 mode = params->vad_mode;
1388 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001389 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001390}
1391
kwiberg55b97fe2016-01-28 05:22:45 -08001392int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1393 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1394 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001395
kwiberg55b97fe2016-01-28 05:22:45 -08001396 if (channel_state_.Get().playing) {
1397 _engineStatisticsPtr->SetLastError(
1398 VE_ALREADY_PLAYING, kTraceError,
1399 "SetRecPayloadType() unable to set PT while playing");
1400 return -1;
1401 }
kwiberg55b97fe2016-01-28 05:22:45 -08001402
1403 if (codec.pltype == -1) {
1404 // De-register the selected codec (RTP/RTCP module and ACM)
1405
1406 int8_t pltype(-1);
1407 CodecInst rxCodec = codec;
1408
1409 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001410 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001411 rxCodec.pltype = pltype;
1412
1413 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1414 _engineStatisticsPtr->SetLastError(
1415 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1416 "SetRecPayloadType() RTP/RTCP-module deregistration "
1417 "failed");
1418 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001419 }
kwiberg55b97fe2016-01-28 05:22:45 -08001420 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1421 _engineStatisticsPtr->SetLastError(
1422 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1423 "SetRecPayloadType() ACM deregistration failed - 1");
1424 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001425 }
kwiberg55b97fe2016-01-28 05:22:45 -08001426 return 0;
1427 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001428
magjed56124bd2016-11-24 09:34:46 -08001429 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001430 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001431 // TODO(kwiberg): Retrying is probably not necessary, since
1432 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001433 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001434 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001435 _engineStatisticsPtr->SetLastError(
1436 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1437 "SetRecPayloadType() RTP/RTCP-module registration failed");
1438 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001439 }
kwiberg55b97fe2016-01-28 05:22:45 -08001440 }
kwibergda2bf4e2016-10-24 13:47:09 -07001441 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1442 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001443 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergda2bf4e2016-10-24 13:47:09 -07001444 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1445 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001446 _engineStatisticsPtr->SetLastError(
1447 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1448 "SetRecPayloadType() ACM registration failed - 1");
1449 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001450 }
kwiberg55b97fe2016-01-28 05:22:45 -08001451 }
1452 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001453}
1454
kwiberg55b97fe2016-01-28 05:22:45 -08001455int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1456 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001457 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001458 _engineStatisticsPtr->SetLastError(
1459 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1460 "GetRecPayloadType() failed to retrieve RX payload type");
1461 return -1;
1462 }
1463 codec.pltype = payloadType;
1464 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001465}
1466
kwiberg55b97fe2016-01-28 05:22:45 -08001467int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1468 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1469 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001470
kwiberg55b97fe2016-01-28 05:22:45 -08001471 CodecInst codec;
1472 int32_t samplingFreqHz(-1);
1473 const size_t kMono = 1;
1474 if (frequency == kFreq32000Hz)
1475 samplingFreqHz = 32000;
1476 else if (frequency == kFreq16000Hz)
1477 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001478
kwiberg55b97fe2016-01-28 05:22:45 -08001479 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1480 _engineStatisticsPtr->SetLastError(
1481 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1482 "SetSendCNPayloadType() failed to retrieve default CN codec "
1483 "settings");
1484 return -1;
1485 }
1486
1487 // Modify the payload type (must be set to dynamic range)
1488 codec.pltype = type;
1489
kwibergc8d071e2016-04-06 12:22:38 -07001490 if (!codec_manager_.RegisterEncoder(codec) ||
1491 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001492 _engineStatisticsPtr->SetLastError(
1493 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1494 "SetSendCNPayloadType() failed to register CN to ACM");
1495 return -1;
1496 }
1497
1498 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1499 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1500 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1501 _engineStatisticsPtr->SetLastError(
1502 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1503 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1504 "module");
1505 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001506 }
kwiberg55b97fe2016-01-28 05:22:45 -08001507 }
1508 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001509}
1510
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001511int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001512 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001513 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001514
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001515 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001516 _engineStatisticsPtr->SetLastError(
1517 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001518 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001519 return -1;
1520 }
1521 return 0;
1522}
1523
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001524int Channel::SetOpusDtx(bool enable_dtx) {
1525 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1526 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001527 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001528 : audio_coding_->DisableOpusDtx();
1529 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001530 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1531 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001532 return -1;
1533 }
1534 return 0;
1535}
1536
ivoc85228d62016-07-27 04:53:47 -07001537int Channel::GetOpusDtx(bool* enabled) {
1538 int success = -1;
1539 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1540 if (encoder) {
1541 *enabled = encoder->GetDtx();
1542 success = 0;
1543 }
1544 });
1545 return success;
1546}
1547
minyue7e304322016-10-12 05:00:55 -07001548bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1549 bool success = false;
1550 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1551 if (*encoder) {
1552 success = (*encoder)->EnableAudioNetworkAdaptor(
1553 config_string, Clock::GetRealTimeClock());
1554 }
1555 });
1556 return success;
1557}
1558
1559void Channel::DisableAudioNetworkAdaptor() {
1560 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1561 if (*encoder)
1562 (*encoder)->DisableAudioNetworkAdaptor();
1563 });
1564}
1565
1566void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1567 int max_frame_length_ms) {
1568 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1569 if (*encoder) {
1570 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1571 max_frame_length_ms);
1572 }
1573 });
1574}
1575
mflodman3d7db262016-04-29 00:57:13 -07001576int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001577 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001578 "Channel::RegisterExternalTransport()");
1579
kwiberg55b97fe2016-01-28 05:22:45 -08001580 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001581 if (_externalTransport) {
1582 _engineStatisticsPtr->SetLastError(
1583 VE_INVALID_OPERATION, kTraceError,
1584 "RegisterExternalTransport() external transport already enabled");
1585 return -1;
1586 }
1587 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001588 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001589 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001590}
1591
kwiberg55b97fe2016-01-28 05:22:45 -08001592int32_t Channel::DeRegisterExternalTransport() {
1593 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1594 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001595
kwiberg55b97fe2016-01-28 05:22:45 -08001596 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001597 if (_transportPtr) {
1598 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1599 "DeRegisterExternalTransport() all transport is disabled");
1600 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001601 _engineStatisticsPtr->SetLastError(
1602 VE_INVALID_OPERATION, kTraceWarning,
1603 "DeRegisterExternalTransport() external transport already "
1604 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001605 }
1606 _externalTransport = false;
1607 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001608 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001609}
1610
mflodman3d7db262016-04-29 00:57:13 -07001611int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001612 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001613 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001614 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001615 "Channel::ReceivedRTPPacket()");
1616
1617 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001618 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001619
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001620 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001621 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1622 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1623 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001624 return -1;
1625 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001626 header.payload_type_frequency =
1627 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001628 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001629 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001630 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001631 rtp_receive_statistics_->IncomingPacket(
1632 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001633 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001634
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001635 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001636}
1637
1638bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001639 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001640 const RTPHeader& header,
1641 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001642 if (rtp_payload_registry_->IsRtx(header)) {
1643 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001644 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001645 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001646 assert(packet_length >= header.headerLength);
1647 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001648 PayloadUnion payload_specific;
1649 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001650 &payload_specific)) {
1651 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001652 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001653 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1654 payload_specific, in_order);
1655}
1656
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001657bool Channel::HandleRtxPacket(const uint8_t* packet,
1658 size_t packet_length,
1659 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001660 if (!rtp_payload_registry_->IsRtx(header))
1661 return false;
1662
1663 // Remove the RTX header and parse the original RTP header.
1664 if (packet_length < header.headerLength)
1665 return false;
1666 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1667 return false;
1668 if (restored_packet_in_use_) {
1669 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1670 "Multiple RTX headers detected, dropping packet");
1671 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001672 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001673 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001674 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1675 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001676 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1677 "Incoming RTX packet: invalid RTP header");
1678 return false;
1679 }
1680 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001681 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001682 restored_packet_in_use_ = false;
1683 return ret;
1684}
1685
1686bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1687 StreamStatistician* statistician =
1688 rtp_receive_statistics_->GetStatistician(header.ssrc);
1689 if (!statistician)
1690 return false;
1691 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001692}
1693
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001694bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1695 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001696 // Retransmissions are handled separately if RTX is enabled.
1697 if (rtp_payload_registry_->RtxEnabled())
1698 return false;
1699 StreamStatistician* statistician =
1700 rtp_receive_statistics_->GetStatistician(header.ssrc);
1701 if (!statistician)
1702 return false;
1703 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001704 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001705 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001706 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001707}
1708
mflodman3d7db262016-04-29 00:57:13 -07001709int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001710 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001711 "Channel::ReceivedRTCPPacket()");
1712 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001713 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001714
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001715 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001716 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001717 _engineStatisticsPtr->SetLastError(
1718 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1719 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1720 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001721
Minyue2013aec2015-05-13 14:14:42 +02001722 int64_t rtt = GetRTT(true);
1723 if (rtt == 0) {
1724 // Waiting for valid RTT.
1725 return 0;
1726 }
Erik Språng737336d2016-07-29 12:59:36 +02001727
1728 int64_t nack_window_ms = rtt;
1729 if (nack_window_ms < kMinRetransmissionWindowMs) {
1730 nack_window_ms = kMinRetransmissionWindowMs;
1731 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1732 nack_window_ms = kMaxRetransmissionWindowMs;
1733 }
1734 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1735
minyue7e304322016-10-12 05:00:55 -07001736 // Invoke audio encoders OnReceivedRtt().
1737 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1738 if (*encoder)
1739 (*encoder)->OnReceivedRtt(rtt);
1740 });
1741
Minyue2013aec2015-05-13 14:14:42 +02001742 uint32_t ntp_secs = 0;
1743 uint32_t ntp_frac = 0;
1744 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001745 if (0 !=
1746 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1747 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001748 // Waiting for RTCP.
1749 return 0;
1750 }
1751
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001752 {
tommi31fc21f2016-01-21 10:37:37 -08001753 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001754 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001755 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001756 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001757}
1758
niklase@google.com470e71d2011-07-07 08:21:25 +00001759int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001760 bool loop,
1761 FileFormats format,
1762 int startPosition,
1763 float volumeScaling,
1764 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001765 const CodecInst* codecInst) {
1766 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1767 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1768 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1769 "stopPosition=%d)",
1770 fileName, loop, format, volumeScaling, startPosition,
1771 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001772
kwiberg55b97fe2016-01-28 05:22:45 -08001773 if (channel_state_.Get().output_file_playing) {
1774 _engineStatisticsPtr->SetLastError(
1775 VE_ALREADY_PLAYING, kTraceError,
1776 "StartPlayingFileLocally() is already playing");
1777 return -1;
1778 }
1779
1780 {
1781 rtc::CritScope cs(&_fileCritSect);
1782
kwiberg5a25d952016-08-17 07:31:12 -07001783 if (output_file_player_) {
1784 output_file_player_->RegisterModuleFileCallback(NULL);
1785 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001786 }
1787
kwiberg5b356f42016-09-08 04:32:33 -07001788 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001789 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001790
kwiberg5a25d952016-08-17 07:31:12 -07001791 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001792 _engineStatisticsPtr->SetLastError(
1793 VE_INVALID_ARGUMENT, kTraceError,
1794 "StartPlayingFileLocally() filePlayer format is not correct");
1795 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001796 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001797
kwiberg55b97fe2016-01-28 05:22:45 -08001798 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001799
kwiberg5a25d952016-08-17 07:31:12 -07001800 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001801 fileName, loop, startPosition, volumeScaling, notificationTime,
1802 stopPosition, (const CodecInst*)codecInst) != 0) {
1803 _engineStatisticsPtr->SetLastError(
1804 VE_BAD_FILE, kTraceError,
1805 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001806 output_file_player_->StopPlayingFile();
1807 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001808 return -1;
1809 }
kwiberg5a25d952016-08-17 07:31:12 -07001810 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001811 channel_state_.SetOutputFilePlaying(true);
1812 }
1813
1814 if (RegisterFilePlayingToMixer() != 0)
1815 return -1;
1816
1817 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001818}
1819
1820int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001821 FileFormats format,
1822 int startPosition,
1823 float volumeScaling,
1824 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001825 const CodecInst* codecInst) {
1826 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1827 "Channel::StartPlayingFileLocally(format=%d,"
1828 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1829 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001830
kwiberg55b97fe2016-01-28 05:22:45 -08001831 if (stream == NULL) {
1832 _engineStatisticsPtr->SetLastError(
1833 VE_BAD_FILE, kTraceError,
1834 "StartPlayingFileLocally() NULL as input stream");
1835 return -1;
1836 }
1837
1838 if (channel_state_.Get().output_file_playing) {
1839 _engineStatisticsPtr->SetLastError(
1840 VE_ALREADY_PLAYING, kTraceError,
1841 "StartPlayingFileLocally() is already playing");
1842 return -1;
1843 }
1844
1845 {
1846 rtc::CritScope cs(&_fileCritSect);
1847
1848 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001849 if (output_file_player_) {
1850 output_file_player_->RegisterModuleFileCallback(NULL);
1851 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001852 }
1853
kwiberg55b97fe2016-01-28 05:22:45 -08001854 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001855 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001856 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001857
kwiberg5a25d952016-08-17 07:31:12 -07001858 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001859 _engineStatisticsPtr->SetLastError(
1860 VE_INVALID_ARGUMENT, kTraceError,
1861 "StartPlayingFileLocally() filePlayer format isnot correct");
1862 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001863 }
1864
kwiberg55b97fe2016-01-28 05:22:45 -08001865 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001866
kwiberg4ec01d92016-08-22 08:43:54 -07001867 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001868 volumeScaling, notificationTime,
1869 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001870 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1871 "StartPlayingFile() failed to "
1872 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001873 output_file_player_->StopPlayingFile();
1874 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001875 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001876 }
kwiberg5a25d952016-08-17 07:31:12 -07001877 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001878 channel_state_.SetOutputFilePlaying(true);
1879 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001880
kwiberg55b97fe2016-01-28 05:22:45 -08001881 if (RegisterFilePlayingToMixer() != 0)
1882 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001883
kwiberg55b97fe2016-01-28 05:22:45 -08001884 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001885}
1886
kwiberg55b97fe2016-01-28 05:22:45 -08001887int Channel::StopPlayingFileLocally() {
1888 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1889 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001890
kwiberg55b97fe2016-01-28 05:22:45 -08001891 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001892 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001893 }
1894
1895 {
1896 rtc::CritScope cs(&_fileCritSect);
1897
kwiberg5a25d952016-08-17 07:31:12 -07001898 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001899 _engineStatisticsPtr->SetLastError(
1900 VE_STOP_RECORDING_FAILED, kTraceError,
1901 "StopPlayingFile() could not stop playing");
1902 return -1;
1903 }
kwiberg5a25d952016-08-17 07:31:12 -07001904 output_file_player_->RegisterModuleFileCallback(NULL);
1905 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001906 channel_state_.SetOutputFilePlaying(false);
1907 }
1908 // _fileCritSect cannot be taken while calling
1909 // SetAnonymousMixibilityStatus. Refer to comments in
1910 // StartPlayingFileLocally(const char* ...) for more details.
1911 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1912 _engineStatisticsPtr->SetLastError(
1913 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1914 "StopPlayingFile() failed to stop participant from playing as"
1915 "file in the mixer");
1916 return -1;
1917 }
1918
1919 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001920}
1921
kwiberg55b97fe2016-01-28 05:22:45 -08001922int Channel::IsPlayingFileLocally() const {
1923 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001924}
1925
kwiberg55b97fe2016-01-28 05:22:45 -08001926int Channel::RegisterFilePlayingToMixer() {
1927 // Return success for not registering for file playing to mixer if:
1928 // 1. playing file before playout is started on that channel.
1929 // 2. starting playout without file playing on that channel.
1930 if (!channel_state_.Get().playing ||
1931 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001932 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001933 }
1934
1935 // |_fileCritSect| cannot be taken while calling
1936 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1937 // frames can be pulled by the mixer. Since the frames are generated from
1938 // the file, _fileCritSect will be taken. This would result in a deadlock.
1939 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1940 channel_state_.SetOutputFilePlaying(false);
1941 rtc::CritScope cs(&_fileCritSect);
1942 _engineStatisticsPtr->SetLastError(
1943 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1944 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001945 output_file_player_->StopPlayingFile();
1946 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001947 return -1;
1948 }
1949
1950 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001951}
1952
niklase@google.com470e71d2011-07-07 08:21:25 +00001953int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001954 bool loop,
1955 FileFormats format,
1956 int startPosition,
1957 float volumeScaling,
1958 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001959 const CodecInst* codecInst) {
1960 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1961 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1962 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1963 "stopPosition=%d)",
1964 fileName, loop, format, volumeScaling, startPosition,
1965 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001966
kwiberg55b97fe2016-01-28 05:22:45 -08001967 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001968
kwiberg55b97fe2016-01-28 05:22:45 -08001969 if (channel_state_.Get().input_file_playing) {
1970 _engineStatisticsPtr->SetLastError(
1971 VE_ALREADY_PLAYING, kTraceWarning,
1972 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001973 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001974 }
1975
1976 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001977 if (input_file_player_) {
1978 input_file_player_->RegisterModuleFileCallback(NULL);
1979 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001980 }
1981
1982 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001983 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07001984 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08001985
kwiberg5a25d952016-08-17 07:31:12 -07001986 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001987 _engineStatisticsPtr->SetLastError(
1988 VE_INVALID_ARGUMENT, kTraceError,
1989 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1990 return -1;
1991 }
1992
1993 const uint32_t notificationTime(0);
1994
kwiberg5a25d952016-08-17 07:31:12 -07001995 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001996 fileName, loop, startPosition, volumeScaling, notificationTime,
1997 stopPosition, (const CodecInst*)codecInst) != 0) {
1998 _engineStatisticsPtr->SetLastError(
1999 VE_BAD_FILE, kTraceError,
2000 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002001 input_file_player_->StopPlayingFile();
2002 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002003 return -1;
2004 }
kwiberg5a25d952016-08-17 07:31:12 -07002005 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002006 channel_state_.SetInputFilePlaying(true);
2007
2008 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002009}
2010
2011int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002012 FileFormats format,
2013 int startPosition,
2014 float volumeScaling,
2015 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002016 const CodecInst* codecInst) {
2017 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2018 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2019 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2020 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002021
kwiberg55b97fe2016-01-28 05:22:45 -08002022 if (stream == NULL) {
2023 _engineStatisticsPtr->SetLastError(
2024 VE_BAD_FILE, kTraceError,
2025 "StartPlayingFileAsMicrophone NULL as input stream");
2026 return -1;
2027 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002028
kwiberg55b97fe2016-01-28 05:22:45 -08002029 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002030
kwiberg55b97fe2016-01-28 05:22:45 -08002031 if (channel_state_.Get().input_file_playing) {
2032 _engineStatisticsPtr->SetLastError(
2033 VE_ALREADY_PLAYING, kTraceWarning,
2034 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002035 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002036 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002037
kwiberg55b97fe2016-01-28 05:22:45 -08002038 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002039 if (input_file_player_) {
2040 input_file_player_->RegisterModuleFileCallback(NULL);
2041 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002042 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002043
kwiberg55b97fe2016-01-28 05:22:45 -08002044 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002045 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002046 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002047
kwiberg5a25d952016-08-17 07:31:12 -07002048 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002049 _engineStatisticsPtr->SetLastError(
2050 VE_INVALID_ARGUMENT, kTraceError,
2051 "StartPlayingInputFile() filePlayer format isnot correct");
2052 return -1;
2053 }
2054
2055 const uint32_t notificationTime(0);
2056
kwiberg4ec01d92016-08-22 08:43:54 -07002057 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2058 notificationTime, stopPosition,
2059 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002060 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2061 "StartPlayingFile() failed to start "
2062 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002063 input_file_player_->StopPlayingFile();
2064 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002065 return -1;
2066 }
2067
kwiberg5a25d952016-08-17 07:31:12 -07002068 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002069 channel_state_.SetInputFilePlaying(true);
2070
2071 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002072}
2073
kwiberg55b97fe2016-01-28 05:22:45 -08002074int Channel::StopPlayingFileAsMicrophone() {
2075 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2076 "Channel::StopPlayingFileAsMicrophone()");
2077
2078 rtc::CritScope cs(&_fileCritSect);
2079
2080 if (!channel_state_.Get().input_file_playing) {
2081 return 0;
2082 }
2083
kwiberg5a25d952016-08-17 07:31:12 -07002084 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002085 _engineStatisticsPtr->SetLastError(
2086 VE_STOP_RECORDING_FAILED, kTraceError,
2087 "StopPlayingFile() could not stop playing");
2088 return -1;
2089 }
kwiberg5a25d952016-08-17 07:31:12 -07002090 input_file_player_->RegisterModuleFileCallback(NULL);
2091 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002092 channel_state_.SetInputFilePlaying(false);
2093
2094 return 0;
2095}
2096
2097int Channel::IsPlayingFileAsMicrophone() const {
2098 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002099}
2100
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002101int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002102 const CodecInst* codecInst) {
2103 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2104 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002105
kwiberg55b97fe2016-01-28 05:22:45 -08002106 if (_outputFileRecording) {
2107 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2108 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002109 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002110 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002111
kwiberg55b97fe2016-01-28 05:22:45 -08002112 FileFormats format;
2113 const uint32_t notificationTime(0); // Not supported in VoE
2114 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002115
kwiberg55b97fe2016-01-28 05:22:45 -08002116 if ((codecInst != NULL) &&
2117 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2118 _engineStatisticsPtr->SetLastError(
2119 VE_BAD_ARGUMENT, kTraceError,
2120 "StartRecordingPlayout() invalid compression");
2121 return (-1);
2122 }
2123 if (codecInst == NULL) {
2124 format = kFileFormatPcm16kHzFile;
2125 codecInst = &dummyCodec;
2126 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2127 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2128 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2129 format = kFileFormatWavFile;
2130 } else {
2131 format = kFileFormatCompressedFile;
2132 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002133
kwiberg55b97fe2016-01-28 05:22:45 -08002134 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002135
kwiberg55b97fe2016-01-28 05:22:45 -08002136 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002137 if (output_file_recorder_) {
2138 output_file_recorder_->RegisterModuleFileCallback(NULL);
2139 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002140 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002141
kwiberg5a25d952016-08-17 07:31:12 -07002142 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002143 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002144 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002145 _engineStatisticsPtr->SetLastError(
2146 VE_INVALID_ARGUMENT, kTraceError,
2147 "StartRecordingPlayout() fileRecorder format isnot correct");
2148 return -1;
2149 }
2150
kwiberg5a25d952016-08-17 07:31:12 -07002151 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002152 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2153 _engineStatisticsPtr->SetLastError(
2154 VE_BAD_FILE, kTraceError,
2155 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002156 output_file_recorder_->StopRecording();
2157 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002158 return -1;
2159 }
kwiberg5a25d952016-08-17 07:31:12 -07002160 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002161 _outputFileRecording = true;
2162
2163 return 0;
2164}
2165
2166int Channel::StartRecordingPlayout(OutStream* stream,
2167 const CodecInst* codecInst) {
2168 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2169 "Channel::StartRecordingPlayout()");
2170
2171 if (_outputFileRecording) {
2172 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2173 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002174 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002175 }
2176
2177 FileFormats format;
2178 const uint32_t notificationTime(0); // Not supported in VoE
2179 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2180
2181 if (codecInst != NULL && codecInst->channels != 1) {
2182 _engineStatisticsPtr->SetLastError(
2183 VE_BAD_ARGUMENT, kTraceError,
2184 "StartRecordingPlayout() invalid compression");
2185 return (-1);
2186 }
2187 if (codecInst == NULL) {
2188 format = kFileFormatPcm16kHzFile;
2189 codecInst = &dummyCodec;
2190 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2191 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2192 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2193 format = kFileFormatWavFile;
2194 } else {
2195 format = kFileFormatCompressedFile;
2196 }
2197
2198 rtc::CritScope cs(&_fileCritSect);
2199
2200 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002201 if (output_file_recorder_) {
2202 output_file_recorder_->RegisterModuleFileCallback(NULL);
2203 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002204 }
2205
kwiberg5a25d952016-08-17 07:31:12 -07002206 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002207 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002208 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002209 _engineStatisticsPtr->SetLastError(
2210 VE_INVALID_ARGUMENT, kTraceError,
2211 "StartRecordingPlayout() fileRecorder format isnot correct");
2212 return -1;
2213 }
2214
kwiberg4ec01d92016-08-22 08:43:54 -07002215 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002216 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002217 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2218 "StartRecordingPlayout() failed to "
2219 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002220 output_file_recorder_->StopRecording();
2221 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002222 return -1;
2223 }
2224
kwiberg5a25d952016-08-17 07:31:12 -07002225 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002226 _outputFileRecording = true;
2227
2228 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002229}
2230
kwiberg55b97fe2016-01-28 05:22:45 -08002231int Channel::StopRecordingPlayout() {
2232 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2233 "Channel::StopRecordingPlayout()");
2234
2235 if (!_outputFileRecording) {
2236 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2237 "StopRecordingPlayout() isnot recording");
2238 return -1;
2239 }
2240
2241 rtc::CritScope cs(&_fileCritSect);
2242
kwiberg5a25d952016-08-17 07:31:12 -07002243 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002244 _engineStatisticsPtr->SetLastError(
2245 VE_STOP_RECORDING_FAILED, kTraceError,
2246 "StopRecording() could not stop recording");
2247 return (-1);
2248 }
kwiberg5a25d952016-08-17 07:31:12 -07002249 output_file_recorder_->RegisterModuleFileCallback(NULL);
2250 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002251 _outputFileRecording = false;
2252
2253 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002254}
2255
kwiberg55b97fe2016-01-28 05:22:45 -08002256void Channel::SetMixWithMicStatus(bool mix) {
2257 rtc::CritScope cs(&_fileCritSect);
2258 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002259}
2260
kwiberg55b97fe2016-01-28 05:22:45 -08002261int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2262 int8_t currentLevel = _outputAudioLevel.Level();
2263 level = static_cast<int32_t>(currentLevel);
2264 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002265}
2266
kwiberg55b97fe2016-01-28 05:22:45 -08002267int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2268 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2269 level = static_cast<int32_t>(currentLevel);
2270 return 0;
2271}
2272
solenberg1c2af8e2016-03-24 10:36:00 -07002273int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002274 rtc::CritScope cs(&volume_settings_critsect_);
2275 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002276 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002277 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002278 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002279}
2280
solenberg1c2af8e2016-03-24 10:36:00 -07002281bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002282 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002283 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002284}
2285
kwiberg55b97fe2016-01-28 05:22:45 -08002286int Channel::SetOutputVolumePan(float left, float right) {
2287 rtc::CritScope cs(&volume_settings_critsect_);
2288 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002289 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002290 _panLeft = left;
2291 _panRight = right;
2292 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002293}
2294
kwiberg55b97fe2016-01-28 05:22:45 -08002295int Channel::GetOutputVolumePan(float& left, float& right) const {
2296 rtc::CritScope cs(&volume_settings_critsect_);
2297 left = _panLeft;
2298 right = _panRight;
2299 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002300}
2301
kwiberg55b97fe2016-01-28 05:22:45 -08002302int Channel::SetChannelOutputVolumeScaling(float scaling) {
2303 rtc::CritScope cs(&volume_settings_critsect_);
2304 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002305 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002306 _outputGain = scaling;
2307 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002308}
2309
kwiberg55b97fe2016-01-28 05:22:45 -08002310int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2311 rtc::CritScope cs(&volume_settings_critsect_);
2312 scaling = _outputGain;
2313 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002314}
2315
solenberg8842c3e2016-03-11 03:06:41 -08002316int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002317 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002318 "Channel::SendTelephoneEventOutband(...)");
2319 RTC_DCHECK_LE(0, event);
2320 RTC_DCHECK_GE(255, event);
2321 RTC_DCHECK_LE(0, duration_ms);
2322 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002323 if (!Sending()) {
2324 return -1;
2325 }
solenberg8842c3e2016-03-11 03:06:41 -08002326 if (_rtpRtcpModule->SendTelephoneEventOutband(
2327 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002328 _engineStatisticsPtr->SetLastError(
2329 VE_SEND_DTMF_FAILED, kTraceWarning,
2330 "SendTelephoneEventOutband() failed to send event");
2331 return -1;
2332 }
2333 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002334}
2335
solenbergffbbcac2016-11-17 05:25:37 -08002336int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2337 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002338 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002339 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002340 RTC_DCHECK_LE(0, payload_type);
2341 RTC_DCHECK_GE(127, payload_type);
2342 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002343 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002344 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002345 memcpy(codec.plname, "telephone-event", 16);
2346 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2347 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2348 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2349 _engineStatisticsPtr->SetLastError(
2350 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2351 "SetSendTelephoneEventPayloadType() failed to register send"
2352 "payload type");
2353 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002354 }
kwiberg55b97fe2016-01-28 05:22:45 -08002355 }
kwiberg55b97fe2016-01-28 05:22:45 -08002356 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002357}
2358
kwiberg55b97fe2016-01-28 05:22:45 -08002359int Channel::VoiceActivityIndicator(int& activity) {
2360 activity = _sendFrameType;
2361 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002362}
2363
kwiberg55b97fe2016-01-28 05:22:45 -08002364int Channel::SetLocalSSRC(unsigned int ssrc) {
2365 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2366 "Channel::SetLocalSSRC()");
2367 if (channel_state_.Get().sending) {
2368 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2369 "SetLocalSSRC() already sending");
2370 return -1;
2371 }
2372 _rtpRtcpModule->SetSSRC(ssrc);
2373 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002374}
2375
kwiberg55b97fe2016-01-28 05:22:45 -08002376int Channel::GetLocalSSRC(unsigned int& ssrc) {
2377 ssrc = _rtpRtcpModule->SSRC();
2378 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002379}
2380
kwiberg55b97fe2016-01-28 05:22:45 -08002381int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2382 ssrc = rtp_receiver_->SSRC();
2383 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002384}
2385
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002386int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002387 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002388 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002389}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002390
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002391int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2392 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002393 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2394 if (enable &&
2395 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2396 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002397 return -1;
2398 }
2399 return 0;
2400}
2401
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002402void Channel::EnableSendTransportSequenceNumber(int id) {
2403 int ret =
2404 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2405 RTC_DCHECK_EQ(0, ret);
2406}
2407
stefan3313ec92016-01-21 06:32:43 -08002408void Channel::EnableReceiveTransportSequenceNumber(int id) {
2409 rtp_header_parser_->DeregisterRtpHeaderExtension(
2410 kRtpExtensionTransportSequenceNumber);
2411 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2412 kRtpExtensionTransportSequenceNumber, id);
2413 RTC_DCHECK(ret);
2414}
2415
stefanbba9dec2016-02-01 04:39:55 -08002416void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002417 RtpPacketSender* rtp_packet_sender,
2418 TransportFeedbackObserver* transport_feedback_observer,
2419 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002420 RTC_DCHECK(rtp_packet_sender);
2421 RTC_DCHECK(transport_feedback_observer);
2422 RTC_DCHECK(packet_router && !packet_router_);
2423 feedback_observer_proxy_->SetTransportFeedbackObserver(
2424 transport_feedback_observer);
2425 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2426 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2427 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002428 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002429 packet_router_ = packet_router;
2430}
2431
stefanbba9dec2016-02-01 04:39:55 -08002432void Channel::RegisterReceiverCongestionControlObjects(
2433 PacketRouter* packet_router) {
2434 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002435 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002436 packet_router_ = packet_router;
2437}
2438
2439void Channel::ResetCongestionControlObjects() {
2440 RTC_DCHECK(packet_router_);
2441 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2442 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2443 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002444 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002445 packet_router_ = nullptr;
2446 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2447}
2448
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002449void Channel::SetRTCPStatus(bool enable) {
2450 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2451 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002452 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002453}
2454
kwiberg55b97fe2016-01-28 05:22:45 -08002455int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002456 RtcpMode method = _rtpRtcpModule->RTCP();
2457 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002458 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002459}
2460
kwiberg55b97fe2016-01-28 05:22:45 -08002461int Channel::SetRTCP_CNAME(const char cName[256]) {
2462 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2463 "Channel::SetRTCP_CNAME()");
2464 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2465 _engineStatisticsPtr->SetLastError(
2466 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2467 "SetRTCP_CNAME() failed to set RTCP CNAME");
2468 return -1;
2469 }
2470 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002471}
2472
kwiberg55b97fe2016-01-28 05:22:45 -08002473int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2474 if (cName == NULL) {
2475 _engineStatisticsPtr->SetLastError(
2476 VE_INVALID_ARGUMENT, kTraceError,
2477 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2478 return -1;
2479 }
2480 char cname[RTCP_CNAME_SIZE];
2481 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2482 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2483 _engineStatisticsPtr->SetLastError(
2484 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2485 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2486 return -1;
2487 }
2488 strcpy(cName, cname);
2489 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002490}
2491
kwiberg55b97fe2016-01-28 05:22:45 -08002492int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2493 unsigned int& NTPLow,
2494 unsigned int& timestamp,
2495 unsigned int& playoutTimestamp,
2496 unsigned int* jitter,
2497 unsigned short* fractionLost) {
2498 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002499
kwiberg55b97fe2016-01-28 05:22:45 -08002500 RTCPSenderInfo senderInfo;
2501 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2502 _engineStatisticsPtr->SetLastError(
2503 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2504 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2505 "side");
2506 return -1;
2507 }
2508
2509 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2510 // and octet count)
2511 NTPHigh = senderInfo.NTPseconds;
2512 NTPLow = senderInfo.NTPfraction;
2513 timestamp = senderInfo.RTPtimeStamp;
2514
2515 // --- Locally derived information
2516
2517 // This value is updated on each incoming RTCP packet (0 when no packet
2518 // has been received)
2519 playoutTimestamp = playout_timestamp_rtcp_;
2520
2521 if (NULL != jitter || NULL != fractionLost) {
2522 // Get all RTCP receiver report blocks that have been received on this
2523 // channel. If we receive RTP packets from a remote source we know the
2524 // remote SSRC and use the report block from him.
2525 // Otherwise use the first report block.
2526 std::vector<RTCPReportBlock> remote_stats;
2527 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2528 remote_stats.empty()) {
2529 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2530 "GetRemoteRTCPData() failed to measure statistics due"
2531 " to lack of received RTP and/or RTCP packets");
2532 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002533 }
2534
kwiberg55b97fe2016-01-28 05:22:45 -08002535 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2536 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2537 for (; it != remote_stats.end(); ++it) {
2538 if (it->remoteSSRC == remoteSSRC)
2539 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002540 }
kwiberg55b97fe2016-01-28 05:22:45 -08002541
2542 if (it == remote_stats.end()) {
2543 // If we have not received any RTCP packets from this SSRC it probably
2544 // means that we have not received any RTP packets.
2545 // Use the first received report block instead.
2546 it = remote_stats.begin();
2547 remoteSSRC = it->remoteSSRC;
2548 }
2549
2550 if (jitter) {
2551 *jitter = it->jitter;
2552 }
2553
2554 if (fractionLost) {
2555 *fractionLost = it->fractionLost;
2556 }
2557 }
2558 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002559}
2560
kwiberg55b97fe2016-01-28 05:22:45 -08002561int Channel::SendApplicationDefinedRTCPPacket(
2562 unsigned char subType,
2563 unsigned int name,
2564 const char* data,
2565 unsigned short dataLengthInBytes) {
2566 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2567 "Channel::SendApplicationDefinedRTCPPacket()");
2568 if (!channel_state_.Get().sending) {
2569 _engineStatisticsPtr->SetLastError(
2570 VE_NOT_SENDING, kTraceError,
2571 "SendApplicationDefinedRTCPPacket() not sending");
2572 return -1;
2573 }
2574 if (NULL == data) {
2575 _engineStatisticsPtr->SetLastError(
2576 VE_INVALID_ARGUMENT, kTraceError,
2577 "SendApplicationDefinedRTCPPacket() invalid data value");
2578 return -1;
2579 }
2580 if (dataLengthInBytes % 4 != 0) {
2581 _engineStatisticsPtr->SetLastError(
2582 VE_INVALID_ARGUMENT, kTraceError,
2583 "SendApplicationDefinedRTCPPacket() invalid length value");
2584 return -1;
2585 }
2586 RtcpMode status = _rtpRtcpModule->RTCP();
2587 if (status == RtcpMode::kOff) {
2588 _engineStatisticsPtr->SetLastError(
2589 VE_RTCP_ERROR, kTraceError,
2590 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2591 return -1;
2592 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002593
kwiberg55b97fe2016-01-28 05:22:45 -08002594 // Create and schedule the RTCP APP packet for transmission
2595 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2596 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2597 _engineStatisticsPtr->SetLastError(
2598 VE_SEND_ERROR, kTraceError,
2599 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2600 return -1;
2601 }
2602 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002603}
2604
kwiberg55b97fe2016-01-28 05:22:45 -08002605int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2606 unsigned int& maxJitterMs,
2607 unsigned int& discardedPackets) {
2608 // The jitter statistics is updated for each received RTP packet and is
2609 // based on received packets.
2610 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2611 // If RTCP is off, there is no timed thread in the RTCP module regularly
2612 // generating new stats, trigger the update manually here instead.
2613 StreamStatistician* statistician =
2614 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2615 if (statistician) {
2616 // Don't use returned statistics, use data from proxy instead so that
2617 // max jitter can be fetched atomically.
2618 RtcpStatistics s;
2619 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002620 }
kwiberg55b97fe2016-01-28 05:22:45 -08002621 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002622
kwiberg55b97fe2016-01-28 05:22:45 -08002623 ChannelStatistics stats = statistics_proxy_->GetStats();
2624 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2625 if (playoutFrequency > 0) {
2626 // Scale RTP statistics given the current playout frequency
2627 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2628 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2629 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002630
kwiberg55b97fe2016-01-28 05:22:45 -08002631 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002632
kwiberg55b97fe2016-01-28 05:22:45 -08002633 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002634}
2635
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002636int Channel::GetRemoteRTCPReportBlocks(
2637 std::vector<ReportBlock>* report_blocks) {
2638 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002639 _engineStatisticsPtr->SetLastError(
2640 VE_INVALID_ARGUMENT, kTraceError,
2641 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002642 return -1;
2643 }
2644
2645 // Get the report blocks from the latest received RTCP Sender or Receiver
2646 // Report. Each element in the vector contains the sender's SSRC and a
2647 // report block according to RFC 3550.
2648 std::vector<RTCPReportBlock> rtcp_report_blocks;
2649 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002650 return -1;
2651 }
2652
2653 if (rtcp_report_blocks.empty())
2654 return 0;
2655
2656 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2657 for (; it != rtcp_report_blocks.end(); ++it) {
2658 ReportBlock report_block;
2659 report_block.sender_SSRC = it->remoteSSRC;
2660 report_block.source_SSRC = it->sourceSSRC;
2661 report_block.fraction_lost = it->fractionLost;
2662 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2663 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2664 report_block.interarrival_jitter = it->jitter;
2665 report_block.last_SR_timestamp = it->lastSR;
2666 report_block.delay_since_last_SR = it->delaySinceLastSR;
2667 report_blocks->push_back(report_block);
2668 }
2669 return 0;
2670}
2671
kwiberg55b97fe2016-01-28 05:22:45 -08002672int Channel::GetRTPStatistics(CallStatistics& stats) {
2673 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002674
kwiberg55b97fe2016-01-28 05:22:45 -08002675 // The jitter statistics is updated for each received RTP packet and is
2676 // based on received packets.
2677 RtcpStatistics statistics;
2678 StreamStatistician* statistician =
2679 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002680 if (statistician) {
2681 statistician->GetStatistics(&statistics,
2682 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002683 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002684
kwiberg55b97fe2016-01-28 05:22:45 -08002685 stats.fractionLost = statistics.fraction_lost;
2686 stats.cumulativeLost = statistics.cumulative_lost;
2687 stats.extendedMax = statistics.extended_max_sequence_number;
2688 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002689
kwiberg55b97fe2016-01-28 05:22:45 -08002690 // --- RTT
2691 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002692
kwiberg55b97fe2016-01-28 05:22:45 -08002693 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002694
kwiberg55b97fe2016-01-28 05:22:45 -08002695 size_t bytesSent(0);
2696 uint32_t packetsSent(0);
2697 size_t bytesReceived(0);
2698 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002699
kwiberg55b97fe2016-01-28 05:22:45 -08002700 if (statistician) {
2701 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2702 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002703
kwiberg55b97fe2016-01-28 05:22:45 -08002704 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2705 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2706 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2707 " output will not be complete");
2708 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002709
kwiberg55b97fe2016-01-28 05:22:45 -08002710 stats.bytesSent = bytesSent;
2711 stats.packetsSent = packetsSent;
2712 stats.bytesReceived = bytesReceived;
2713 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002714
kwiberg55b97fe2016-01-28 05:22:45 -08002715 // --- Timestamps
2716 {
2717 rtc::CritScope lock(&ts_stats_lock_);
2718 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2719 }
2720 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002721}
2722
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002723int Channel::SetCodecFECStatus(bool enable) {
2724 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2725 "Channel::SetCodecFECStatus()");
2726
kwibergc8d071e2016-04-06 12:22:38 -07002727 if (!codec_manager_.SetCodecFEC(enable) ||
2728 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002729 _engineStatisticsPtr->SetLastError(
2730 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2731 "SetCodecFECStatus() failed to set FEC state");
2732 return -1;
2733 }
2734 return 0;
2735}
2736
2737bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002738 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002739}
2740
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002741void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2742 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002743 // If pacing is enabled we always store packets.
2744 if (!pacing_enabled_)
2745 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002746 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002747 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002748 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002749 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002750 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002751}
2752
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002753// Called when we are missing one or more packets.
2754int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002755 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2756}
2757
kwiberg55b97fe2016-01-28 05:22:45 -08002758uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2759 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2760 "Channel::Demultiplex()");
2761 _audioFrame.CopyFrom(audioFrame);
2762 _audioFrame.id_ = _channelId;
2763 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002764}
2765
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002766void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002767 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002768 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002769 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002770 CodecInst codec;
2771 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002772
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002773 // Never upsample or upmix the capture signal here. This should be done at the
2774 // end of the send chain.
2775 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2776 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2777 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2778 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002779}
2780
kwiberg55b97fe2016-01-28 05:22:45 -08002781uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2782 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2783 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002784
kwiberg55b97fe2016-01-28 05:22:45 -08002785 if (_audioFrame.samples_per_channel_ == 0) {
2786 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2787 "Channel::PrepareEncodeAndSend() invalid audio frame");
2788 return 0xFFFFFFFF;
2789 }
2790
2791 if (channel_state_.Get().input_file_playing) {
2792 MixOrReplaceAudioWithFile(mixingFrequency);
2793 }
2794
solenberg1c2af8e2016-03-24 10:36:00 -07002795 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2796 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002797
2798 if (channel_state_.Get().input_external_media) {
2799 rtc::CritScope cs(&_callbackCritSect);
2800 const bool isStereo = (_audioFrame.num_channels_ == 2);
2801 if (_inputExternalMediaCallbackPtr) {
2802 _inputExternalMediaCallbackPtr->Process(
2803 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2804 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2805 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002806 }
kwiberg55b97fe2016-01-28 05:22:45 -08002807 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002808
kwiberg55b97fe2016-01-28 05:22:45 -08002809 if (_includeAudioLevelIndication) {
2810 size_t length =
2811 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002812 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002813 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002814 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002815 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002816 rms_level_.Analyze(
2817 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002818 }
kwiberg55b97fe2016-01-28 05:22:45 -08002819 }
solenberg1c2af8e2016-03-24 10:36:00 -07002820 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002821
kwiberg55b97fe2016-01-28 05:22:45 -08002822 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002823}
2824
kwiberg55b97fe2016-01-28 05:22:45 -08002825uint32_t Channel::EncodeAndSend() {
2826 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2827 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002828
kwiberg55b97fe2016-01-28 05:22:45 -08002829 assert(_audioFrame.num_channels_ <= 2);
2830 if (_audioFrame.samples_per_channel_ == 0) {
2831 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2832 "Channel::EncodeAndSend() invalid audio frame");
2833 return 0xFFFFFFFF;
2834 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002835
kwiberg55b97fe2016-01-28 05:22:45 -08002836 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002837
kwiberg55b97fe2016-01-28 05:22:45 -08002838 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002839
kwiberg55b97fe2016-01-28 05:22:45 -08002840 // The ACM resamples internally.
2841 _audioFrame.timestamp_ = _timeStamp;
2842 // This call will trigger AudioPacketizationCallback::SendData if encoding
2843 // is done and payload is ready for packetization and transmission.
2844 // Otherwise, it will return without invoking the callback.
2845 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2846 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2847 "Channel::EncodeAndSend() ACM encoding failed");
2848 return 0xFFFFFFFF;
2849 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002850
kwiberg55b97fe2016-01-28 05:22:45 -08002851 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2852 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002853}
2854
solenberg7602aab2016-11-14 11:30:07 -08002855void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2856 RTC_DCHECK(!channel.channel() ||
2857 channel.channel()->ChannelId() != _channelId);
2858 rtc::CritScope lock(&assoc_send_channel_lock_);
2859 associate_send_channel_ = channel;
2860}
2861
Minyue2013aec2015-05-13 14:14:42 +02002862void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002863 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002864 Channel* channel = associate_send_channel_.channel();
2865 if (channel && channel->ChannelId() == channel_id) {
2866 // If this channel is associated with a send channel of the specified
2867 // Channel ID, disassociate with it.
2868 ChannelOwner ref(NULL);
2869 associate_send_channel_ = ref;
2870 }
2871}
2872
ivoc14d5dbe2016-07-04 07:06:55 -07002873void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2874 event_log_proxy_->SetEventLog(event_log);
2875}
2876
michaelt9332b7d2016-11-30 07:51:13 -08002877void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2878 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2879}
2880
michaelt79e05882016-11-08 02:50:09 -08002881void Channel::SetTransportOverhead(int transport_overhead_per_packet) {
2882 _rtpRtcpModule->SetTransportOverhead(transport_overhead_per_packet);
2883}
2884
michaeltbf65be52016-12-15 06:24:49 -08002885void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
2886 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2887 if (*encoder) {
2888 (*encoder)->OnReceivedOverhead(overhead_bytes_per_packet);
2889 }
2890 });
2891}
2892
kwiberg55b97fe2016-01-28 05:22:45 -08002893int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
2894 VoEMediaProcess& processObject) {
2895 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2896 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002897
kwiberg55b97fe2016-01-28 05:22:45 -08002898 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002899
kwiberg55b97fe2016-01-28 05:22:45 -08002900 if (kPlaybackPerChannel == type) {
2901 if (_outputExternalMediaCallbackPtr) {
2902 _engineStatisticsPtr->SetLastError(
2903 VE_INVALID_OPERATION, kTraceError,
2904 "Channel::RegisterExternalMediaProcessing() "
2905 "output external media already enabled");
2906 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002907 }
kwiberg55b97fe2016-01-28 05:22:45 -08002908 _outputExternalMediaCallbackPtr = &processObject;
2909 _outputExternalMedia = true;
2910 } else if (kRecordingPerChannel == type) {
2911 if (_inputExternalMediaCallbackPtr) {
2912 _engineStatisticsPtr->SetLastError(
2913 VE_INVALID_OPERATION, kTraceError,
2914 "Channel::RegisterExternalMediaProcessing() "
2915 "output external media already enabled");
2916 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002917 }
kwiberg55b97fe2016-01-28 05:22:45 -08002918 _inputExternalMediaCallbackPtr = &processObject;
2919 channel_state_.SetInputExternalMedia(true);
2920 }
2921 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002922}
2923
kwiberg55b97fe2016-01-28 05:22:45 -08002924int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
2925 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2926 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002927
kwiberg55b97fe2016-01-28 05:22:45 -08002928 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002929
kwiberg55b97fe2016-01-28 05:22:45 -08002930 if (kPlaybackPerChannel == type) {
2931 if (!_outputExternalMediaCallbackPtr) {
2932 _engineStatisticsPtr->SetLastError(
2933 VE_INVALID_OPERATION, kTraceWarning,
2934 "Channel::DeRegisterExternalMediaProcessing() "
2935 "output external media already disabled");
2936 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002937 }
kwiberg55b97fe2016-01-28 05:22:45 -08002938 _outputExternalMedia = false;
2939 _outputExternalMediaCallbackPtr = NULL;
2940 } else if (kRecordingPerChannel == type) {
2941 if (!_inputExternalMediaCallbackPtr) {
2942 _engineStatisticsPtr->SetLastError(
2943 VE_INVALID_OPERATION, kTraceWarning,
2944 "Channel::DeRegisterExternalMediaProcessing() "
2945 "input external media already disabled");
2946 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002947 }
kwiberg55b97fe2016-01-28 05:22:45 -08002948 channel_state_.SetInputExternalMedia(false);
2949 _inputExternalMediaCallbackPtr = NULL;
2950 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002951
kwiberg55b97fe2016-01-28 05:22:45 -08002952 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002953}
2954
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002955int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08002956 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2957 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002958
kwiberg55b97fe2016-01-28 05:22:45 -08002959 if (channel_state_.Get().playing) {
2960 _engineStatisticsPtr->SetLastError(
2961 VE_INVALID_OPERATION, kTraceError,
2962 "Channel::SetExternalMixing() "
2963 "external mixing cannot be changed while playing.");
2964 return -1;
2965 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002966
kwiberg55b97fe2016-01-28 05:22:45 -08002967 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002968
kwiberg55b97fe2016-01-28 05:22:45 -08002969 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002970}
2971
kwiberg55b97fe2016-01-28 05:22:45 -08002972int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2973 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002974}
2975
wu@webrtc.org24301a62013-12-13 19:17:43 +00002976void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2977 audio_coding_->GetDecodingCallStatistics(stats);
2978}
2979
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002980bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
2981 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08002982 rtc::CritScope lock(&video_sync_lock_);
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07002983 *jitter_buffer_delay_ms = audio_coding_->FilteredCurrentDelayMs();
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002984 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002985 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00002986}
2987
solenberg358057b2015-11-27 10:46:42 -08002988uint32_t Channel::GetDelayEstimate() const {
2989 int jitter_buffer_delay_ms = 0;
2990 int playout_buffer_delay_ms = 0;
2991 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
2992 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
2993}
2994
deadbeef74375882015-08-13 12:09:10 -07002995int Channel::LeastRequiredDelayMs() const {
2996 return audio_coding_->LeastRequiredDelayMs();
2997}
2998
kwiberg55b97fe2016-01-28 05:22:45 -08002999int Channel::SetMinimumPlayoutDelay(int delayMs) {
3000 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3001 "Channel::SetMinimumPlayoutDelay()");
3002 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3003 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3004 _engineStatisticsPtr->SetLastError(
3005 VE_INVALID_ARGUMENT, kTraceError,
3006 "SetMinimumPlayoutDelay() invalid min delay");
3007 return -1;
3008 }
3009 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3010 _engineStatisticsPtr->SetLastError(
3011 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3012 "SetMinimumPlayoutDelay() failed to set min playout delay");
3013 return -1;
3014 }
3015 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003016}
3017
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003018int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003019 uint32_t playout_timestamp_rtp = 0;
3020 {
tommi31fc21f2016-01-21 10:37:37 -08003021 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003022 playout_timestamp_rtp = playout_timestamp_rtp_;
3023 }
kwiberg55b97fe2016-01-28 05:22:45 -08003024 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003025 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07003026 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003027 "GetPlayoutTimestamp() failed to retrieve timestamp");
3028 return -1;
3029 }
deadbeef74375882015-08-13 12:09:10 -07003030 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003031 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003032}
3033
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003034int Channel::SetInitTimestamp(unsigned int timestamp) {
3035 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003036 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003037 if (channel_state_.Get().sending) {
3038 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3039 "SetInitTimestamp() already sending");
3040 return -1;
3041 }
3042 _rtpRtcpModule->SetStartTimestamp(timestamp);
3043 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003044}
3045
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003046int Channel::SetInitSequenceNumber(short sequenceNumber) {
3047 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3048 "Channel::SetInitSequenceNumber()");
3049 if (channel_state_.Get().sending) {
3050 _engineStatisticsPtr->SetLastError(
3051 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3052 return -1;
3053 }
3054 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3055 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003056}
3057
kwiberg55b97fe2016-01-28 05:22:45 -08003058int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3059 RtpReceiver** rtp_receiver) const {
3060 *rtpRtcpModule = _rtpRtcpModule.get();
3061 *rtp_receiver = rtp_receiver_.get();
3062 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003063}
3064
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003065// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3066// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003067int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003068 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003069 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003070
kwiberg55b97fe2016-01-28 05:22:45 -08003071 {
3072 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003073
kwiberg5a25d952016-08-17 07:31:12 -07003074 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003075 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3076 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3077 " doesnt exist");
3078 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003079 }
3080
kwiberg4ec01d92016-08-22 08:43:54 -07003081 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07003082 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003083 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3084 "Channel::MixOrReplaceAudioWithFile() file mixing "
3085 "failed");
3086 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003087 }
kwiberg55b97fe2016-01-28 05:22:45 -08003088 if (fileSamples == 0) {
3089 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3090 "Channel::MixOrReplaceAudioWithFile() file is ended");
3091 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003092 }
kwiberg55b97fe2016-01-28 05:22:45 -08003093 }
3094
3095 assert(_audioFrame.samples_per_channel_ == fileSamples);
3096
3097 if (_mixFileWithMicrophone) {
3098 // Currently file stream is always mono.
3099 // TODO(xians): Change the code when FilePlayer supports real stereo.
3100 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3101 1, fileSamples);
3102 } else {
3103 // Replace ACM audio with file.
3104 // Currently file stream is always mono.
3105 // TODO(xians): Change the code when FilePlayer supports real stereo.
3106 _audioFrame.UpdateFrame(
3107 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3108 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3109 }
3110 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003111}
3112
kwiberg55b97fe2016-01-28 05:22:45 -08003113int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3114 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003115
kwibergb7f89d62016-02-17 10:04:18 -08003116 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003117 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003118
kwiberg55b97fe2016-01-28 05:22:45 -08003119 {
3120 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003121
kwiberg5a25d952016-08-17 07:31:12 -07003122 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003123 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3124 "Channel::MixAudioWithFile() file mixing failed");
3125 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003126 }
3127
kwiberg55b97fe2016-01-28 05:22:45 -08003128 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07003129 if (output_file_player_->Get10msAudioFromFile(
3130 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003131 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3132 "Channel::MixAudioWithFile() file mixing failed");
3133 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003134 }
kwiberg55b97fe2016-01-28 05:22:45 -08003135 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003136
kwiberg55b97fe2016-01-28 05:22:45 -08003137 if (audioFrame.samples_per_channel_ == fileSamples) {
3138 // Currently file stream is always mono.
3139 // TODO(xians): Change the code when FilePlayer supports real stereo.
3140 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3141 fileSamples);
3142 } else {
3143 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3144 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3145 ") != "
3146 "fileSamples(%" PRIuS ")",
3147 audioFrame.samples_per_channel_, fileSamples);
3148 return -1;
3149 }
3150
3151 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003152}
3153
deadbeef74375882015-08-13 12:09:10 -07003154void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003155 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003156
henrik.lundin96bd5022016-04-06 04:13:56 -07003157 if (!jitter_buffer_playout_timestamp_) {
3158 // This can happen if this channel has not received any RTP packets. In
3159 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003160 return;
3161 }
3162
3163 uint16_t delay_ms = 0;
3164 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003165 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003166 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3167 " delay from the ADM");
3168 _engineStatisticsPtr->SetLastError(
3169 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3170 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3171 return;
3172 }
3173
henrik.lundin96bd5022016-04-06 04:13:56 -07003174 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3175 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003176
3177 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003178 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003179
kwiberg55b97fe2016-01-28 05:22:45 -08003180 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003181 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003182 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003183
3184 {
tommi31fc21f2016-01-21 10:37:37 -08003185 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003186 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003187 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003188 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003189 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003190 }
3191 playout_delay_ms_ = delay_ms;
3192 }
3193}
3194
kwiberg55b97fe2016-01-28 05:22:45 -08003195void Channel::RegisterReceiveCodecsToRTPModule() {
3196 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3197 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003198
kwiberg55b97fe2016-01-28 05:22:45 -08003199 CodecInst codec;
3200 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003201
kwiberg55b97fe2016-01-28 05:22:45 -08003202 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3203 // Open up the RTP/RTCP receiver for all supported codecs
3204 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003205 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003206 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3207 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3208 " to register %s (%d/%d/%" PRIuS
3209 "/%d) to RTP/RTCP "
3210 "receiver",
3211 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3212 codec.rate);
3213 } else {
3214 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3215 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3216 "(%d/%d/%" PRIuS
3217 "/%d) has been added to the RTP/RTCP "
3218 "receiver",
3219 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3220 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003221 }
kwiberg55b97fe2016-01-28 05:22:45 -08003222 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003223}
3224
kwiberg55b97fe2016-01-28 05:22:45 -08003225int Channel::SetSendRtpHeaderExtension(bool enable,
3226 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003227 unsigned char id) {
3228 int error = 0;
3229 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3230 if (enable) {
3231 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3232 }
3233 return error;
3234}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003235
ossue280cde2016-10-12 11:04:10 -07003236int Channel::GetRtpTimestampRateHz() const {
3237 const auto format = audio_coding_->ReceiveFormat();
3238 // Default to the playout frequency if we've not gotten any packets yet.
3239 // TODO(ossu): Zero clockrate can only happen if we've added an external
3240 // decoder for a format we don't support internally. Remove once that way of
3241 // adding decoders is gone!
3242 return (format && format->clockrate_hz != 0)
3243 ? format->clockrate_hz
3244 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003245}
3246
Minyue2013aec2015-05-13 14:14:42 +02003247int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003248 RtcpMode method = _rtpRtcpModule->RTCP();
3249 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003250 return 0;
3251 }
3252 std::vector<RTCPReportBlock> report_blocks;
3253 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003254
3255 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003256 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003257 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003258 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003259 Channel* channel = associate_send_channel_.channel();
3260 // Tries to get RTT from an associated channel. This is important for
3261 // receive-only channels.
3262 if (channel) {
3263 // To prevent infinite recursion and deadlock, calling GetRTT of
3264 // associate channel should always use "false" for argument:
3265 // |allow_associate_channel|.
3266 rtt = channel->GetRTT(false);
3267 }
3268 }
3269 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003270 }
3271
3272 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3273 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3274 for (; it != report_blocks.end(); ++it) {
3275 if (it->remoteSSRC == remoteSSRC)
3276 break;
3277 }
3278 if (it == report_blocks.end()) {
3279 // We have not received packets with SSRC matching the report blocks.
3280 // To calculate RTT we try with the SSRC of the first report block.
3281 // This is very important for send-only channels where we don't know
3282 // the SSRC of the other end.
3283 remoteSSRC = report_blocks[0].remoteSSRC;
3284 }
Minyue2013aec2015-05-13 14:14:42 +02003285
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003286 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003287 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003288 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003289 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3290 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003291 return 0;
3292 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003293 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003294}
3295
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003296} // namespace voe
3297} // namespace webrtc