blob: 84d7a204b19b49e1b4d85728e21b4f02a779ff08 [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),
nisse284542b2017-01-10 08:58:32 -0800917 transport_overhead_per_packet_(0),
918 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100919 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100920 restored_packet_in_use_(false),
921 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100922 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700923 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800924 feedback_observer_proxy_(new TransportFeedbackProxy()),
925 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700926 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200927 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
928 kMaxRetransmissionWindowMs)),
michaelt2fedf9c2016-11-28 02:34:18 -0800929 decoder_factory_(config.acm_config.decoder_factory),
930 // Bitrate smoother can be initialized with arbitrary time constant
931 // (0 used here). The actual time constant will be set in SetBitRate.
932 bitrate_smoother_(0, Clock::GetRealTimeClock()) {
kwiberg55b97fe2016-01-28 05:22:45 -0800933 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
934 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700935 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800936 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700937 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800938 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200939
kwiberg55b97fe2016-01-28 05:22:45 -0800940 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000941
kwiberg55b97fe2016-01-28 05:22:45 -0800942 RtpRtcp::Configuration configuration;
943 configuration.audio = true;
944 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800945 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800946 configuration.receive_statistics = rtp_receive_statistics_.get();
947 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800948 if (pacing_enabled_) {
949 configuration.paced_sender = rtp_packet_sender_proxy_.get();
950 configuration.transport_sequence_number_allocator =
951 seq_num_allocator_proxy_.get();
952 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
953 }
ivoc14d5dbe2016-07-04 07:06:55 -0700954 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800955 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200956 configuration.retransmission_rate_limiter =
957 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000958
kwiberg55b97fe2016-01-28 05:22:45 -0800959 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100960 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000961
kwiberg55b97fe2016-01-28 05:22:45 -0800962 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
963 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
964 statistics_proxy_.get());
niklase@google.com470e71d2011-07-07 08:21:25 +0000965}
966
kwiberg55b97fe2016-01-28 05:22:45 -0800967Channel::~Channel() {
968 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
969 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
970 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000971
kwiberg55b97fe2016-01-28 05:22:45 -0800972 if (_outputExternalMedia) {
973 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
974 }
975 if (channel_state_.Get().input_external_media) {
976 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
977 }
978 StopSend();
979 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000980
kwiberg55b97fe2016-01-28 05:22:45 -0800981 {
982 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700983 if (input_file_player_) {
984 input_file_player_->RegisterModuleFileCallback(NULL);
985 input_file_player_->StopPlayingFile();
niklase@google.com470e71d2011-07-07 08:21:25 +0000986 }
kwiberg5a25d952016-08-17 07:31:12 -0700987 if (output_file_player_) {
988 output_file_player_->RegisterModuleFileCallback(NULL);
989 output_file_player_->StopPlayingFile();
kwiberg55b97fe2016-01-28 05:22:45 -0800990 }
kwiberg5a25d952016-08-17 07:31:12 -0700991 if (output_file_recorder_) {
992 output_file_recorder_->RegisterModuleFileCallback(NULL);
993 output_file_recorder_->StopRecording();
kwiberg55b97fe2016-01-28 05:22:45 -0800994 }
995 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000996
kwiberg55b97fe2016-01-28 05:22:45 -0800997 // The order to safely shutdown modules in a channel is:
998 // 1. De-register callbacks in modules
999 // 2. De-register modules in process thread
1000 // 3. Destroy modules
1001 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1002 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1003 "~Channel() failed to de-register transport callback"
1004 " (Audio coding module)");
1005 }
1006 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1007 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1008 "~Channel() failed to de-register VAD callback"
1009 " (Audio coding module)");
1010 }
1011 // De-register modules in process thread
1012 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +00001013
kwiberg55b97fe2016-01-28 05:22:45 -08001014 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +00001015}
1016
kwiberg55b97fe2016-01-28 05:22:45 -08001017int32_t Channel::Init() {
1018 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1019 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001020
kwiberg55b97fe2016-01-28 05:22:45 -08001021 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001022
kwiberg55b97fe2016-01-28 05:22:45 -08001023 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +00001024
kwiberg55b97fe2016-01-28 05:22:45 -08001025 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
1026 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1027 "Channel::Init() must call SetEngineInformation() first");
1028 return -1;
1029 }
1030
1031 // --- Add modules to process thread (for periodic schedulation)
1032
1033 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
1034
1035 // --- ACM initialization
1036
1037 if (audio_coding_->InitializeReceiver() == -1) {
1038 _engineStatisticsPtr->SetLastError(
1039 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1040 "Channel::Init() unable to initialize the ACM - 1");
1041 return -1;
1042 }
1043
1044 // --- RTP/RTCP module initialization
1045
1046 // Ensure that RTCP is enabled by default for the created channel.
1047 // Note that, the module will keep generating RTCP until it is explicitly
1048 // disabled by the user.
1049 // After StopListen (when no sockets exists), RTCP packets will no longer
1050 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -07001051 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001052 // RTCP is enabled by default.
1053 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1054 // --- Register all permanent callbacks
1055 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
1056 (audio_coding_->RegisterVADCallback(this) == -1);
1057
1058 if (fail) {
1059 _engineStatisticsPtr->SetLastError(
1060 VE_CANNOT_INIT_CHANNEL, kTraceError,
1061 "Channel::Init() callbacks not registered");
1062 return -1;
1063 }
1064
1065 // --- Register all supported codecs to the receiving side of the
1066 // RTP/RTCP module
1067
1068 CodecInst codec;
1069 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1070
1071 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1072 // Open up the RTP/RTCP receiver for all supported codecs
1073 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001074 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001075 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1076 "Channel::Init() unable to register %s "
1077 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1078 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1079 codec.rate);
1080 } else {
1081 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1082 "Channel::Init() %s (%d/%d/%" PRIuS
1083 "/%d) has been "
1084 "added to the RTP/RTCP receiver",
1085 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1086 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001087 }
1088
kwiberg55b97fe2016-01-28 05:22:45 -08001089 // Ensure that PCMU is used as default codec on the sending side
1090 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1091 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001092 }
1093
kwiberg55b97fe2016-01-28 05:22:45 -08001094 // Register default PT for outband 'telephone-event'
1095 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001096 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
kwibergda2bf4e2016-10-24 13:47:09 -07001097 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1098 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001099 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1100 "Channel::Init() failed to register outband "
1101 "'telephone-event' (%d/%d) correctly",
1102 codec.pltype, codec.plfreq);
1103 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001104 }
1105
kwiberg55b97fe2016-01-28 05:22:45 -08001106 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001107 if (!codec_manager_.RegisterEncoder(codec) ||
1108 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
kwibergda2bf4e2016-10-24 13:47:09 -07001109 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1110 CodecInstToSdp(codec)) ||
kwibergc8d071e2016-04-06 12:22:38 -07001111 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001112 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1113 "Channel::Init() failed to register CN (%d/%d) "
1114 "correctly - 1",
1115 codec.pltype, codec.plfreq);
1116 }
1117 }
kwiberg55b97fe2016-01-28 05:22:45 -08001118 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001119
kwiberg55b97fe2016-01-28 05:22:45 -08001120 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001121}
1122
kwiberg55b97fe2016-01-28 05:22:45 -08001123int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1124 OutputMixer& outputMixer,
1125 voe::TransmitMixer& transmitMixer,
1126 ProcessThread& moduleProcessThread,
1127 AudioDeviceModule& audioDeviceModule,
1128 VoiceEngineObserver* voiceEngineObserver,
1129 rtc::CriticalSection* callbackCritSect) {
1130 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1131 "Channel::SetEngineInformation()");
1132 _engineStatisticsPtr = &engineStatistics;
1133 _outputMixerPtr = &outputMixer;
1134 _transmitMixerPtr = &transmitMixer,
1135 _moduleProcessThreadPtr = &moduleProcessThread;
1136 _audioDeviceModulePtr = &audioDeviceModule;
1137 _voiceEngineObserverPtr = voiceEngineObserver;
1138 _callbackCritSectPtr = callbackCritSect;
1139 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001140}
1141
kwiberg55b97fe2016-01-28 05:22:45 -08001142int32_t Channel::UpdateLocalTimeStamp() {
1143 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1144 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001145}
1146
kwibergb7f89d62016-02-17 10:04:18 -08001147void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001148 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001149 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001150}
1151
ossu29b1a8d2016-06-13 07:34:51 -07001152const rtc::scoped_refptr<AudioDecoderFactory>&
1153Channel::GetAudioDecoderFactory() const {
1154 return decoder_factory_;
1155}
1156
kwiberg55b97fe2016-01-28 05:22:45 -08001157int32_t Channel::StartPlayout() {
1158 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1159 "Channel::StartPlayout()");
1160 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001161 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001162 }
1163
1164 if (!_externalMixing) {
1165 // Add participant as candidates for mixing.
1166 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1167 _engineStatisticsPtr->SetLastError(
1168 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1169 "StartPlayout() failed to add participant to mixer");
1170 return -1;
1171 }
1172 }
1173
1174 channel_state_.SetPlaying(true);
1175 if (RegisterFilePlayingToMixer() != 0)
1176 return -1;
1177
1178 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001179}
1180
kwiberg55b97fe2016-01-28 05:22:45 -08001181int32_t Channel::StopPlayout() {
1182 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1183 "Channel::StopPlayout()");
1184 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001185 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001186 }
1187
1188 if (!_externalMixing) {
1189 // Remove participant as candidates for mixing
1190 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1191 _engineStatisticsPtr->SetLastError(
1192 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1193 "StopPlayout() failed to remove participant from mixer");
1194 return -1;
1195 }
1196 }
1197
1198 channel_state_.SetPlaying(false);
1199 _outputAudioLevel.Clear();
1200
1201 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001202}
1203
kwiberg55b97fe2016-01-28 05:22:45 -08001204int32_t Channel::StartSend() {
1205 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1206 "Channel::StartSend()");
1207 // Resume the previous sequence number which was reset by StopSend().
1208 // This needs to be done before |sending| is set to true.
1209 if (send_sequence_number_)
1210 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001211
kwiberg55b97fe2016-01-28 05:22:45 -08001212 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001213 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001214 }
1215 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001216
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001217 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001218 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1219 _engineStatisticsPtr->SetLastError(
1220 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1221 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001222 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001223 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001224 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001225 return -1;
1226 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001227
kwiberg55b97fe2016-01-28 05:22:45 -08001228 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001229}
1230
kwiberg55b97fe2016-01-28 05:22:45 -08001231int32_t Channel::StopSend() {
1232 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1233 "Channel::StopSend()");
1234 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001235 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001236 }
1237 channel_state_.SetSending(false);
1238
1239 // Store the sequence number to be able to pick up the same sequence for
1240 // the next StartSend(). This is needed for restarting device, otherwise
1241 // it might cause libSRTP to complain about packets being replayed.
1242 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1243 // CL is landed. See issue
1244 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1245 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1246
1247 // Reset sending SSRC and sequence number and triggers direct transmission
1248 // of RTCP BYE
1249 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1250 _engineStatisticsPtr->SetLastError(
1251 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1252 "StartSend() RTP/RTCP failed to stop sending");
1253 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001254 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001255
1256 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001257}
1258
solenberge566ac72016-10-31 12:52:33 -07001259void Channel::ResetDiscardedPacketCount() {
kwiberg55b97fe2016-01-28 05:22:45 -08001260 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberge566ac72016-10-31 12:52:33 -07001261 "Channel::ResetDiscardedPacketCount()");
kwiberg55b97fe2016-01-28 05:22:45 -08001262 _numberOfDiscardedPackets = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001263}
1264
kwiberg55b97fe2016-01-28 05:22:45 -08001265int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1266 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1267 "Channel::RegisterVoiceEngineObserver()");
1268 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001269
kwiberg55b97fe2016-01-28 05:22:45 -08001270 if (_voiceEngineObserverPtr) {
1271 _engineStatisticsPtr->SetLastError(
1272 VE_INVALID_OPERATION, kTraceError,
1273 "RegisterVoiceEngineObserver() observer already enabled");
1274 return -1;
1275 }
1276 _voiceEngineObserverPtr = &observer;
1277 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001278}
1279
kwiberg55b97fe2016-01-28 05:22:45 -08001280int32_t Channel::DeRegisterVoiceEngineObserver() {
1281 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1282 "Channel::DeRegisterVoiceEngineObserver()");
1283 rtc::CritScope cs(&_callbackCritSect);
1284
1285 if (!_voiceEngineObserverPtr) {
1286 _engineStatisticsPtr->SetLastError(
1287 VE_INVALID_OPERATION, kTraceWarning,
1288 "DeRegisterVoiceEngineObserver() observer already disabled");
1289 return 0;
1290 }
1291 _voiceEngineObserverPtr = NULL;
1292 return 0;
1293}
1294
1295int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001296 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001297 if (send_codec) {
1298 codec = *send_codec;
1299 return 0;
1300 }
1301 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001302}
1303
kwiberg55b97fe2016-01-28 05:22:45 -08001304int32_t Channel::GetRecCodec(CodecInst& codec) {
1305 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001306}
1307
kwiberg55b97fe2016-01-28 05:22:45 -08001308int32_t Channel::SetSendCodec(const CodecInst& codec) {
1309 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1310 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001311
kwibergc8d071e2016-04-06 12:22:38 -07001312 if (!codec_manager_.RegisterEncoder(codec) ||
1313 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001314 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1315 "SetSendCodec() failed to register codec to ACM");
1316 return -1;
1317 }
1318
1319 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1320 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1321 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1322 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1323 "SetSendCodec() failed to register codec to"
1324 " RTP/RTCP module");
1325 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001326 }
kwiberg55b97fe2016-01-28 05:22:45 -08001327 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001328
kwiberg55b97fe2016-01-28 05:22:45 -08001329 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001330}
1331
minyue78b4d562016-11-30 04:47:39 -08001332void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001333 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1334 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001335 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1336 if (*encoder)
1337 (*encoder)->OnReceivedTargetAudioBitrate(bitrate_bps);
1338 });
Erik Språng737336d2016-07-29 12:59:36 +02001339 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
michaelt2fedf9c2016-11-28 02:34:18 -08001340
1341 // We give smoothed bitrate allocation to audio network adaptor as
1342 // the uplink bandwidth.
minyue78b4d562016-11-30 04:47:39 -08001343 // The probing spikes should not affect the bitrate smoother more than 25%.
1344 // To simplify the calculations we use a step response as input signal.
1345 // The step response of an exponential filter is
1346 // u(t) = 1 - e^(-t / time_constant).
1347 // In order to limit the affect of a BWE spike within 25% of its value before
1348 // the next probing, we would choose a time constant that fulfills
1349 // 1 - e^(-probing_interval_ms / time_constant) < 0.25
1350 // Then 4 * probing_interval_ms is a good choice.
1351 bitrate_smoother_.SetTimeConstantMs(probing_interval_ms * 4);
michaelt2fedf9c2016-11-28 02:34:18 -08001352 bitrate_smoother_.AddSample(bitrate_bps);
1353 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1354 if (*encoder) {
1355 (*encoder)->OnReceivedUplinkBandwidth(
1356 static_cast<int>(*bitrate_smoother_.GetAverage()));
1357 }
1358 });
Ivo Creusenadf89b72015-04-29 16:03:33 +02001359}
1360
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001361void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue7e304322016-10-12 05:00:55 -07001362 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1363 if (*encoder)
1364 (*encoder)->OnReceivedUplinkPacketLossFraction(fraction_lost / 255.0f);
1365 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001366}
1367
kwiberg55b97fe2016-01-28 05:22:45 -08001368int32_t Channel::SetVADStatus(bool enableVAD,
1369 ACMVADMode mode,
1370 bool disableDTX) {
1371 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1372 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001373 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1374 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1375 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001376 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1377 kTraceError,
1378 "SetVADStatus() failed to set VAD");
1379 return -1;
1380 }
1381 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001382}
1383
kwiberg55b97fe2016-01-28 05:22:45 -08001384int32_t Channel::GetVADStatus(bool& enabledVAD,
1385 ACMVADMode& mode,
1386 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001387 const auto* params = codec_manager_.GetStackParams();
1388 enabledVAD = params->use_cng;
1389 mode = params->vad_mode;
1390 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001391 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001392}
1393
kwiberg55b97fe2016-01-28 05:22:45 -08001394int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1395 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1396 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001397
kwiberg55b97fe2016-01-28 05:22:45 -08001398 if (channel_state_.Get().playing) {
1399 _engineStatisticsPtr->SetLastError(
1400 VE_ALREADY_PLAYING, kTraceError,
1401 "SetRecPayloadType() unable to set PT while playing");
1402 return -1;
1403 }
kwiberg55b97fe2016-01-28 05:22:45 -08001404
1405 if (codec.pltype == -1) {
1406 // De-register the selected codec (RTP/RTCP module and ACM)
1407
1408 int8_t pltype(-1);
1409 CodecInst rxCodec = codec;
1410
1411 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001412 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001413 rxCodec.pltype = pltype;
1414
1415 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1416 _engineStatisticsPtr->SetLastError(
1417 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1418 "SetRecPayloadType() RTP/RTCP-module deregistration "
1419 "failed");
1420 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001421 }
kwiberg55b97fe2016-01-28 05:22:45 -08001422 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1423 _engineStatisticsPtr->SetLastError(
1424 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1425 "SetRecPayloadType() ACM deregistration failed - 1");
1426 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001427 }
kwiberg55b97fe2016-01-28 05:22:45 -08001428 return 0;
1429 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001430
magjed56124bd2016-11-24 09:34:46 -08001431 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001432 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001433 // TODO(kwiberg): Retrying is probably not necessary, since
1434 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001435 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001436 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001437 _engineStatisticsPtr->SetLastError(
1438 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1439 "SetRecPayloadType() RTP/RTCP-module registration failed");
1440 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001441 }
kwiberg55b97fe2016-01-28 05:22:45 -08001442 }
kwibergda2bf4e2016-10-24 13:47:09 -07001443 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1444 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001445 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergda2bf4e2016-10-24 13:47:09 -07001446 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1447 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001448 _engineStatisticsPtr->SetLastError(
1449 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1450 "SetRecPayloadType() ACM registration failed - 1");
1451 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001452 }
kwiberg55b97fe2016-01-28 05:22:45 -08001453 }
1454 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001455}
1456
kwiberg55b97fe2016-01-28 05:22:45 -08001457int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1458 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001459 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001460 _engineStatisticsPtr->SetLastError(
1461 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1462 "GetRecPayloadType() failed to retrieve RX payload type");
1463 return -1;
1464 }
1465 codec.pltype = payloadType;
1466 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001467}
1468
kwiberg55b97fe2016-01-28 05:22:45 -08001469int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1470 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1471 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001472
kwiberg55b97fe2016-01-28 05:22:45 -08001473 CodecInst codec;
1474 int32_t samplingFreqHz(-1);
1475 const size_t kMono = 1;
1476 if (frequency == kFreq32000Hz)
1477 samplingFreqHz = 32000;
1478 else if (frequency == kFreq16000Hz)
1479 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001480
kwiberg55b97fe2016-01-28 05:22:45 -08001481 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1482 _engineStatisticsPtr->SetLastError(
1483 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1484 "SetSendCNPayloadType() failed to retrieve default CN codec "
1485 "settings");
1486 return -1;
1487 }
1488
1489 // Modify the payload type (must be set to dynamic range)
1490 codec.pltype = type;
1491
kwibergc8d071e2016-04-06 12:22:38 -07001492 if (!codec_manager_.RegisterEncoder(codec) ||
1493 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001494 _engineStatisticsPtr->SetLastError(
1495 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1496 "SetSendCNPayloadType() failed to register CN to ACM");
1497 return -1;
1498 }
1499
1500 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1501 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1502 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1503 _engineStatisticsPtr->SetLastError(
1504 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1505 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1506 "module");
1507 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001508 }
kwiberg55b97fe2016-01-28 05:22:45 -08001509 }
1510 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001511}
1512
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001513int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001514 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001515 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001516
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001517 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001518 _engineStatisticsPtr->SetLastError(
1519 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001520 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001521 return -1;
1522 }
1523 return 0;
1524}
1525
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001526int Channel::SetOpusDtx(bool enable_dtx) {
1527 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1528 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001529 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001530 : audio_coding_->DisableOpusDtx();
1531 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001532 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1533 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001534 return -1;
1535 }
1536 return 0;
1537}
1538
ivoc85228d62016-07-27 04:53:47 -07001539int Channel::GetOpusDtx(bool* enabled) {
1540 int success = -1;
1541 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1542 if (encoder) {
1543 *enabled = encoder->GetDtx();
1544 success = 0;
1545 }
1546 });
1547 return success;
1548}
1549
minyue7e304322016-10-12 05:00:55 -07001550bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1551 bool success = false;
1552 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1553 if (*encoder) {
1554 success = (*encoder)->EnableAudioNetworkAdaptor(
1555 config_string, Clock::GetRealTimeClock());
1556 }
1557 });
1558 return success;
1559}
1560
1561void Channel::DisableAudioNetworkAdaptor() {
1562 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1563 if (*encoder)
1564 (*encoder)->DisableAudioNetworkAdaptor();
1565 });
1566}
1567
1568void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1569 int max_frame_length_ms) {
1570 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1571 if (*encoder) {
1572 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1573 max_frame_length_ms);
1574 }
1575 });
1576}
1577
mflodman3d7db262016-04-29 00:57:13 -07001578int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001579 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001580 "Channel::RegisterExternalTransport()");
1581
kwiberg55b97fe2016-01-28 05:22:45 -08001582 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001583 if (_externalTransport) {
1584 _engineStatisticsPtr->SetLastError(
1585 VE_INVALID_OPERATION, kTraceError,
1586 "RegisterExternalTransport() external transport already enabled");
1587 return -1;
1588 }
1589 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001590 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001591 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001592}
1593
kwiberg55b97fe2016-01-28 05:22:45 -08001594int32_t Channel::DeRegisterExternalTransport() {
1595 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1596 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001597
kwiberg55b97fe2016-01-28 05:22:45 -08001598 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001599 if (_transportPtr) {
1600 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1601 "DeRegisterExternalTransport() all transport is disabled");
1602 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001603 _engineStatisticsPtr->SetLastError(
1604 VE_INVALID_OPERATION, kTraceWarning,
1605 "DeRegisterExternalTransport() external transport already "
1606 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001607 }
1608 _externalTransport = false;
1609 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001610 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001611}
1612
mflodman3d7db262016-04-29 00:57:13 -07001613int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001614 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001615 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001616 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001617 "Channel::ReceivedRTPPacket()");
1618
1619 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001620 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001621
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001622 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001623 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1624 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1625 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001626 return -1;
1627 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001628 header.payload_type_frequency =
1629 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001630 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001631 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001632 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001633 rtp_receive_statistics_->IncomingPacket(
1634 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001635 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001636
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001637 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001638}
1639
1640bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001641 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001642 const RTPHeader& header,
1643 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001644 if (rtp_payload_registry_->IsRtx(header)) {
1645 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001646 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001647 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001648 assert(packet_length >= header.headerLength);
1649 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001650 PayloadUnion payload_specific;
1651 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001652 &payload_specific)) {
1653 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001654 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001655 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1656 payload_specific, in_order);
1657}
1658
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001659bool Channel::HandleRtxPacket(const uint8_t* packet,
1660 size_t packet_length,
1661 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001662 if (!rtp_payload_registry_->IsRtx(header))
1663 return false;
1664
1665 // Remove the RTX header and parse the original RTP header.
1666 if (packet_length < header.headerLength)
1667 return false;
1668 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1669 return false;
1670 if (restored_packet_in_use_) {
1671 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1672 "Multiple RTX headers detected, dropping packet");
1673 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001674 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001675 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001676 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1677 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001678 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1679 "Incoming RTX packet: invalid RTP header");
1680 return false;
1681 }
1682 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001683 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001684 restored_packet_in_use_ = false;
1685 return ret;
1686}
1687
1688bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1689 StreamStatistician* statistician =
1690 rtp_receive_statistics_->GetStatistician(header.ssrc);
1691 if (!statistician)
1692 return false;
1693 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001694}
1695
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001696bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1697 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001698 // Retransmissions are handled separately if RTX is enabled.
1699 if (rtp_payload_registry_->RtxEnabled())
1700 return false;
1701 StreamStatistician* statistician =
1702 rtp_receive_statistics_->GetStatistician(header.ssrc);
1703 if (!statistician)
1704 return false;
1705 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001706 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001707 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001708 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001709}
1710
mflodman3d7db262016-04-29 00:57:13 -07001711int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001712 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001713 "Channel::ReceivedRTCPPacket()");
1714 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001715 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001716
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001717 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001718 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001719 _engineStatisticsPtr->SetLastError(
1720 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1721 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1722 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001723
Minyue2013aec2015-05-13 14:14:42 +02001724 int64_t rtt = GetRTT(true);
1725 if (rtt == 0) {
1726 // Waiting for valid RTT.
1727 return 0;
1728 }
Erik Språng737336d2016-07-29 12:59:36 +02001729
1730 int64_t nack_window_ms = rtt;
1731 if (nack_window_ms < kMinRetransmissionWindowMs) {
1732 nack_window_ms = kMinRetransmissionWindowMs;
1733 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1734 nack_window_ms = kMaxRetransmissionWindowMs;
1735 }
1736 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1737
minyue7e304322016-10-12 05:00:55 -07001738 // Invoke audio encoders OnReceivedRtt().
1739 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1740 if (*encoder)
1741 (*encoder)->OnReceivedRtt(rtt);
1742 });
1743
Minyue2013aec2015-05-13 14:14:42 +02001744 uint32_t ntp_secs = 0;
1745 uint32_t ntp_frac = 0;
1746 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001747 if (0 !=
1748 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1749 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001750 // Waiting for RTCP.
1751 return 0;
1752 }
1753
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001754 {
tommi31fc21f2016-01-21 10:37:37 -08001755 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001756 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001757 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001758 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001759}
1760
niklase@google.com470e71d2011-07-07 08:21:25 +00001761int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001762 bool loop,
1763 FileFormats format,
1764 int startPosition,
1765 float volumeScaling,
1766 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001767 const CodecInst* codecInst) {
1768 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1769 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1770 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1771 "stopPosition=%d)",
1772 fileName, loop, format, volumeScaling, startPosition,
1773 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001774
kwiberg55b97fe2016-01-28 05:22:45 -08001775 if (channel_state_.Get().output_file_playing) {
1776 _engineStatisticsPtr->SetLastError(
1777 VE_ALREADY_PLAYING, kTraceError,
1778 "StartPlayingFileLocally() is already playing");
1779 return -1;
1780 }
1781
1782 {
1783 rtc::CritScope cs(&_fileCritSect);
1784
kwiberg5a25d952016-08-17 07:31:12 -07001785 if (output_file_player_) {
1786 output_file_player_->RegisterModuleFileCallback(NULL);
1787 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001788 }
1789
kwiberg5b356f42016-09-08 04:32:33 -07001790 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001791 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001792
kwiberg5a25d952016-08-17 07:31:12 -07001793 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001794 _engineStatisticsPtr->SetLastError(
1795 VE_INVALID_ARGUMENT, kTraceError,
1796 "StartPlayingFileLocally() filePlayer format is not correct");
1797 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001798 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001799
kwiberg55b97fe2016-01-28 05:22:45 -08001800 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001801
kwiberg5a25d952016-08-17 07:31:12 -07001802 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001803 fileName, loop, startPosition, volumeScaling, notificationTime,
1804 stopPosition, (const CodecInst*)codecInst) != 0) {
1805 _engineStatisticsPtr->SetLastError(
1806 VE_BAD_FILE, kTraceError,
1807 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001808 output_file_player_->StopPlayingFile();
1809 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001810 return -1;
1811 }
kwiberg5a25d952016-08-17 07:31:12 -07001812 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001813 channel_state_.SetOutputFilePlaying(true);
1814 }
1815
1816 if (RegisterFilePlayingToMixer() != 0)
1817 return -1;
1818
1819 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001820}
1821
1822int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001823 FileFormats format,
1824 int startPosition,
1825 float volumeScaling,
1826 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001827 const CodecInst* codecInst) {
1828 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1829 "Channel::StartPlayingFileLocally(format=%d,"
1830 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1831 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001832
kwiberg55b97fe2016-01-28 05:22:45 -08001833 if (stream == NULL) {
1834 _engineStatisticsPtr->SetLastError(
1835 VE_BAD_FILE, kTraceError,
1836 "StartPlayingFileLocally() NULL as input stream");
1837 return -1;
1838 }
1839
1840 if (channel_state_.Get().output_file_playing) {
1841 _engineStatisticsPtr->SetLastError(
1842 VE_ALREADY_PLAYING, kTraceError,
1843 "StartPlayingFileLocally() is already playing");
1844 return -1;
1845 }
1846
1847 {
1848 rtc::CritScope cs(&_fileCritSect);
1849
1850 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001851 if (output_file_player_) {
1852 output_file_player_->RegisterModuleFileCallback(NULL);
1853 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001854 }
1855
kwiberg55b97fe2016-01-28 05:22:45 -08001856 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001857 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001858 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001859
kwiberg5a25d952016-08-17 07:31:12 -07001860 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001861 _engineStatisticsPtr->SetLastError(
1862 VE_INVALID_ARGUMENT, kTraceError,
1863 "StartPlayingFileLocally() filePlayer format isnot correct");
1864 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001865 }
1866
kwiberg55b97fe2016-01-28 05:22:45 -08001867 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001868
kwiberg4ec01d92016-08-22 08:43:54 -07001869 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001870 volumeScaling, notificationTime,
1871 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001872 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1873 "StartPlayingFile() failed to "
1874 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001875 output_file_player_->StopPlayingFile();
1876 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001877 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001878 }
kwiberg5a25d952016-08-17 07:31:12 -07001879 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001880 channel_state_.SetOutputFilePlaying(true);
1881 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001882
kwiberg55b97fe2016-01-28 05:22:45 -08001883 if (RegisterFilePlayingToMixer() != 0)
1884 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001885
kwiberg55b97fe2016-01-28 05:22:45 -08001886 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001887}
1888
kwiberg55b97fe2016-01-28 05:22:45 -08001889int Channel::StopPlayingFileLocally() {
1890 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1891 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001892
kwiberg55b97fe2016-01-28 05:22:45 -08001893 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001894 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001895 }
1896
1897 {
1898 rtc::CritScope cs(&_fileCritSect);
1899
kwiberg5a25d952016-08-17 07:31:12 -07001900 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001901 _engineStatisticsPtr->SetLastError(
1902 VE_STOP_RECORDING_FAILED, kTraceError,
1903 "StopPlayingFile() could not stop playing");
1904 return -1;
1905 }
kwiberg5a25d952016-08-17 07:31:12 -07001906 output_file_player_->RegisterModuleFileCallback(NULL);
1907 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001908 channel_state_.SetOutputFilePlaying(false);
1909 }
1910 // _fileCritSect cannot be taken while calling
1911 // SetAnonymousMixibilityStatus. Refer to comments in
1912 // StartPlayingFileLocally(const char* ...) for more details.
1913 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1914 _engineStatisticsPtr->SetLastError(
1915 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1916 "StopPlayingFile() failed to stop participant from playing as"
1917 "file in the mixer");
1918 return -1;
1919 }
1920
1921 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001922}
1923
kwiberg55b97fe2016-01-28 05:22:45 -08001924int Channel::IsPlayingFileLocally() const {
1925 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001926}
1927
kwiberg55b97fe2016-01-28 05:22:45 -08001928int Channel::RegisterFilePlayingToMixer() {
1929 // Return success for not registering for file playing to mixer if:
1930 // 1. playing file before playout is started on that channel.
1931 // 2. starting playout without file playing on that channel.
1932 if (!channel_state_.Get().playing ||
1933 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001934 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001935 }
1936
1937 // |_fileCritSect| cannot be taken while calling
1938 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1939 // frames can be pulled by the mixer. Since the frames are generated from
1940 // the file, _fileCritSect will be taken. This would result in a deadlock.
1941 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1942 channel_state_.SetOutputFilePlaying(false);
1943 rtc::CritScope cs(&_fileCritSect);
1944 _engineStatisticsPtr->SetLastError(
1945 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1946 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001947 output_file_player_->StopPlayingFile();
1948 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001949 return -1;
1950 }
1951
1952 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001953}
1954
niklase@google.com470e71d2011-07-07 08:21:25 +00001955int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001956 bool loop,
1957 FileFormats format,
1958 int startPosition,
1959 float volumeScaling,
1960 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001961 const CodecInst* codecInst) {
1962 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1963 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1964 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1965 "stopPosition=%d)",
1966 fileName, loop, format, volumeScaling, startPosition,
1967 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001968
kwiberg55b97fe2016-01-28 05:22:45 -08001969 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001970
kwiberg55b97fe2016-01-28 05:22:45 -08001971 if (channel_state_.Get().input_file_playing) {
1972 _engineStatisticsPtr->SetLastError(
1973 VE_ALREADY_PLAYING, kTraceWarning,
1974 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001975 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001976 }
1977
1978 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001979 if (input_file_player_) {
1980 input_file_player_->RegisterModuleFileCallback(NULL);
1981 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001982 }
1983
1984 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001985 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07001986 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08001987
kwiberg5a25d952016-08-17 07:31:12 -07001988 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001989 _engineStatisticsPtr->SetLastError(
1990 VE_INVALID_ARGUMENT, kTraceError,
1991 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1992 return -1;
1993 }
1994
1995 const uint32_t notificationTime(0);
1996
kwiberg5a25d952016-08-17 07:31:12 -07001997 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001998 fileName, loop, startPosition, volumeScaling, notificationTime,
1999 stopPosition, (const CodecInst*)codecInst) != 0) {
2000 _engineStatisticsPtr->SetLastError(
2001 VE_BAD_FILE, kTraceError,
2002 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002003 input_file_player_->StopPlayingFile();
2004 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002005 return -1;
2006 }
kwiberg5a25d952016-08-17 07:31:12 -07002007 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002008 channel_state_.SetInputFilePlaying(true);
2009
2010 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002011}
2012
2013int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002014 FileFormats format,
2015 int startPosition,
2016 float volumeScaling,
2017 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002018 const CodecInst* codecInst) {
2019 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2020 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2021 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2022 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002023
kwiberg55b97fe2016-01-28 05:22:45 -08002024 if (stream == NULL) {
2025 _engineStatisticsPtr->SetLastError(
2026 VE_BAD_FILE, kTraceError,
2027 "StartPlayingFileAsMicrophone NULL as input stream");
2028 return -1;
2029 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002030
kwiberg55b97fe2016-01-28 05:22:45 -08002031 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002032
kwiberg55b97fe2016-01-28 05:22:45 -08002033 if (channel_state_.Get().input_file_playing) {
2034 _engineStatisticsPtr->SetLastError(
2035 VE_ALREADY_PLAYING, kTraceWarning,
2036 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002037 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002038 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002039
kwiberg55b97fe2016-01-28 05:22:45 -08002040 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002041 if (input_file_player_) {
2042 input_file_player_->RegisterModuleFileCallback(NULL);
2043 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002044 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002045
kwiberg55b97fe2016-01-28 05:22:45 -08002046 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002047 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002048 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002049
kwiberg5a25d952016-08-17 07:31:12 -07002050 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002051 _engineStatisticsPtr->SetLastError(
2052 VE_INVALID_ARGUMENT, kTraceError,
2053 "StartPlayingInputFile() filePlayer format isnot correct");
2054 return -1;
2055 }
2056
2057 const uint32_t notificationTime(0);
2058
kwiberg4ec01d92016-08-22 08:43:54 -07002059 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2060 notificationTime, stopPosition,
2061 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002062 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2063 "StartPlayingFile() failed to start "
2064 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002065 input_file_player_->StopPlayingFile();
2066 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002067 return -1;
2068 }
2069
kwiberg5a25d952016-08-17 07:31:12 -07002070 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002071 channel_state_.SetInputFilePlaying(true);
2072
2073 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002074}
2075
kwiberg55b97fe2016-01-28 05:22:45 -08002076int Channel::StopPlayingFileAsMicrophone() {
2077 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2078 "Channel::StopPlayingFileAsMicrophone()");
2079
2080 rtc::CritScope cs(&_fileCritSect);
2081
2082 if (!channel_state_.Get().input_file_playing) {
2083 return 0;
2084 }
2085
kwiberg5a25d952016-08-17 07:31:12 -07002086 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002087 _engineStatisticsPtr->SetLastError(
2088 VE_STOP_RECORDING_FAILED, kTraceError,
2089 "StopPlayingFile() could not stop playing");
2090 return -1;
2091 }
kwiberg5a25d952016-08-17 07:31:12 -07002092 input_file_player_->RegisterModuleFileCallback(NULL);
2093 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002094 channel_state_.SetInputFilePlaying(false);
2095
2096 return 0;
2097}
2098
2099int Channel::IsPlayingFileAsMicrophone() const {
2100 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002101}
2102
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002103int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002104 const CodecInst* codecInst) {
2105 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2106 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002107
kwiberg55b97fe2016-01-28 05:22:45 -08002108 if (_outputFileRecording) {
2109 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2110 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002111 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002112 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002113
kwiberg55b97fe2016-01-28 05:22:45 -08002114 FileFormats format;
2115 const uint32_t notificationTime(0); // Not supported in VoE
2116 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002117
kwiberg55b97fe2016-01-28 05:22:45 -08002118 if ((codecInst != NULL) &&
2119 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2120 _engineStatisticsPtr->SetLastError(
2121 VE_BAD_ARGUMENT, kTraceError,
2122 "StartRecordingPlayout() invalid compression");
2123 return (-1);
2124 }
2125 if (codecInst == NULL) {
2126 format = kFileFormatPcm16kHzFile;
2127 codecInst = &dummyCodec;
2128 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2129 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2130 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2131 format = kFileFormatWavFile;
2132 } else {
2133 format = kFileFormatCompressedFile;
2134 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002135
kwiberg55b97fe2016-01-28 05:22:45 -08002136 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002137
kwiberg55b97fe2016-01-28 05:22:45 -08002138 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002139 if (output_file_recorder_) {
2140 output_file_recorder_->RegisterModuleFileCallback(NULL);
2141 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002142 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002143
kwiberg5a25d952016-08-17 07:31:12 -07002144 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002145 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002146 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002147 _engineStatisticsPtr->SetLastError(
2148 VE_INVALID_ARGUMENT, kTraceError,
2149 "StartRecordingPlayout() fileRecorder format isnot correct");
2150 return -1;
2151 }
2152
kwiberg5a25d952016-08-17 07:31:12 -07002153 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002154 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2155 _engineStatisticsPtr->SetLastError(
2156 VE_BAD_FILE, kTraceError,
2157 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002158 output_file_recorder_->StopRecording();
2159 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002160 return -1;
2161 }
kwiberg5a25d952016-08-17 07:31:12 -07002162 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002163 _outputFileRecording = true;
2164
2165 return 0;
2166}
2167
2168int Channel::StartRecordingPlayout(OutStream* stream,
2169 const CodecInst* codecInst) {
2170 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2171 "Channel::StartRecordingPlayout()");
2172
2173 if (_outputFileRecording) {
2174 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2175 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002176 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002177 }
2178
2179 FileFormats format;
2180 const uint32_t notificationTime(0); // Not supported in VoE
2181 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2182
2183 if (codecInst != NULL && codecInst->channels != 1) {
2184 _engineStatisticsPtr->SetLastError(
2185 VE_BAD_ARGUMENT, kTraceError,
2186 "StartRecordingPlayout() invalid compression");
2187 return (-1);
2188 }
2189 if (codecInst == NULL) {
2190 format = kFileFormatPcm16kHzFile;
2191 codecInst = &dummyCodec;
2192 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2193 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2194 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2195 format = kFileFormatWavFile;
2196 } else {
2197 format = kFileFormatCompressedFile;
2198 }
2199
2200 rtc::CritScope cs(&_fileCritSect);
2201
2202 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002203 if (output_file_recorder_) {
2204 output_file_recorder_->RegisterModuleFileCallback(NULL);
2205 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002206 }
2207
kwiberg5a25d952016-08-17 07:31:12 -07002208 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002209 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002210 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002211 _engineStatisticsPtr->SetLastError(
2212 VE_INVALID_ARGUMENT, kTraceError,
2213 "StartRecordingPlayout() fileRecorder format isnot correct");
2214 return -1;
2215 }
2216
kwiberg4ec01d92016-08-22 08:43:54 -07002217 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002218 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002219 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2220 "StartRecordingPlayout() failed to "
2221 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002222 output_file_recorder_->StopRecording();
2223 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002224 return -1;
2225 }
2226
kwiberg5a25d952016-08-17 07:31:12 -07002227 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002228 _outputFileRecording = true;
2229
2230 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002231}
2232
kwiberg55b97fe2016-01-28 05:22:45 -08002233int Channel::StopRecordingPlayout() {
2234 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2235 "Channel::StopRecordingPlayout()");
2236
2237 if (!_outputFileRecording) {
2238 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2239 "StopRecordingPlayout() isnot recording");
2240 return -1;
2241 }
2242
2243 rtc::CritScope cs(&_fileCritSect);
2244
kwiberg5a25d952016-08-17 07:31:12 -07002245 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002246 _engineStatisticsPtr->SetLastError(
2247 VE_STOP_RECORDING_FAILED, kTraceError,
2248 "StopRecording() could not stop recording");
2249 return (-1);
2250 }
kwiberg5a25d952016-08-17 07:31:12 -07002251 output_file_recorder_->RegisterModuleFileCallback(NULL);
2252 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002253 _outputFileRecording = false;
2254
2255 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002256}
2257
kwiberg55b97fe2016-01-28 05:22:45 -08002258void Channel::SetMixWithMicStatus(bool mix) {
2259 rtc::CritScope cs(&_fileCritSect);
2260 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002261}
2262
kwiberg55b97fe2016-01-28 05:22:45 -08002263int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2264 int8_t currentLevel = _outputAudioLevel.Level();
2265 level = static_cast<int32_t>(currentLevel);
2266 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002267}
2268
kwiberg55b97fe2016-01-28 05:22:45 -08002269int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2270 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2271 level = static_cast<int32_t>(currentLevel);
2272 return 0;
2273}
2274
solenberg1c2af8e2016-03-24 10:36:00 -07002275int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002276 rtc::CritScope cs(&volume_settings_critsect_);
2277 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002278 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002279 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002280 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002281}
2282
solenberg1c2af8e2016-03-24 10:36:00 -07002283bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002284 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002285 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002286}
2287
kwiberg55b97fe2016-01-28 05:22:45 -08002288int Channel::SetOutputVolumePan(float left, float right) {
2289 rtc::CritScope cs(&volume_settings_critsect_);
2290 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002291 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002292 _panLeft = left;
2293 _panRight = right;
2294 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002295}
2296
kwiberg55b97fe2016-01-28 05:22:45 -08002297int Channel::GetOutputVolumePan(float& left, float& right) const {
2298 rtc::CritScope cs(&volume_settings_critsect_);
2299 left = _panLeft;
2300 right = _panRight;
2301 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002302}
2303
kwiberg55b97fe2016-01-28 05:22:45 -08002304int Channel::SetChannelOutputVolumeScaling(float scaling) {
2305 rtc::CritScope cs(&volume_settings_critsect_);
2306 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002307 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002308 _outputGain = scaling;
2309 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002310}
2311
kwiberg55b97fe2016-01-28 05:22:45 -08002312int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2313 rtc::CritScope cs(&volume_settings_critsect_);
2314 scaling = _outputGain;
2315 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002316}
2317
solenberg8842c3e2016-03-11 03:06:41 -08002318int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002319 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002320 "Channel::SendTelephoneEventOutband(...)");
2321 RTC_DCHECK_LE(0, event);
2322 RTC_DCHECK_GE(255, event);
2323 RTC_DCHECK_LE(0, duration_ms);
2324 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002325 if (!Sending()) {
2326 return -1;
2327 }
solenberg8842c3e2016-03-11 03:06:41 -08002328 if (_rtpRtcpModule->SendTelephoneEventOutband(
2329 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002330 _engineStatisticsPtr->SetLastError(
2331 VE_SEND_DTMF_FAILED, kTraceWarning,
2332 "SendTelephoneEventOutband() failed to send event");
2333 return -1;
2334 }
2335 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002336}
2337
solenbergffbbcac2016-11-17 05:25:37 -08002338int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2339 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002340 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002341 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002342 RTC_DCHECK_LE(0, payload_type);
2343 RTC_DCHECK_GE(127, payload_type);
2344 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002345 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002346 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002347 memcpy(codec.plname, "telephone-event", 16);
2348 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2349 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2350 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2351 _engineStatisticsPtr->SetLastError(
2352 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2353 "SetSendTelephoneEventPayloadType() failed to register send"
2354 "payload type");
2355 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002356 }
kwiberg55b97fe2016-01-28 05:22:45 -08002357 }
kwiberg55b97fe2016-01-28 05:22:45 -08002358 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002359}
2360
kwiberg55b97fe2016-01-28 05:22:45 -08002361int Channel::VoiceActivityIndicator(int& activity) {
2362 activity = _sendFrameType;
2363 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002364}
2365
kwiberg55b97fe2016-01-28 05:22:45 -08002366int Channel::SetLocalSSRC(unsigned int ssrc) {
2367 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2368 "Channel::SetLocalSSRC()");
2369 if (channel_state_.Get().sending) {
2370 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2371 "SetLocalSSRC() already sending");
2372 return -1;
2373 }
2374 _rtpRtcpModule->SetSSRC(ssrc);
2375 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002376}
2377
kwiberg55b97fe2016-01-28 05:22:45 -08002378int Channel::GetLocalSSRC(unsigned int& ssrc) {
2379 ssrc = _rtpRtcpModule->SSRC();
2380 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002381}
2382
kwiberg55b97fe2016-01-28 05:22:45 -08002383int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2384 ssrc = rtp_receiver_->SSRC();
2385 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002386}
2387
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002388int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002389 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002390 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002391}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002392
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002393int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2394 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002395 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2396 if (enable &&
2397 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2398 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002399 return -1;
2400 }
2401 return 0;
2402}
2403
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002404void Channel::EnableSendTransportSequenceNumber(int id) {
2405 int ret =
2406 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2407 RTC_DCHECK_EQ(0, ret);
2408}
2409
stefan3313ec92016-01-21 06:32:43 -08002410void Channel::EnableReceiveTransportSequenceNumber(int id) {
2411 rtp_header_parser_->DeregisterRtpHeaderExtension(
2412 kRtpExtensionTransportSequenceNumber);
2413 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2414 kRtpExtensionTransportSequenceNumber, id);
2415 RTC_DCHECK(ret);
2416}
2417
stefanbba9dec2016-02-01 04:39:55 -08002418void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002419 RtpPacketSender* rtp_packet_sender,
2420 TransportFeedbackObserver* transport_feedback_observer,
2421 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002422 RTC_DCHECK(rtp_packet_sender);
2423 RTC_DCHECK(transport_feedback_observer);
2424 RTC_DCHECK(packet_router && !packet_router_);
2425 feedback_observer_proxy_->SetTransportFeedbackObserver(
2426 transport_feedback_observer);
2427 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2428 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2429 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002430 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002431 packet_router_ = packet_router;
2432}
2433
stefanbba9dec2016-02-01 04:39:55 -08002434void Channel::RegisterReceiverCongestionControlObjects(
2435 PacketRouter* packet_router) {
2436 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002437 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002438 packet_router_ = packet_router;
2439}
2440
2441void Channel::ResetCongestionControlObjects() {
2442 RTC_DCHECK(packet_router_);
2443 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2444 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2445 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002446 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002447 packet_router_ = nullptr;
2448 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2449}
2450
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002451void Channel::SetRTCPStatus(bool enable) {
2452 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2453 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002454 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002455}
2456
kwiberg55b97fe2016-01-28 05:22:45 -08002457int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002458 RtcpMode method = _rtpRtcpModule->RTCP();
2459 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002460 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002461}
2462
kwiberg55b97fe2016-01-28 05:22:45 -08002463int Channel::SetRTCP_CNAME(const char cName[256]) {
2464 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2465 "Channel::SetRTCP_CNAME()");
2466 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2467 _engineStatisticsPtr->SetLastError(
2468 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2469 "SetRTCP_CNAME() failed to set RTCP CNAME");
2470 return -1;
2471 }
2472 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002473}
2474
kwiberg55b97fe2016-01-28 05:22:45 -08002475int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2476 if (cName == NULL) {
2477 _engineStatisticsPtr->SetLastError(
2478 VE_INVALID_ARGUMENT, kTraceError,
2479 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2480 return -1;
2481 }
2482 char cname[RTCP_CNAME_SIZE];
2483 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2484 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2485 _engineStatisticsPtr->SetLastError(
2486 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2487 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2488 return -1;
2489 }
2490 strcpy(cName, cname);
2491 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002492}
2493
kwiberg55b97fe2016-01-28 05:22:45 -08002494int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2495 unsigned int& NTPLow,
2496 unsigned int& timestamp,
2497 unsigned int& playoutTimestamp,
2498 unsigned int* jitter,
2499 unsigned short* fractionLost) {
2500 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002501
kwiberg55b97fe2016-01-28 05:22:45 -08002502 RTCPSenderInfo senderInfo;
2503 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2504 _engineStatisticsPtr->SetLastError(
2505 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2506 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2507 "side");
2508 return -1;
2509 }
2510
2511 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2512 // and octet count)
2513 NTPHigh = senderInfo.NTPseconds;
2514 NTPLow = senderInfo.NTPfraction;
2515 timestamp = senderInfo.RTPtimeStamp;
2516
2517 // --- Locally derived information
2518
2519 // This value is updated on each incoming RTCP packet (0 when no packet
2520 // has been received)
2521 playoutTimestamp = playout_timestamp_rtcp_;
2522
2523 if (NULL != jitter || NULL != fractionLost) {
2524 // Get all RTCP receiver report blocks that have been received on this
2525 // channel. If we receive RTP packets from a remote source we know the
2526 // remote SSRC and use the report block from him.
2527 // Otherwise use the first report block.
2528 std::vector<RTCPReportBlock> remote_stats;
2529 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2530 remote_stats.empty()) {
2531 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2532 "GetRemoteRTCPData() failed to measure statistics due"
2533 " to lack of received RTP and/or RTCP packets");
2534 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002535 }
2536
kwiberg55b97fe2016-01-28 05:22:45 -08002537 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2538 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2539 for (; it != remote_stats.end(); ++it) {
2540 if (it->remoteSSRC == remoteSSRC)
2541 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002542 }
kwiberg55b97fe2016-01-28 05:22:45 -08002543
2544 if (it == remote_stats.end()) {
2545 // If we have not received any RTCP packets from this SSRC it probably
2546 // means that we have not received any RTP packets.
2547 // Use the first received report block instead.
2548 it = remote_stats.begin();
2549 remoteSSRC = it->remoteSSRC;
2550 }
2551
2552 if (jitter) {
2553 *jitter = it->jitter;
2554 }
2555
2556 if (fractionLost) {
2557 *fractionLost = it->fractionLost;
2558 }
2559 }
2560 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002561}
2562
kwiberg55b97fe2016-01-28 05:22:45 -08002563int Channel::SendApplicationDefinedRTCPPacket(
2564 unsigned char subType,
2565 unsigned int name,
2566 const char* data,
2567 unsigned short dataLengthInBytes) {
2568 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2569 "Channel::SendApplicationDefinedRTCPPacket()");
2570 if (!channel_state_.Get().sending) {
2571 _engineStatisticsPtr->SetLastError(
2572 VE_NOT_SENDING, kTraceError,
2573 "SendApplicationDefinedRTCPPacket() not sending");
2574 return -1;
2575 }
2576 if (NULL == data) {
2577 _engineStatisticsPtr->SetLastError(
2578 VE_INVALID_ARGUMENT, kTraceError,
2579 "SendApplicationDefinedRTCPPacket() invalid data value");
2580 return -1;
2581 }
2582 if (dataLengthInBytes % 4 != 0) {
2583 _engineStatisticsPtr->SetLastError(
2584 VE_INVALID_ARGUMENT, kTraceError,
2585 "SendApplicationDefinedRTCPPacket() invalid length value");
2586 return -1;
2587 }
2588 RtcpMode status = _rtpRtcpModule->RTCP();
2589 if (status == RtcpMode::kOff) {
2590 _engineStatisticsPtr->SetLastError(
2591 VE_RTCP_ERROR, kTraceError,
2592 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2593 return -1;
2594 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002595
kwiberg55b97fe2016-01-28 05:22:45 -08002596 // Create and schedule the RTCP APP packet for transmission
2597 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2598 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2599 _engineStatisticsPtr->SetLastError(
2600 VE_SEND_ERROR, kTraceError,
2601 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2602 return -1;
2603 }
2604 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002605}
2606
kwiberg55b97fe2016-01-28 05:22:45 -08002607int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2608 unsigned int& maxJitterMs,
2609 unsigned int& discardedPackets) {
2610 // The jitter statistics is updated for each received RTP packet and is
2611 // based on received packets.
2612 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2613 // If RTCP is off, there is no timed thread in the RTCP module regularly
2614 // generating new stats, trigger the update manually here instead.
2615 StreamStatistician* statistician =
2616 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2617 if (statistician) {
2618 // Don't use returned statistics, use data from proxy instead so that
2619 // max jitter can be fetched atomically.
2620 RtcpStatistics s;
2621 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002622 }
kwiberg55b97fe2016-01-28 05:22:45 -08002623 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002624
kwiberg55b97fe2016-01-28 05:22:45 -08002625 ChannelStatistics stats = statistics_proxy_->GetStats();
2626 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2627 if (playoutFrequency > 0) {
2628 // Scale RTP statistics given the current playout frequency
2629 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2630 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2631 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002632
kwiberg55b97fe2016-01-28 05:22:45 -08002633 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002634
kwiberg55b97fe2016-01-28 05:22:45 -08002635 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002636}
2637
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002638int Channel::GetRemoteRTCPReportBlocks(
2639 std::vector<ReportBlock>* report_blocks) {
2640 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002641 _engineStatisticsPtr->SetLastError(
2642 VE_INVALID_ARGUMENT, kTraceError,
2643 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002644 return -1;
2645 }
2646
2647 // Get the report blocks from the latest received RTCP Sender or Receiver
2648 // Report. Each element in the vector contains the sender's SSRC and a
2649 // report block according to RFC 3550.
2650 std::vector<RTCPReportBlock> rtcp_report_blocks;
2651 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002652 return -1;
2653 }
2654
2655 if (rtcp_report_blocks.empty())
2656 return 0;
2657
2658 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2659 for (; it != rtcp_report_blocks.end(); ++it) {
2660 ReportBlock report_block;
2661 report_block.sender_SSRC = it->remoteSSRC;
2662 report_block.source_SSRC = it->sourceSSRC;
2663 report_block.fraction_lost = it->fractionLost;
2664 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2665 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2666 report_block.interarrival_jitter = it->jitter;
2667 report_block.last_SR_timestamp = it->lastSR;
2668 report_block.delay_since_last_SR = it->delaySinceLastSR;
2669 report_blocks->push_back(report_block);
2670 }
2671 return 0;
2672}
2673
kwiberg55b97fe2016-01-28 05:22:45 -08002674int Channel::GetRTPStatistics(CallStatistics& stats) {
2675 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002676
kwiberg55b97fe2016-01-28 05:22:45 -08002677 // The jitter statistics is updated for each received RTP packet and is
2678 // based on received packets.
2679 RtcpStatistics statistics;
2680 StreamStatistician* statistician =
2681 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002682 if (statistician) {
2683 statistician->GetStatistics(&statistics,
2684 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002685 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002686
kwiberg55b97fe2016-01-28 05:22:45 -08002687 stats.fractionLost = statistics.fraction_lost;
2688 stats.cumulativeLost = statistics.cumulative_lost;
2689 stats.extendedMax = statistics.extended_max_sequence_number;
2690 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002691
kwiberg55b97fe2016-01-28 05:22:45 -08002692 // --- RTT
2693 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002694
kwiberg55b97fe2016-01-28 05:22:45 -08002695 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002696
kwiberg55b97fe2016-01-28 05:22:45 -08002697 size_t bytesSent(0);
2698 uint32_t packetsSent(0);
2699 size_t bytesReceived(0);
2700 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002701
kwiberg55b97fe2016-01-28 05:22:45 -08002702 if (statistician) {
2703 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2704 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002705
kwiberg55b97fe2016-01-28 05:22:45 -08002706 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2707 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2708 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2709 " output will not be complete");
2710 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002711
kwiberg55b97fe2016-01-28 05:22:45 -08002712 stats.bytesSent = bytesSent;
2713 stats.packetsSent = packetsSent;
2714 stats.bytesReceived = bytesReceived;
2715 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002716
kwiberg55b97fe2016-01-28 05:22:45 -08002717 // --- Timestamps
2718 {
2719 rtc::CritScope lock(&ts_stats_lock_);
2720 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2721 }
2722 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002723}
2724
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002725int Channel::SetCodecFECStatus(bool enable) {
2726 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2727 "Channel::SetCodecFECStatus()");
2728
kwibergc8d071e2016-04-06 12:22:38 -07002729 if (!codec_manager_.SetCodecFEC(enable) ||
2730 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002731 _engineStatisticsPtr->SetLastError(
2732 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2733 "SetCodecFECStatus() failed to set FEC state");
2734 return -1;
2735 }
2736 return 0;
2737}
2738
2739bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002740 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002741}
2742
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002743void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2744 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002745 // If pacing is enabled we always store packets.
2746 if (!pacing_enabled_)
2747 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002748 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002749 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002750 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002751 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002752 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002753}
2754
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002755// Called when we are missing one or more packets.
2756int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002757 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2758}
2759
kwiberg55b97fe2016-01-28 05:22:45 -08002760uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2761 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2762 "Channel::Demultiplex()");
2763 _audioFrame.CopyFrom(audioFrame);
2764 _audioFrame.id_ = _channelId;
2765 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002766}
2767
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002768void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002769 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002770 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002771 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002772 CodecInst codec;
2773 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002774
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002775 // Never upsample or upmix the capture signal here. This should be done at the
2776 // end of the send chain.
2777 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2778 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2779 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2780 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002781}
2782
kwiberg55b97fe2016-01-28 05:22:45 -08002783uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2784 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2785 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002786
kwiberg55b97fe2016-01-28 05:22:45 -08002787 if (_audioFrame.samples_per_channel_ == 0) {
2788 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2789 "Channel::PrepareEncodeAndSend() invalid audio frame");
2790 return 0xFFFFFFFF;
2791 }
2792
2793 if (channel_state_.Get().input_file_playing) {
2794 MixOrReplaceAudioWithFile(mixingFrequency);
2795 }
2796
solenberg1c2af8e2016-03-24 10:36:00 -07002797 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2798 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002799
2800 if (channel_state_.Get().input_external_media) {
2801 rtc::CritScope cs(&_callbackCritSect);
2802 const bool isStereo = (_audioFrame.num_channels_ == 2);
2803 if (_inputExternalMediaCallbackPtr) {
2804 _inputExternalMediaCallbackPtr->Process(
2805 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2806 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2807 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002808 }
kwiberg55b97fe2016-01-28 05:22:45 -08002809 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002810
kwiberg55b97fe2016-01-28 05:22:45 -08002811 if (_includeAudioLevelIndication) {
2812 size_t length =
2813 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002814 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002815 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002816 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002817 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002818 rms_level_.Analyze(
2819 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002820 }
kwiberg55b97fe2016-01-28 05:22:45 -08002821 }
solenberg1c2af8e2016-03-24 10:36:00 -07002822 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002823
kwiberg55b97fe2016-01-28 05:22:45 -08002824 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002825}
2826
kwiberg55b97fe2016-01-28 05:22:45 -08002827uint32_t Channel::EncodeAndSend() {
2828 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2829 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002830
kwiberg55b97fe2016-01-28 05:22:45 -08002831 assert(_audioFrame.num_channels_ <= 2);
2832 if (_audioFrame.samples_per_channel_ == 0) {
2833 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2834 "Channel::EncodeAndSend() invalid audio frame");
2835 return 0xFFFFFFFF;
2836 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002837
kwiberg55b97fe2016-01-28 05:22:45 -08002838 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002839
kwiberg55b97fe2016-01-28 05:22:45 -08002840 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002841
kwiberg55b97fe2016-01-28 05:22:45 -08002842 // The ACM resamples internally.
2843 _audioFrame.timestamp_ = _timeStamp;
2844 // This call will trigger AudioPacketizationCallback::SendData if encoding
2845 // is done and payload is ready for packetization and transmission.
2846 // Otherwise, it will return without invoking the callback.
2847 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2848 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2849 "Channel::EncodeAndSend() ACM encoding failed");
2850 return 0xFFFFFFFF;
2851 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002852
kwiberg55b97fe2016-01-28 05:22:45 -08002853 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2854 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002855}
2856
solenberg7602aab2016-11-14 11:30:07 -08002857void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2858 RTC_DCHECK(!channel.channel() ||
2859 channel.channel()->ChannelId() != _channelId);
2860 rtc::CritScope lock(&assoc_send_channel_lock_);
2861 associate_send_channel_ = channel;
2862}
2863
Minyue2013aec2015-05-13 14:14:42 +02002864void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002865 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002866 Channel* channel = associate_send_channel_.channel();
2867 if (channel && channel->ChannelId() == channel_id) {
2868 // If this channel is associated with a send channel of the specified
2869 // Channel ID, disassociate with it.
2870 ChannelOwner ref(NULL);
2871 associate_send_channel_ = ref;
2872 }
2873}
2874
ivoc14d5dbe2016-07-04 07:06:55 -07002875void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2876 event_log_proxy_->SetEventLog(event_log);
2877}
2878
michaelt9332b7d2016-11-30 07:51:13 -08002879void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2880 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2881}
2882
nisse284542b2017-01-10 08:58:32 -08002883void Channel::UpdateOverheadForEncoder() {
2884 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2885 if (*encoder) {
2886 (*encoder)->OnReceivedOverhead(transport_overhead_per_packet_ +
2887 rtp_overhead_per_packet_);
2888 }
2889 });
2890}
2891
2892void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
2893 transport_overhead_per_packet_ = transport_overhead_per_packet;
2894 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002895}
2896
michaeltbf65be52016-12-15 06:24:49 -08002897void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
nisse284542b2017-01-10 08:58:32 -08002898 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2899 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002900}
2901
kwiberg55b97fe2016-01-28 05:22:45 -08002902int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
2903 VoEMediaProcess& processObject) {
2904 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2905 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002906
kwiberg55b97fe2016-01-28 05:22:45 -08002907 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002908
kwiberg55b97fe2016-01-28 05:22:45 -08002909 if (kPlaybackPerChannel == type) {
2910 if (_outputExternalMediaCallbackPtr) {
2911 _engineStatisticsPtr->SetLastError(
2912 VE_INVALID_OPERATION, kTraceError,
2913 "Channel::RegisterExternalMediaProcessing() "
2914 "output external media already enabled");
2915 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002916 }
kwiberg55b97fe2016-01-28 05:22:45 -08002917 _outputExternalMediaCallbackPtr = &processObject;
2918 _outputExternalMedia = true;
2919 } else if (kRecordingPerChannel == type) {
2920 if (_inputExternalMediaCallbackPtr) {
2921 _engineStatisticsPtr->SetLastError(
2922 VE_INVALID_OPERATION, kTraceError,
2923 "Channel::RegisterExternalMediaProcessing() "
2924 "output external media already enabled");
2925 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002926 }
kwiberg55b97fe2016-01-28 05:22:45 -08002927 _inputExternalMediaCallbackPtr = &processObject;
2928 channel_state_.SetInputExternalMedia(true);
2929 }
2930 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002931}
2932
kwiberg55b97fe2016-01-28 05:22:45 -08002933int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
2934 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2935 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002936
kwiberg55b97fe2016-01-28 05:22:45 -08002937 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002938
kwiberg55b97fe2016-01-28 05:22:45 -08002939 if (kPlaybackPerChannel == type) {
2940 if (!_outputExternalMediaCallbackPtr) {
2941 _engineStatisticsPtr->SetLastError(
2942 VE_INVALID_OPERATION, kTraceWarning,
2943 "Channel::DeRegisterExternalMediaProcessing() "
2944 "output external media already disabled");
2945 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002946 }
kwiberg55b97fe2016-01-28 05:22:45 -08002947 _outputExternalMedia = false;
2948 _outputExternalMediaCallbackPtr = NULL;
2949 } else if (kRecordingPerChannel == type) {
2950 if (!_inputExternalMediaCallbackPtr) {
2951 _engineStatisticsPtr->SetLastError(
2952 VE_INVALID_OPERATION, kTraceWarning,
2953 "Channel::DeRegisterExternalMediaProcessing() "
2954 "input external media already disabled");
2955 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002956 }
kwiberg55b97fe2016-01-28 05:22:45 -08002957 channel_state_.SetInputExternalMedia(false);
2958 _inputExternalMediaCallbackPtr = NULL;
2959 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002960
kwiberg55b97fe2016-01-28 05:22:45 -08002961 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002962}
2963
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002964int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08002965 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2966 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002967
kwiberg55b97fe2016-01-28 05:22:45 -08002968 if (channel_state_.Get().playing) {
2969 _engineStatisticsPtr->SetLastError(
2970 VE_INVALID_OPERATION, kTraceError,
2971 "Channel::SetExternalMixing() "
2972 "external mixing cannot be changed while playing.");
2973 return -1;
2974 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002975
kwiberg55b97fe2016-01-28 05:22:45 -08002976 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002977
kwiberg55b97fe2016-01-28 05:22:45 -08002978 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002979}
2980
kwiberg55b97fe2016-01-28 05:22:45 -08002981int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2982 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002983}
2984
wu@webrtc.org24301a62013-12-13 19:17:43 +00002985void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2986 audio_coding_->GetDecodingCallStatistics(stats);
2987}
2988
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002989bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
2990 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08002991 rtc::CritScope lock(&video_sync_lock_);
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07002992 *jitter_buffer_delay_ms = audio_coding_->FilteredCurrentDelayMs();
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002993 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002994 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00002995}
2996
solenberg358057b2015-11-27 10:46:42 -08002997uint32_t Channel::GetDelayEstimate() const {
2998 int jitter_buffer_delay_ms = 0;
2999 int playout_buffer_delay_ms = 0;
3000 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3001 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3002}
3003
deadbeef74375882015-08-13 12:09:10 -07003004int Channel::LeastRequiredDelayMs() const {
3005 return audio_coding_->LeastRequiredDelayMs();
3006}
3007
kwiberg55b97fe2016-01-28 05:22:45 -08003008int Channel::SetMinimumPlayoutDelay(int delayMs) {
3009 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3010 "Channel::SetMinimumPlayoutDelay()");
3011 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3012 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3013 _engineStatisticsPtr->SetLastError(
3014 VE_INVALID_ARGUMENT, kTraceError,
3015 "SetMinimumPlayoutDelay() invalid min delay");
3016 return -1;
3017 }
3018 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3019 _engineStatisticsPtr->SetLastError(
3020 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3021 "SetMinimumPlayoutDelay() failed to set min playout delay");
3022 return -1;
3023 }
3024 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003025}
3026
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003027int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003028 uint32_t playout_timestamp_rtp = 0;
3029 {
tommi31fc21f2016-01-21 10:37:37 -08003030 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003031 playout_timestamp_rtp = playout_timestamp_rtp_;
3032 }
kwiberg55b97fe2016-01-28 05:22:45 -08003033 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003034 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07003035 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003036 "GetPlayoutTimestamp() failed to retrieve timestamp");
3037 return -1;
3038 }
deadbeef74375882015-08-13 12:09:10 -07003039 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003040 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003041}
3042
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003043int Channel::SetInitTimestamp(unsigned int timestamp) {
3044 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003045 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003046 if (channel_state_.Get().sending) {
3047 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3048 "SetInitTimestamp() already sending");
3049 return -1;
3050 }
3051 _rtpRtcpModule->SetStartTimestamp(timestamp);
3052 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003053}
3054
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003055int Channel::SetInitSequenceNumber(short sequenceNumber) {
3056 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3057 "Channel::SetInitSequenceNumber()");
3058 if (channel_state_.Get().sending) {
3059 _engineStatisticsPtr->SetLastError(
3060 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3061 return -1;
3062 }
3063 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3064 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003065}
3066
kwiberg55b97fe2016-01-28 05:22:45 -08003067int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3068 RtpReceiver** rtp_receiver) const {
3069 *rtpRtcpModule = _rtpRtcpModule.get();
3070 *rtp_receiver = rtp_receiver_.get();
3071 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003072}
3073
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003074// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3075// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003076int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003077 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003078 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003079
kwiberg55b97fe2016-01-28 05:22:45 -08003080 {
3081 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003082
kwiberg5a25d952016-08-17 07:31:12 -07003083 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003084 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3085 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3086 " doesnt exist");
3087 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003088 }
3089
kwiberg4ec01d92016-08-22 08:43:54 -07003090 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07003091 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003092 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3093 "Channel::MixOrReplaceAudioWithFile() file mixing "
3094 "failed");
3095 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003096 }
kwiberg55b97fe2016-01-28 05:22:45 -08003097 if (fileSamples == 0) {
3098 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3099 "Channel::MixOrReplaceAudioWithFile() file is ended");
3100 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003101 }
kwiberg55b97fe2016-01-28 05:22:45 -08003102 }
3103
3104 assert(_audioFrame.samples_per_channel_ == fileSamples);
3105
3106 if (_mixFileWithMicrophone) {
3107 // Currently file stream is always mono.
3108 // TODO(xians): Change the code when FilePlayer supports real stereo.
3109 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3110 1, fileSamples);
3111 } else {
3112 // Replace ACM audio with file.
3113 // Currently file stream is always mono.
3114 // TODO(xians): Change the code when FilePlayer supports real stereo.
3115 _audioFrame.UpdateFrame(
3116 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3117 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3118 }
3119 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003120}
3121
kwiberg55b97fe2016-01-28 05:22:45 -08003122int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3123 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003124
kwibergb7f89d62016-02-17 10:04:18 -08003125 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003126 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003127
kwiberg55b97fe2016-01-28 05:22:45 -08003128 {
3129 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003130
kwiberg5a25d952016-08-17 07:31:12 -07003131 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003132 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3133 "Channel::MixAudioWithFile() file mixing failed");
3134 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003135 }
3136
kwiberg55b97fe2016-01-28 05:22:45 -08003137 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07003138 if (output_file_player_->Get10msAudioFromFile(
3139 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003140 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3141 "Channel::MixAudioWithFile() file mixing failed");
3142 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003143 }
kwiberg55b97fe2016-01-28 05:22:45 -08003144 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003145
kwiberg55b97fe2016-01-28 05:22:45 -08003146 if (audioFrame.samples_per_channel_ == fileSamples) {
3147 // Currently file stream is always mono.
3148 // TODO(xians): Change the code when FilePlayer supports real stereo.
3149 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3150 fileSamples);
3151 } else {
3152 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3153 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3154 ") != "
3155 "fileSamples(%" PRIuS ")",
3156 audioFrame.samples_per_channel_, fileSamples);
3157 return -1;
3158 }
3159
3160 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003161}
3162
deadbeef74375882015-08-13 12:09:10 -07003163void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003164 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003165
henrik.lundin96bd5022016-04-06 04:13:56 -07003166 if (!jitter_buffer_playout_timestamp_) {
3167 // This can happen if this channel has not received any RTP packets. In
3168 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003169 return;
3170 }
3171
3172 uint16_t delay_ms = 0;
3173 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003174 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003175 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3176 " delay from the ADM");
3177 _engineStatisticsPtr->SetLastError(
3178 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3179 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3180 return;
3181 }
3182
henrik.lundin96bd5022016-04-06 04:13:56 -07003183 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3184 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003185
3186 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003187 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003188
kwiberg55b97fe2016-01-28 05:22:45 -08003189 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003190 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003191 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003192
3193 {
tommi31fc21f2016-01-21 10:37:37 -08003194 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003195 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003196 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003197 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003198 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003199 }
3200 playout_delay_ms_ = delay_ms;
3201 }
3202}
3203
kwiberg55b97fe2016-01-28 05:22:45 -08003204void Channel::RegisterReceiveCodecsToRTPModule() {
3205 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3206 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003207
kwiberg55b97fe2016-01-28 05:22:45 -08003208 CodecInst codec;
3209 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003210
kwiberg55b97fe2016-01-28 05:22:45 -08003211 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3212 // Open up the RTP/RTCP receiver for all supported codecs
3213 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003214 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003215 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3216 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3217 " to register %s (%d/%d/%" PRIuS
3218 "/%d) to RTP/RTCP "
3219 "receiver",
3220 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3221 codec.rate);
3222 } else {
3223 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3224 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3225 "(%d/%d/%" PRIuS
3226 "/%d) has been added to the RTP/RTCP "
3227 "receiver",
3228 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3229 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003230 }
kwiberg55b97fe2016-01-28 05:22:45 -08003231 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003232}
3233
kwiberg55b97fe2016-01-28 05:22:45 -08003234int Channel::SetSendRtpHeaderExtension(bool enable,
3235 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003236 unsigned char id) {
3237 int error = 0;
3238 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3239 if (enable) {
3240 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3241 }
3242 return error;
3243}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003244
ossue280cde2016-10-12 11:04:10 -07003245int Channel::GetRtpTimestampRateHz() const {
3246 const auto format = audio_coding_->ReceiveFormat();
3247 // Default to the playout frequency if we've not gotten any packets yet.
3248 // TODO(ossu): Zero clockrate can only happen if we've added an external
3249 // decoder for a format we don't support internally. Remove once that way of
3250 // adding decoders is gone!
3251 return (format && format->clockrate_hz != 0)
3252 ? format->clockrate_hz
3253 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003254}
3255
Minyue2013aec2015-05-13 14:14:42 +02003256int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003257 RtcpMode method = _rtpRtcpModule->RTCP();
3258 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003259 return 0;
3260 }
3261 std::vector<RTCPReportBlock> report_blocks;
3262 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003263
3264 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003265 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003266 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003267 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003268 Channel* channel = associate_send_channel_.channel();
3269 // Tries to get RTT from an associated channel. This is important for
3270 // receive-only channels.
3271 if (channel) {
3272 // To prevent infinite recursion and deadlock, calling GetRTT of
3273 // associate channel should always use "false" for argument:
3274 // |allow_associate_channel|.
3275 rtt = channel->GetRTT(false);
3276 }
3277 }
3278 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003279 }
3280
3281 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3282 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3283 for (; it != report_blocks.end(); ++it) {
3284 if (it->remoteSSRC == remoteSSRC)
3285 break;
3286 }
3287 if (it == report_blocks.end()) {
3288 // We have not received packets with SSRC matching the report blocks.
3289 // To calculate RTT we try with the SSRC of the first report block.
3290 // This is very important for send-only channels where we don't know
3291 // the SSRC of the other end.
3292 remoteSSRC = report_blocks[0].remoteSSRC;
3293 }
Minyue2013aec2015-05-13 14:14:42 +02003294
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003295 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003296 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003297 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003298 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3299 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003300 return 0;
3301 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003302 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003303}
3304
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003305} // namespace voe
3306} // namespace webrtc