blob: 6e2e91c0a1bd0c0e62ccc4a753ef940d12ec2849 [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
henrik.lundin50499422016-11-29 04:26:24 -080016#include "webrtc/base/array_view.h"
Ivo Creusenae856f22015-09-17 16:30:16 +020017#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080018#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000019#include "webrtc/base/format_macros.h"
pbosad856222015-11-27 09:48:36 -080020#include "webrtc/base/logging.h"
Erik Språng737336d2016-07-29 12:59:36 +020021#include "webrtc/base/rate_limiter.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010022#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000023#include "webrtc/base/timeutils.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020024#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070025#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070026#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000027#include "webrtc/modules/audio_device/include/audio_device.h"
28#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010029#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010030#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010031#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
32#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
33#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000034#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010035#include "webrtc/modules/utility/include/audio_frame_operations.h"
36#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.
616 audioFrame->Mute();
617 }
kwiberg55b97fe2016-01-28 05:22:45 -0800618
kwiberg55b97fe2016-01-28 05:22:45 -0800619 // Convert module ID to internal VoE channel ID
620 audioFrame->id_ = VoEChannelId(audioFrame->id_);
621 // Store speech type for dead-or-alive detection
622 _outputSpeechType = audioFrame->speech_type_;
623
624 ChannelState::State state = channel_state_.Get();
625
kwiberg55b97fe2016-01-28 05:22:45 -0800626 {
627 // Pass the audio buffers to an optional sink callback, before applying
628 // scaling/panning, as that applies to the mix operation.
629 // External recipients of the audio (e.g. via AudioTrack), will do their
630 // own mixing/dynamic processing.
631 rtc::CritScope cs(&_callbackCritSect);
632 if (audio_sink_) {
633 AudioSinkInterface::Data data(
634 &audioFrame->data_[0], audioFrame->samples_per_channel_,
635 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
636 audioFrame->timestamp_);
637 audio_sink_->OnData(data);
638 }
639 }
640
641 float output_gain = 1.0f;
642 float left_pan = 1.0f;
643 float right_pan = 1.0f;
644 {
645 rtc::CritScope cs(&volume_settings_critsect_);
646 output_gain = _outputGain;
647 left_pan = _panLeft;
648 right_pan = _panRight;
649 }
650
651 // Output volume scaling
652 if (output_gain < 0.99f || output_gain > 1.01f) {
653 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
654 }
655
656 // Scale left and/or right channel(s) if stereo and master balance is
657 // active
658
659 if (left_pan != 1.0f || right_pan != 1.0f) {
660 if (audioFrame->num_channels_ == 1) {
661 // Emulate stereo mode since panning is active.
662 // The mono signal is copied to both left and right channels here.
663 AudioFrameOperations::MonoToStereo(audioFrame);
664 }
665 // For true stereo mode (when we are receiving a stereo signal), no
666 // action is needed.
667
668 // Do the panning operation (the audio frame contains stereo at this
669 // stage)
670 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
671 }
672
673 // Mix decoded PCM output with file if file mixing is enabled
674 if (state.output_file_playing) {
675 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700676 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800677 }
678
679 // External media
680 if (_outputExternalMedia) {
681 rtc::CritScope cs(&_callbackCritSect);
682 const bool isStereo = (audioFrame->num_channels_ == 2);
683 if (_outputExternalMediaCallbackPtr) {
684 _outputExternalMediaCallbackPtr->Process(
685 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
686 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
687 isStereo);
688 }
689 }
690
691 // Record playout if enabled
692 {
693 rtc::CritScope cs(&_fileCritSect);
694
kwiberg5a25d952016-08-17 07:31:12 -0700695 if (_outputFileRecording && output_file_recorder_) {
696 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800697 }
698 }
699
700 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700701 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800702 _outputAudioLevel.ComputeLevel(*audioFrame);
703
704 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
705 // The first frame with a valid rtp timestamp.
706 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
707 }
708
709 if (capture_start_rtp_time_stamp_ >= 0) {
710 // audioFrame.timestamp_ should be valid from now on.
711
712 // Compute elapsed time.
713 int64_t unwrap_timestamp =
714 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
715 audioFrame->elapsed_time_ms_ =
716 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700717 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800718
niklase@google.com470e71d2011-07-07 08:21:25 +0000719 {
kwiberg55b97fe2016-01-28 05:22:45 -0800720 rtc::CritScope lock(&ts_stats_lock_);
721 // Compute ntp time.
722 audioFrame->ntp_time_ms_ =
723 ntp_estimator_.Estimate(audioFrame->timestamp_);
724 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
725 if (audioFrame->ntp_time_ms_ > 0) {
726 // Compute |capture_start_ntp_time_ms_| so that
727 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
728 capture_start_ntp_time_ms_ =
729 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000730 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000731 }
kwiberg55b97fe2016-01-28 05:22:45 -0800732 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000733
henrik.lundin42dda502016-05-18 05:36:01 -0700734 return muted ? MixerParticipant::AudioFrameInfo::kMuted
735 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000736}
737
aleloi6c278492016-10-20 14:24:39 -0700738AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
739 int sample_rate_hz,
740 AudioFrame* audio_frame) {
741 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700742
aleloi6c278492016-10-20 14:24:39 -0700743 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700744
745 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
746 FrameInfo new_audio_frame_info = FrameInfo::kError;
747 switch (frame_info) {
748 case MixerParticipant::AudioFrameInfo::kNormal:
749 new_audio_frame_info = FrameInfo::kNormal;
750 break;
751 case MixerParticipant::AudioFrameInfo::kMuted:
752 new_audio_frame_info = FrameInfo::kMuted;
753 break;
754 case MixerParticipant::AudioFrameInfo::kError:
755 new_audio_frame_info = FrameInfo::kError;
756 break;
757 }
aleloi6c278492016-10-20 14:24:39 -0700758 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700759}
760
kwiberg55b97fe2016-01-28 05:22:45 -0800761int32_t Channel::NeededFrequency(int32_t id) const {
762 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
763 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000764
kwiberg55b97fe2016-01-28 05:22:45 -0800765 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000766
kwiberg55b97fe2016-01-28 05:22:45 -0800767 // Determine highest needed receive frequency
768 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000769
kwiberg55b97fe2016-01-28 05:22:45 -0800770 // Return the bigger of playout and receive frequency in the ACM.
771 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
772 highestNeeded = audio_coding_->PlayoutFrequency();
773 } else {
774 highestNeeded = receiveFrequency;
775 }
776
777 // Special case, if we're playing a file on the playout side
778 // we take that frequency into consideration as well
779 // This is not needed on sending side, since the codec will
780 // limit the spectrum anyway.
781 if (channel_state_.Get().output_file_playing) {
782 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700783 if (output_file_player_) {
784 if (output_file_player_->Frequency() > highestNeeded) {
785 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800786 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000787 }
kwiberg55b97fe2016-01-28 05:22:45 -0800788 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000789
kwiberg55b97fe2016-01-28 05:22:45 -0800790 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000791}
792
ossu5f7cfa52016-05-30 08:11:28 -0700793int32_t Channel::CreateChannel(
794 Channel*& channel,
795 int32_t channelId,
796 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700797 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800798 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
799 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
800 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000801
solenberg88499ec2016-09-07 07:34:41 -0700802 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800803 if (channel == NULL) {
804 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
805 "Channel::CreateChannel() unable to allocate memory for"
806 " channel");
807 return -1;
808 }
809 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000810}
811
kwiberg55b97fe2016-01-28 05:22:45 -0800812void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
813 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
814 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
815 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000816
kwiberg55b97fe2016-01-28 05:22:45 -0800817 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000818}
819
kwiberg55b97fe2016-01-28 05:22:45 -0800820void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
821 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
822 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
823 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000824
kwiberg55b97fe2016-01-28 05:22:45 -0800825 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000826}
827
kwiberg55b97fe2016-01-28 05:22:45 -0800828void Channel::PlayFileEnded(int32_t id) {
829 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
830 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000831
kwiberg55b97fe2016-01-28 05:22:45 -0800832 if (id == _inputFilePlayerId) {
833 channel_state_.SetInputFilePlaying(false);
834 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
835 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000836 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800837 } else if (id == _outputFilePlayerId) {
838 channel_state_.SetOutputFilePlaying(false);
839 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
840 "Channel::PlayFileEnded() => output file player module is"
841 " shutdown");
842 }
843}
844
845void Channel::RecordFileEnded(int32_t id) {
846 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
847 "Channel::RecordFileEnded(id=%d)", id);
848
849 assert(id == _outputFileRecorderId);
850
851 rtc::CritScope cs(&_fileCritSect);
852
853 _outputFileRecording = false;
854 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
855 "Channel::RecordFileEnded() => output file recorder module is"
856 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000857}
858
pbos@webrtc.org92135212013-05-14 08:31:39 +0000859Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000860 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700861 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800862 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100863 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700864 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800865 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100866 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800867 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100868 rtp_receive_statistics_(
869 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
870 rtp_receiver_(
871 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100872 this,
873 this,
874 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700875 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 _outputAudioLevel(),
877 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100878 // Avoid conflict with other channels by adding 1024 - 1026,
879 // won't use as much as 1024 channels.
880 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
881 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
882 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
883 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100884 _outputExternalMedia(false),
885 _inputExternalMediaCallbackPtr(NULL),
886 _outputExternalMediaCallbackPtr(NULL),
887 _timeStamp(0), // This is just an offset, RTP module will add it's own
888 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100889 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100890 playout_timestamp_rtp_(0),
891 playout_timestamp_rtcp_(0),
892 playout_delay_ms_(0),
893 _numberOfDiscardedPackets(0),
894 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100895 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
896 capture_start_rtp_time_stamp_(-1),
897 capture_start_ntp_time_ms_(-1),
898 _engineStatisticsPtr(NULL),
899 _outputMixerPtr(NULL),
900 _transmitMixerPtr(NULL),
901 _moduleProcessThreadPtr(NULL),
902 _audioDeviceModulePtr(NULL),
903 _voiceEngineObserverPtr(NULL),
904 _callbackCritSectPtr(NULL),
905 _transportPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100906 _sendFrameType(0),
907 _externalMixing(false),
908 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700909 input_mute_(false),
910 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100911 _panLeft(1.0f),
912 _panRight(1.0f),
913 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100914 _lastLocalTimeStamp(0),
915 _lastPayloadType(0),
916 _includeAudioLevelIndication(false),
917 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100918 restored_packet_in_use_(false),
919 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100920 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700921 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800922 feedback_observer_proxy_(new TransportFeedbackProxy()),
923 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700924 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200925 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
926 kMaxRetransmissionWindowMs)),
michaelt2fedf9c2016-11-28 02:34:18 -0800927 decoder_factory_(config.acm_config.decoder_factory),
928 // Bitrate smoother can be initialized with arbitrary time constant
929 // (0 used here). The actual time constant will be set in SetBitRate.
930 bitrate_smoother_(0, Clock::GetRealTimeClock()) {
kwiberg55b97fe2016-01-28 05:22:45 -0800931 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
932 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700933 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800934 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700935 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800936 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200937
kwiberg55b97fe2016-01-28 05:22:45 -0800938 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000939
kwiberg55b97fe2016-01-28 05:22:45 -0800940 RtpRtcp::Configuration configuration;
941 configuration.audio = true;
942 configuration.outgoing_transport = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800943 configuration.receive_statistics = rtp_receive_statistics_.get();
944 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800945 if (pacing_enabled_) {
946 configuration.paced_sender = rtp_packet_sender_proxy_.get();
947 configuration.transport_sequence_number_allocator =
948 seq_num_allocator_proxy_.get();
949 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
950 }
ivoc14d5dbe2016-07-04 07:06:55 -0700951 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800952 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200953 configuration.retransmission_rate_limiter =
954 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000955
kwiberg55b97fe2016-01-28 05:22:45 -0800956 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100957 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000958
kwiberg55b97fe2016-01-28 05:22:45 -0800959 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
960 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
961 statistics_proxy_.get());
niklase@google.com470e71d2011-07-07 08:21:25 +0000962}
963
kwiberg55b97fe2016-01-28 05:22:45 -0800964Channel::~Channel() {
965 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
966 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
967 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000968
kwiberg55b97fe2016-01-28 05:22:45 -0800969 if (_outputExternalMedia) {
970 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
971 }
972 if (channel_state_.Get().input_external_media) {
973 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
974 }
975 StopSend();
976 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000977
kwiberg55b97fe2016-01-28 05:22:45 -0800978 {
979 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700980 if (input_file_player_) {
981 input_file_player_->RegisterModuleFileCallback(NULL);
982 input_file_player_->StopPlayingFile();
niklase@google.com470e71d2011-07-07 08:21:25 +0000983 }
kwiberg5a25d952016-08-17 07:31:12 -0700984 if (output_file_player_) {
985 output_file_player_->RegisterModuleFileCallback(NULL);
986 output_file_player_->StopPlayingFile();
kwiberg55b97fe2016-01-28 05:22:45 -0800987 }
kwiberg5a25d952016-08-17 07:31:12 -0700988 if (output_file_recorder_) {
989 output_file_recorder_->RegisterModuleFileCallback(NULL);
990 output_file_recorder_->StopRecording();
kwiberg55b97fe2016-01-28 05:22:45 -0800991 }
992 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000993
kwiberg55b97fe2016-01-28 05:22:45 -0800994 // The order to safely shutdown modules in a channel is:
995 // 1. De-register callbacks in modules
996 // 2. De-register modules in process thread
997 // 3. Destroy modules
998 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
999 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1000 "~Channel() failed to de-register transport callback"
1001 " (Audio coding module)");
1002 }
1003 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1004 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1005 "~Channel() failed to de-register VAD callback"
1006 " (Audio coding module)");
1007 }
1008 // De-register modules in process thread
1009 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +00001010
kwiberg55b97fe2016-01-28 05:22:45 -08001011 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +00001012}
1013
kwiberg55b97fe2016-01-28 05:22:45 -08001014int32_t Channel::Init() {
1015 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1016 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001017
kwiberg55b97fe2016-01-28 05:22:45 -08001018 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001019
kwiberg55b97fe2016-01-28 05:22:45 -08001020 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +00001021
kwiberg55b97fe2016-01-28 05:22:45 -08001022 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
1023 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1024 "Channel::Init() must call SetEngineInformation() first");
1025 return -1;
1026 }
1027
1028 // --- Add modules to process thread (for periodic schedulation)
1029
1030 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
1031
1032 // --- ACM initialization
1033
1034 if (audio_coding_->InitializeReceiver() == -1) {
1035 _engineStatisticsPtr->SetLastError(
1036 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1037 "Channel::Init() unable to initialize the ACM - 1");
1038 return -1;
1039 }
1040
1041 // --- RTP/RTCP module initialization
1042
1043 // Ensure that RTCP is enabled by default for the created channel.
1044 // Note that, the module will keep generating RTCP until it is explicitly
1045 // disabled by the user.
1046 // After StopListen (when no sockets exists), RTCP packets will no longer
1047 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -07001048 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001049 // RTCP is enabled by default.
1050 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1051 // --- Register all permanent callbacks
1052 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
1053 (audio_coding_->RegisterVADCallback(this) == -1);
1054
1055 if (fail) {
1056 _engineStatisticsPtr->SetLastError(
1057 VE_CANNOT_INIT_CHANNEL, kTraceError,
1058 "Channel::Init() callbacks not registered");
1059 return -1;
1060 }
1061
1062 // --- Register all supported codecs to the receiving side of the
1063 // RTP/RTCP module
1064
1065 CodecInst codec;
1066 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1067
1068 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1069 // Open up the RTP/RTCP receiver for all supported codecs
1070 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001071 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001072 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1073 "Channel::Init() unable to register %s "
1074 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1075 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1076 codec.rate);
1077 } else {
1078 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1079 "Channel::Init() %s (%d/%d/%" PRIuS
1080 "/%d) has been "
1081 "added to the RTP/RTCP receiver",
1082 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1083 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001084 }
1085
kwiberg55b97fe2016-01-28 05:22:45 -08001086 // Ensure that PCMU is used as default codec on the sending side
1087 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1088 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001089 }
1090
kwiberg55b97fe2016-01-28 05:22:45 -08001091 // Register default PT for outband 'telephone-event'
1092 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001093 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
kwibergda2bf4e2016-10-24 13:47:09 -07001094 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1095 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001096 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1097 "Channel::Init() failed to register outband "
1098 "'telephone-event' (%d/%d) correctly",
1099 codec.pltype, codec.plfreq);
1100 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001101 }
1102
kwiberg55b97fe2016-01-28 05:22:45 -08001103 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001104 if (!codec_manager_.RegisterEncoder(codec) ||
1105 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
kwibergda2bf4e2016-10-24 13:47:09 -07001106 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1107 CodecInstToSdp(codec)) ||
kwibergc8d071e2016-04-06 12:22:38 -07001108 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001109 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1110 "Channel::Init() failed to register CN (%d/%d) "
1111 "correctly - 1",
1112 codec.pltype, codec.plfreq);
1113 }
1114 }
kwiberg55b97fe2016-01-28 05:22:45 -08001115 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001116
kwiberg55b97fe2016-01-28 05:22:45 -08001117 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001118}
1119
kwiberg55b97fe2016-01-28 05:22:45 -08001120int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1121 OutputMixer& outputMixer,
1122 voe::TransmitMixer& transmitMixer,
1123 ProcessThread& moduleProcessThread,
1124 AudioDeviceModule& audioDeviceModule,
1125 VoiceEngineObserver* voiceEngineObserver,
1126 rtc::CriticalSection* callbackCritSect) {
1127 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1128 "Channel::SetEngineInformation()");
1129 _engineStatisticsPtr = &engineStatistics;
1130 _outputMixerPtr = &outputMixer;
1131 _transmitMixerPtr = &transmitMixer,
1132 _moduleProcessThreadPtr = &moduleProcessThread;
1133 _audioDeviceModulePtr = &audioDeviceModule;
1134 _voiceEngineObserverPtr = voiceEngineObserver;
1135 _callbackCritSectPtr = callbackCritSect;
1136 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001137}
1138
kwiberg55b97fe2016-01-28 05:22:45 -08001139int32_t Channel::UpdateLocalTimeStamp() {
1140 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1141 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001142}
1143
kwibergb7f89d62016-02-17 10:04:18 -08001144void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001145 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001146 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001147}
1148
ossu29b1a8d2016-06-13 07:34:51 -07001149const rtc::scoped_refptr<AudioDecoderFactory>&
1150Channel::GetAudioDecoderFactory() const {
1151 return decoder_factory_;
1152}
1153
kwiberg55b97fe2016-01-28 05:22:45 -08001154int32_t Channel::StartPlayout() {
1155 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1156 "Channel::StartPlayout()");
1157 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001158 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001159 }
1160
1161 if (!_externalMixing) {
1162 // Add participant as candidates for mixing.
1163 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1164 _engineStatisticsPtr->SetLastError(
1165 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1166 "StartPlayout() failed to add participant to mixer");
1167 return -1;
1168 }
1169 }
1170
1171 channel_state_.SetPlaying(true);
1172 if (RegisterFilePlayingToMixer() != 0)
1173 return -1;
1174
1175 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001176}
1177
kwiberg55b97fe2016-01-28 05:22:45 -08001178int32_t Channel::StopPlayout() {
1179 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1180 "Channel::StopPlayout()");
1181 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001182 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001183 }
1184
1185 if (!_externalMixing) {
1186 // Remove participant as candidates for mixing
1187 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1188 _engineStatisticsPtr->SetLastError(
1189 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1190 "StopPlayout() failed to remove participant from mixer");
1191 return -1;
1192 }
1193 }
1194
1195 channel_state_.SetPlaying(false);
1196 _outputAudioLevel.Clear();
1197
1198 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001199}
1200
kwiberg55b97fe2016-01-28 05:22:45 -08001201int32_t Channel::StartSend() {
1202 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1203 "Channel::StartSend()");
1204 // Resume the previous sequence number which was reset by StopSend().
1205 // This needs to be done before |sending| is set to true.
1206 if (send_sequence_number_)
1207 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001208
kwiberg55b97fe2016-01-28 05:22:45 -08001209 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001210 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001211 }
1212 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001213
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001214 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001215 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1216 _engineStatisticsPtr->SetLastError(
1217 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1218 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001219 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001220 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001221 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001222 return -1;
1223 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001224
kwiberg55b97fe2016-01-28 05:22:45 -08001225 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001226}
1227
kwiberg55b97fe2016-01-28 05:22:45 -08001228int32_t Channel::StopSend() {
1229 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1230 "Channel::StopSend()");
1231 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001232 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001233 }
1234 channel_state_.SetSending(false);
1235
1236 // Store the sequence number to be able to pick up the same sequence for
1237 // the next StartSend(). This is needed for restarting device, otherwise
1238 // it might cause libSRTP to complain about packets being replayed.
1239 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1240 // CL is landed. See issue
1241 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1242 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1243
1244 // Reset sending SSRC and sequence number and triggers direct transmission
1245 // of RTCP BYE
1246 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1247 _engineStatisticsPtr->SetLastError(
1248 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1249 "StartSend() RTP/RTCP failed to stop sending");
1250 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001251 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001252
1253 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001254}
1255
solenberge566ac72016-10-31 12:52:33 -07001256void Channel::ResetDiscardedPacketCount() {
kwiberg55b97fe2016-01-28 05:22:45 -08001257 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberge566ac72016-10-31 12:52:33 -07001258 "Channel::ResetDiscardedPacketCount()");
kwiberg55b97fe2016-01-28 05:22:45 -08001259 _numberOfDiscardedPackets = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001260}
1261
kwiberg55b97fe2016-01-28 05:22:45 -08001262int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1263 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1264 "Channel::RegisterVoiceEngineObserver()");
1265 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001266
kwiberg55b97fe2016-01-28 05:22:45 -08001267 if (_voiceEngineObserverPtr) {
1268 _engineStatisticsPtr->SetLastError(
1269 VE_INVALID_OPERATION, kTraceError,
1270 "RegisterVoiceEngineObserver() observer already enabled");
1271 return -1;
1272 }
1273 _voiceEngineObserverPtr = &observer;
1274 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001275}
1276
kwiberg55b97fe2016-01-28 05:22:45 -08001277int32_t Channel::DeRegisterVoiceEngineObserver() {
1278 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1279 "Channel::DeRegisterVoiceEngineObserver()");
1280 rtc::CritScope cs(&_callbackCritSect);
1281
1282 if (!_voiceEngineObserverPtr) {
1283 _engineStatisticsPtr->SetLastError(
1284 VE_INVALID_OPERATION, kTraceWarning,
1285 "DeRegisterVoiceEngineObserver() observer already disabled");
1286 return 0;
1287 }
1288 _voiceEngineObserverPtr = NULL;
1289 return 0;
1290}
1291
1292int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001293 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001294 if (send_codec) {
1295 codec = *send_codec;
1296 return 0;
1297 }
1298 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001299}
1300
kwiberg55b97fe2016-01-28 05:22:45 -08001301int32_t Channel::GetRecCodec(CodecInst& codec) {
1302 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001303}
1304
kwiberg55b97fe2016-01-28 05:22:45 -08001305int32_t Channel::SetSendCodec(const CodecInst& codec) {
1306 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1307 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001308
kwibergc8d071e2016-04-06 12:22:38 -07001309 if (!codec_manager_.RegisterEncoder(codec) ||
1310 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001311 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1312 "SetSendCodec() failed to register codec to ACM");
1313 return -1;
1314 }
1315
1316 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1317 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1318 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1319 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1320 "SetSendCodec() failed to register codec to"
1321 " RTP/RTCP module");
1322 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001323 }
kwiberg55b97fe2016-01-28 05:22:45 -08001324 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001325
kwiberg55b97fe2016-01-28 05:22:45 -08001326 if (_rtpRtcpModule->SetAudioPacketSize(codec.pacsize) != 0) {
1327 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1328 "SetSendCodec() failed to set audio packet size");
1329 return -1;
1330 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001331
kwiberg55b97fe2016-01-28 05:22:45 -08001332 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001333}
1334
minyue78b4d562016-11-30 04:47:39 -08001335void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001336 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1337 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001338 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1339 if (*encoder)
1340 (*encoder)->OnReceivedTargetAudioBitrate(bitrate_bps);
1341 });
Erik Språng737336d2016-07-29 12:59:36 +02001342 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
michaelt2fedf9c2016-11-28 02:34:18 -08001343
1344 // We give smoothed bitrate allocation to audio network adaptor as
1345 // the uplink bandwidth.
minyue78b4d562016-11-30 04:47:39 -08001346 // The probing spikes should not affect the bitrate smoother more than 25%.
1347 // To simplify the calculations we use a step response as input signal.
1348 // The step response of an exponential filter is
1349 // u(t) = 1 - e^(-t / time_constant).
1350 // In order to limit the affect of a BWE spike within 25% of its value before
1351 // the next probing, we would choose a time constant that fulfills
1352 // 1 - e^(-probing_interval_ms / time_constant) < 0.25
1353 // Then 4 * probing_interval_ms is a good choice.
1354 bitrate_smoother_.SetTimeConstantMs(probing_interval_ms * 4);
michaelt2fedf9c2016-11-28 02:34:18 -08001355 bitrate_smoother_.AddSample(bitrate_bps);
1356 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1357 if (*encoder) {
1358 (*encoder)->OnReceivedUplinkBandwidth(
1359 static_cast<int>(*bitrate_smoother_.GetAverage()));
1360 }
1361 });
Ivo Creusenadf89b72015-04-29 16:03:33 +02001362}
1363
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001364void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue7e304322016-10-12 05:00:55 -07001365 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1366 if (*encoder)
1367 (*encoder)->OnReceivedUplinkPacketLossFraction(fraction_lost / 255.0f);
1368 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001369}
1370
kwiberg55b97fe2016-01-28 05:22:45 -08001371int32_t Channel::SetVADStatus(bool enableVAD,
1372 ACMVADMode mode,
1373 bool disableDTX) {
1374 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1375 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001376 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1377 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1378 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001379 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1380 kTraceError,
1381 "SetVADStatus() failed to set VAD");
1382 return -1;
1383 }
1384 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001385}
1386
kwiberg55b97fe2016-01-28 05:22:45 -08001387int32_t Channel::GetVADStatus(bool& enabledVAD,
1388 ACMVADMode& mode,
1389 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001390 const auto* params = codec_manager_.GetStackParams();
1391 enabledVAD = params->use_cng;
1392 mode = params->vad_mode;
1393 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001394 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001395}
1396
kwiberg55b97fe2016-01-28 05:22:45 -08001397int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1398 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1399 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001400
kwiberg55b97fe2016-01-28 05:22:45 -08001401 if (channel_state_.Get().playing) {
1402 _engineStatisticsPtr->SetLastError(
1403 VE_ALREADY_PLAYING, kTraceError,
1404 "SetRecPayloadType() unable to set PT while playing");
1405 return -1;
1406 }
kwiberg55b97fe2016-01-28 05:22:45 -08001407
1408 if (codec.pltype == -1) {
1409 // De-register the selected codec (RTP/RTCP module and ACM)
1410
1411 int8_t pltype(-1);
1412 CodecInst rxCodec = codec;
1413
1414 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001415 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001416 rxCodec.pltype = pltype;
1417
1418 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1419 _engineStatisticsPtr->SetLastError(
1420 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1421 "SetRecPayloadType() RTP/RTCP-module deregistration "
1422 "failed");
1423 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001424 }
kwiberg55b97fe2016-01-28 05:22:45 -08001425 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1426 _engineStatisticsPtr->SetLastError(
1427 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1428 "SetRecPayloadType() ACM deregistration failed - 1");
1429 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001430 }
kwiberg55b97fe2016-01-28 05:22:45 -08001431 return 0;
1432 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001433
magjed56124bd2016-11-24 09:34:46 -08001434 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001435 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001436 // TODO(kwiberg): Retrying is probably not necessary, since
1437 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001438 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001439 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001440 _engineStatisticsPtr->SetLastError(
1441 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1442 "SetRecPayloadType() RTP/RTCP-module registration failed");
1443 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001444 }
kwiberg55b97fe2016-01-28 05:22:45 -08001445 }
kwibergda2bf4e2016-10-24 13:47:09 -07001446 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1447 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001448 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergda2bf4e2016-10-24 13:47:09 -07001449 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1450 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001451 _engineStatisticsPtr->SetLastError(
1452 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1453 "SetRecPayloadType() ACM registration failed - 1");
1454 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001455 }
kwiberg55b97fe2016-01-28 05:22:45 -08001456 }
1457 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001458}
1459
kwiberg55b97fe2016-01-28 05:22:45 -08001460int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1461 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001462 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001463 _engineStatisticsPtr->SetLastError(
1464 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1465 "GetRecPayloadType() failed to retrieve RX payload type");
1466 return -1;
1467 }
1468 codec.pltype = payloadType;
1469 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001470}
1471
kwiberg55b97fe2016-01-28 05:22:45 -08001472int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1473 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1474 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001475
kwiberg55b97fe2016-01-28 05:22:45 -08001476 CodecInst codec;
1477 int32_t samplingFreqHz(-1);
1478 const size_t kMono = 1;
1479 if (frequency == kFreq32000Hz)
1480 samplingFreqHz = 32000;
1481 else if (frequency == kFreq16000Hz)
1482 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001483
kwiberg55b97fe2016-01-28 05:22:45 -08001484 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1485 _engineStatisticsPtr->SetLastError(
1486 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1487 "SetSendCNPayloadType() failed to retrieve default CN codec "
1488 "settings");
1489 return -1;
1490 }
1491
1492 // Modify the payload type (must be set to dynamic range)
1493 codec.pltype = type;
1494
kwibergc8d071e2016-04-06 12:22:38 -07001495 if (!codec_manager_.RegisterEncoder(codec) ||
1496 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001497 _engineStatisticsPtr->SetLastError(
1498 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1499 "SetSendCNPayloadType() failed to register CN to ACM");
1500 return -1;
1501 }
1502
1503 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1504 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1505 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1506 _engineStatisticsPtr->SetLastError(
1507 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1508 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1509 "module");
1510 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001511 }
kwiberg55b97fe2016-01-28 05:22:45 -08001512 }
1513 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001514}
1515
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001516int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001517 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001518 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001519
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001520 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001521 _engineStatisticsPtr->SetLastError(
1522 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001523 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001524 return -1;
1525 }
1526 return 0;
1527}
1528
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001529int Channel::SetOpusDtx(bool enable_dtx) {
1530 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1531 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001532 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001533 : audio_coding_->DisableOpusDtx();
1534 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001535 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1536 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001537 return -1;
1538 }
1539 return 0;
1540}
1541
ivoc85228d62016-07-27 04:53:47 -07001542int Channel::GetOpusDtx(bool* enabled) {
1543 int success = -1;
1544 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1545 if (encoder) {
1546 *enabled = encoder->GetDtx();
1547 success = 0;
1548 }
1549 });
1550 return success;
1551}
1552
minyue7e304322016-10-12 05:00:55 -07001553bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1554 bool success = false;
1555 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1556 if (*encoder) {
1557 success = (*encoder)->EnableAudioNetworkAdaptor(
1558 config_string, Clock::GetRealTimeClock());
1559 }
1560 });
1561 return success;
1562}
1563
1564void Channel::DisableAudioNetworkAdaptor() {
1565 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1566 if (*encoder)
1567 (*encoder)->DisableAudioNetworkAdaptor();
1568 });
1569}
1570
1571void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1572 int max_frame_length_ms) {
1573 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1574 if (*encoder) {
1575 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1576 max_frame_length_ms);
1577 }
1578 });
1579}
1580
mflodman3d7db262016-04-29 00:57:13 -07001581int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001582 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001583 "Channel::RegisterExternalTransport()");
1584
kwiberg55b97fe2016-01-28 05:22:45 -08001585 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001586 if (_externalTransport) {
1587 _engineStatisticsPtr->SetLastError(
1588 VE_INVALID_OPERATION, kTraceError,
1589 "RegisterExternalTransport() external transport already enabled");
1590 return -1;
1591 }
1592 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001593 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001594 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001595}
1596
kwiberg55b97fe2016-01-28 05:22:45 -08001597int32_t Channel::DeRegisterExternalTransport() {
1598 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1599 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001600
kwiberg55b97fe2016-01-28 05:22:45 -08001601 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001602 if (_transportPtr) {
1603 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1604 "DeRegisterExternalTransport() all transport is disabled");
1605 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001606 _engineStatisticsPtr->SetLastError(
1607 VE_INVALID_OPERATION, kTraceWarning,
1608 "DeRegisterExternalTransport() external transport already "
1609 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001610 }
1611 _externalTransport = false;
1612 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001613 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001614}
1615
mflodman3d7db262016-04-29 00:57:13 -07001616int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001617 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001618 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001619 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001620 "Channel::ReceivedRTPPacket()");
1621
1622 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001623 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001624
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001625 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001626 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1627 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1628 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001629 return -1;
1630 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001631 header.payload_type_frequency =
1632 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001633 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001634 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001635 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001636 rtp_receive_statistics_->IncomingPacket(
1637 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001638 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001639
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001640 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001641}
1642
1643bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001644 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001645 const RTPHeader& header,
1646 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001647 if (rtp_payload_registry_->IsRtx(header)) {
1648 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001649 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001650 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001651 assert(packet_length >= header.headerLength);
1652 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001653 PayloadUnion payload_specific;
1654 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001655 &payload_specific)) {
1656 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001657 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001658 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1659 payload_specific, in_order);
1660}
1661
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001662bool Channel::HandleRtxPacket(const uint8_t* packet,
1663 size_t packet_length,
1664 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001665 if (!rtp_payload_registry_->IsRtx(header))
1666 return false;
1667
1668 // Remove the RTX header and parse the original RTP header.
1669 if (packet_length < header.headerLength)
1670 return false;
1671 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1672 return false;
1673 if (restored_packet_in_use_) {
1674 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1675 "Multiple RTX headers detected, dropping packet");
1676 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001677 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001678 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001679 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1680 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001681 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1682 "Incoming RTX packet: invalid RTP header");
1683 return false;
1684 }
1685 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001686 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001687 restored_packet_in_use_ = false;
1688 return ret;
1689}
1690
1691bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1692 StreamStatistician* statistician =
1693 rtp_receive_statistics_->GetStatistician(header.ssrc);
1694 if (!statistician)
1695 return false;
1696 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001697}
1698
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001699bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1700 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001701 // Retransmissions are handled separately if RTX is enabled.
1702 if (rtp_payload_registry_->RtxEnabled())
1703 return false;
1704 StreamStatistician* statistician =
1705 rtp_receive_statistics_->GetStatistician(header.ssrc);
1706 if (!statistician)
1707 return false;
1708 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001709 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001710 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001711 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001712}
1713
mflodman3d7db262016-04-29 00:57:13 -07001714int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001715 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001716 "Channel::ReceivedRTCPPacket()");
1717 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001718 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001719
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001720 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001721 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001722 _engineStatisticsPtr->SetLastError(
1723 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1724 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1725 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001726
Minyue2013aec2015-05-13 14:14:42 +02001727 int64_t rtt = GetRTT(true);
1728 if (rtt == 0) {
1729 // Waiting for valid RTT.
1730 return 0;
1731 }
Erik Språng737336d2016-07-29 12:59:36 +02001732
1733 int64_t nack_window_ms = rtt;
1734 if (nack_window_ms < kMinRetransmissionWindowMs) {
1735 nack_window_ms = kMinRetransmissionWindowMs;
1736 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1737 nack_window_ms = kMaxRetransmissionWindowMs;
1738 }
1739 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1740
minyue7e304322016-10-12 05:00:55 -07001741 // Invoke audio encoders OnReceivedRtt().
1742 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1743 if (*encoder)
1744 (*encoder)->OnReceivedRtt(rtt);
1745 });
1746
Minyue2013aec2015-05-13 14:14:42 +02001747 uint32_t ntp_secs = 0;
1748 uint32_t ntp_frac = 0;
1749 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001750 if (0 !=
1751 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1752 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001753 // Waiting for RTCP.
1754 return 0;
1755 }
1756
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001757 {
tommi31fc21f2016-01-21 10:37:37 -08001758 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001759 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001760 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001761 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001762}
1763
niklase@google.com470e71d2011-07-07 08:21:25 +00001764int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001765 bool loop,
1766 FileFormats format,
1767 int startPosition,
1768 float volumeScaling,
1769 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001770 const CodecInst* codecInst) {
1771 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1772 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1773 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1774 "stopPosition=%d)",
1775 fileName, loop, format, volumeScaling, startPosition,
1776 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001777
kwiberg55b97fe2016-01-28 05:22:45 -08001778 if (channel_state_.Get().output_file_playing) {
1779 _engineStatisticsPtr->SetLastError(
1780 VE_ALREADY_PLAYING, kTraceError,
1781 "StartPlayingFileLocally() is already playing");
1782 return -1;
1783 }
1784
1785 {
1786 rtc::CritScope cs(&_fileCritSect);
1787
kwiberg5a25d952016-08-17 07:31:12 -07001788 if (output_file_player_) {
1789 output_file_player_->RegisterModuleFileCallback(NULL);
1790 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001791 }
1792
kwiberg5b356f42016-09-08 04:32:33 -07001793 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001794 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001795
kwiberg5a25d952016-08-17 07:31:12 -07001796 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001797 _engineStatisticsPtr->SetLastError(
1798 VE_INVALID_ARGUMENT, kTraceError,
1799 "StartPlayingFileLocally() filePlayer format is not correct");
1800 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001801 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001802
kwiberg55b97fe2016-01-28 05:22:45 -08001803 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001804
kwiberg5a25d952016-08-17 07:31:12 -07001805 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001806 fileName, loop, startPosition, volumeScaling, notificationTime,
1807 stopPosition, (const CodecInst*)codecInst) != 0) {
1808 _engineStatisticsPtr->SetLastError(
1809 VE_BAD_FILE, kTraceError,
1810 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001811 output_file_player_->StopPlayingFile();
1812 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001813 return -1;
1814 }
kwiberg5a25d952016-08-17 07:31:12 -07001815 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001816 channel_state_.SetOutputFilePlaying(true);
1817 }
1818
1819 if (RegisterFilePlayingToMixer() != 0)
1820 return -1;
1821
1822 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001823}
1824
1825int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001826 FileFormats format,
1827 int startPosition,
1828 float volumeScaling,
1829 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001830 const CodecInst* codecInst) {
1831 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1832 "Channel::StartPlayingFileLocally(format=%d,"
1833 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1834 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001835
kwiberg55b97fe2016-01-28 05:22:45 -08001836 if (stream == NULL) {
1837 _engineStatisticsPtr->SetLastError(
1838 VE_BAD_FILE, kTraceError,
1839 "StartPlayingFileLocally() NULL as input stream");
1840 return -1;
1841 }
1842
1843 if (channel_state_.Get().output_file_playing) {
1844 _engineStatisticsPtr->SetLastError(
1845 VE_ALREADY_PLAYING, kTraceError,
1846 "StartPlayingFileLocally() is already playing");
1847 return -1;
1848 }
1849
1850 {
1851 rtc::CritScope cs(&_fileCritSect);
1852
1853 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001854 if (output_file_player_) {
1855 output_file_player_->RegisterModuleFileCallback(NULL);
1856 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001857 }
1858
kwiberg55b97fe2016-01-28 05:22:45 -08001859 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001860 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001861 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001862
kwiberg5a25d952016-08-17 07:31:12 -07001863 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001864 _engineStatisticsPtr->SetLastError(
1865 VE_INVALID_ARGUMENT, kTraceError,
1866 "StartPlayingFileLocally() filePlayer format isnot correct");
1867 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001868 }
1869
kwiberg55b97fe2016-01-28 05:22:45 -08001870 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001871
kwiberg4ec01d92016-08-22 08:43:54 -07001872 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001873 volumeScaling, notificationTime,
1874 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001875 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1876 "StartPlayingFile() failed to "
1877 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001878 output_file_player_->StopPlayingFile();
1879 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001880 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001881 }
kwiberg5a25d952016-08-17 07:31:12 -07001882 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001883 channel_state_.SetOutputFilePlaying(true);
1884 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001885
kwiberg55b97fe2016-01-28 05:22:45 -08001886 if (RegisterFilePlayingToMixer() != 0)
1887 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001888
kwiberg55b97fe2016-01-28 05:22:45 -08001889 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001890}
1891
kwiberg55b97fe2016-01-28 05:22:45 -08001892int Channel::StopPlayingFileLocally() {
1893 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1894 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001895
kwiberg55b97fe2016-01-28 05:22:45 -08001896 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001897 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001898 }
1899
1900 {
1901 rtc::CritScope cs(&_fileCritSect);
1902
kwiberg5a25d952016-08-17 07:31:12 -07001903 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001904 _engineStatisticsPtr->SetLastError(
1905 VE_STOP_RECORDING_FAILED, kTraceError,
1906 "StopPlayingFile() could not stop playing");
1907 return -1;
1908 }
kwiberg5a25d952016-08-17 07:31:12 -07001909 output_file_player_->RegisterModuleFileCallback(NULL);
1910 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001911 channel_state_.SetOutputFilePlaying(false);
1912 }
1913 // _fileCritSect cannot be taken while calling
1914 // SetAnonymousMixibilityStatus. Refer to comments in
1915 // StartPlayingFileLocally(const char* ...) for more details.
1916 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1917 _engineStatisticsPtr->SetLastError(
1918 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1919 "StopPlayingFile() failed to stop participant from playing as"
1920 "file in the mixer");
1921 return -1;
1922 }
1923
1924 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001925}
1926
kwiberg55b97fe2016-01-28 05:22:45 -08001927int Channel::IsPlayingFileLocally() const {
1928 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001929}
1930
kwiberg55b97fe2016-01-28 05:22:45 -08001931int Channel::RegisterFilePlayingToMixer() {
1932 // Return success for not registering for file playing to mixer if:
1933 // 1. playing file before playout is started on that channel.
1934 // 2. starting playout without file playing on that channel.
1935 if (!channel_state_.Get().playing ||
1936 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001937 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001938 }
1939
1940 // |_fileCritSect| cannot be taken while calling
1941 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1942 // frames can be pulled by the mixer. Since the frames are generated from
1943 // the file, _fileCritSect will be taken. This would result in a deadlock.
1944 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1945 channel_state_.SetOutputFilePlaying(false);
1946 rtc::CritScope cs(&_fileCritSect);
1947 _engineStatisticsPtr->SetLastError(
1948 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1949 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001950 output_file_player_->StopPlayingFile();
1951 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001952 return -1;
1953 }
1954
1955 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001956}
1957
niklase@google.com470e71d2011-07-07 08:21:25 +00001958int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001959 bool loop,
1960 FileFormats format,
1961 int startPosition,
1962 float volumeScaling,
1963 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001964 const CodecInst* codecInst) {
1965 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1966 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1967 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1968 "stopPosition=%d)",
1969 fileName, loop, format, volumeScaling, startPosition,
1970 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001971
kwiberg55b97fe2016-01-28 05:22:45 -08001972 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001973
kwiberg55b97fe2016-01-28 05:22:45 -08001974 if (channel_state_.Get().input_file_playing) {
1975 _engineStatisticsPtr->SetLastError(
1976 VE_ALREADY_PLAYING, kTraceWarning,
1977 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001978 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001979 }
1980
1981 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001982 if (input_file_player_) {
1983 input_file_player_->RegisterModuleFileCallback(NULL);
1984 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001985 }
1986
1987 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001988 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07001989 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08001990
kwiberg5a25d952016-08-17 07:31:12 -07001991 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001992 _engineStatisticsPtr->SetLastError(
1993 VE_INVALID_ARGUMENT, kTraceError,
1994 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1995 return -1;
1996 }
1997
1998 const uint32_t notificationTime(0);
1999
kwiberg5a25d952016-08-17 07:31:12 -07002000 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002001 fileName, loop, startPosition, volumeScaling, notificationTime,
2002 stopPosition, (const CodecInst*)codecInst) != 0) {
2003 _engineStatisticsPtr->SetLastError(
2004 VE_BAD_FILE, kTraceError,
2005 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002006 input_file_player_->StopPlayingFile();
2007 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002008 return -1;
2009 }
kwiberg5a25d952016-08-17 07:31:12 -07002010 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002011 channel_state_.SetInputFilePlaying(true);
2012
2013 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002014}
2015
2016int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002017 FileFormats format,
2018 int startPosition,
2019 float volumeScaling,
2020 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002021 const CodecInst* codecInst) {
2022 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2023 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2024 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2025 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002026
kwiberg55b97fe2016-01-28 05:22:45 -08002027 if (stream == NULL) {
2028 _engineStatisticsPtr->SetLastError(
2029 VE_BAD_FILE, kTraceError,
2030 "StartPlayingFileAsMicrophone NULL as input stream");
2031 return -1;
2032 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002033
kwiberg55b97fe2016-01-28 05:22:45 -08002034 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002035
kwiberg55b97fe2016-01-28 05:22:45 -08002036 if (channel_state_.Get().input_file_playing) {
2037 _engineStatisticsPtr->SetLastError(
2038 VE_ALREADY_PLAYING, kTraceWarning,
2039 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002040 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002041 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002042
kwiberg55b97fe2016-01-28 05:22:45 -08002043 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002044 if (input_file_player_) {
2045 input_file_player_->RegisterModuleFileCallback(NULL);
2046 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002047 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002048
kwiberg55b97fe2016-01-28 05:22:45 -08002049 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002050 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002051 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002052
kwiberg5a25d952016-08-17 07:31:12 -07002053 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002054 _engineStatisticsPtr->SetLastError(
2055 VE_INVALID_ARGUMENT, kTraceError,
2056 "StartPlayingInputFile() filePlayer format isnot correct");
2057 return -1;
2058 }
2059
2060 const uint32_t notificationTime(0);
2061
kwiberg4ec01d92016-08-22 08:43:54 -07002062 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2063 notificationTime, stopPosition,
2064 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002065 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2066 "StartPlayingFile() failed to start "
2067 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002068 input_file_player_->StopPlayingFile();
2069 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002070 return -1;
2071 }
2072
kwiberg5a25d952016-08-17 07:31:12 -07002073 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002074 channel_state_.SetInputFilePlaying(true);
2075
2076 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002077}
2078
kwiberg55b97fe2016-01-28 05:22:45 -08002079int Channel::StopPlayingFileAsMicrophone() {
2080 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2081 "Channel::StopPlayingFileAsMicrophone()");
2082
2083 rtc::CritScope cs(&_fileCritSect);
2084
2085 if (!channel_state_.Get().input_file_playing) {
2086 return 0;
2087 }
2088
kwiberg5a25d952016-08-17 07:31:12 -07002089 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002090 _engineStatisticsPtr->SetLastError(
2091 VE_STOP_RECORDING_FAILED, kTraceError,
2092 "StopPlayingFile() could not stop playing");
2093 return -1;
2094 }
kwiberg5a25d952016-08-17 07:31:12 -07002095 input_file_player_->RegisterModuleFileCallback(NULL);
2096 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002097 channel_state_.SetInputFilePlaying(false);
2098
2099 return 0;
2100}
2101
2102int Channel::IsPlayingFileAsMicrophone() const {
2103 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002104}
2105
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002106int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002107 const CodecInst* codecInst) {
2108 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2109 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002110
kwiberg55b97fe2016-01-28 05:22:45 -08002111 if (_outputFileRecording) {
2112 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2113 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002114 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002115 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002116
kwiberg55b97fe2016-01-28 05:22:45 -08002117 FileFormats format;
2118 const uint32_t notificationTime(0); // Not supported in VoE
2119 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002120
kwiberg55b97fe2016-01-28 05:22:45 -08002121 if ((codecInst != NULL) &&
2122 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2123 _engineStatisticsPtr->SetLastError(
2124 VE_BAD_ARGUMENT, kTraceError,
2125 "StartRecordingPlayout() invalid compression");
2126 return (-1);
2127 }
2128 if (codecInst == NULL) {
2129 format = kFileFormatPcm16kHzFile;
2130 codecInst = &dummyCodec;
2131 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2132 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2133 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2134 format = kFileFormatWavFile;
2135 } else {
2136 format = kFileFormatCompressedFile;
2137 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002138
kwiberg55b97fe2016-01-28 05:22:45 -08002139 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002140
kwiberg55b97fe2016-01-28 05:22:45 -08002141 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002142 if (output_file_recorder_) {
2143 output_file_recorder_->RegisterModuleFileCallback(NULL);
2144 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002145 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002146
kwiberg5a25d952016-08-17 07:31:12 -07002147 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002148 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002149 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002150 _engineStatisticsPtr->SetLastError(
2151 VE_INVALID_ARGUMENT, kTraceError,
2152 "StartRecordingPlayout() fileRecorder format isnot correct");
2153 return -1;
2154 }
2155
kwiberg5a25d952016-08-17 07:31:12 -07002156 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002157 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2158 _engineStatisticsPtr->SetLastError(
2159 VE_BAD_FILE, kTraceError,
2160 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002161 output_file_recorder_->StopRecording();
2162 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002163 return -1;
2164 }
kwiberg5a25d952016-08-17 07:31:12 -07002165 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002166 _outputFileRecording = true;
2167
2168 return 0;
2169}
2170
2171int Channel::StartRecordingPlayout(OutStream* stream,
2172 const CodecInst* codecInst) {
2173 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2174 "Channel::StartRecordingPlayout()");
2175
2176 if (_outputFileRecording) {
2177 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2178 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002179 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002180 }
2181
2182 FileFormats format;
2183 const uint32_t notificationTime(0); // Not supported in VoE
2184 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2185
2186 if (codecInst != NULL && codecInst->channels != 1) {
2187 _engineStatisticsPtr->SetLastError(
2188 VE_BAD_ARGUMENT, kTraceError,
2189 "StartRecordingPlayout() invalid compression");
2190 return (-1);
2191 }
2192 if (codecInst == NULL) {
2193 format = kFileFormatPcm16kHzFile;
2194 codecInst = &dummyCodec;
2195 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2196 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2197 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2198 format = kFileFormatWavFile;
2199 } else {
2200 format = kFileFormatCompressedFile;
2201 }
2202
2203 rtc::CritScope cs(&_fileCritSect);
2204
2205 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002206 if (output_file_recorder_) {
2207 output_file_recorder_->RegisterModuleFileCallback(NULL);
2208 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002209 }
2210
kwiberg5a25d952016-08-17 07:31:12 -07002211 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002212 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002213 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002214 _engineStatisticsPtr->SetLastError(
2215 VE_INVALID_ARGUMENT, kTraceError,
2216 "StartRecordingPlayout() fileRecorder format isnot correct");
2217 return -1;
2218 }
2219
kwiberg4ec01d92016-08-22 08:43:54 -07002220 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002221 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002222 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2223 "StartRecordingPlayout() failed to "
2224 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002225 output_file_recorder_->StopRecording();
2226 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002227 return -1;
2228 }
2229
kwiberg5a25d952016-08-17 07:31:12 -07002230 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002231 _outputFileRecording = true;
2232
2233 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002234}
2235
kwiberg55b97fe2016-01-28 05:22:45 -08002236int Channel::StopRecordingPlayout() {
2237 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2238 "Channel::StopRecordingPlayout()");
2239
2240 if (!_outputFileRecording) {
2241 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2242 "StopRecordingPlayout() isnot recording");
2243 return -1;
2244 }
2245
2246 rtc::CritScope cs(&_fileCritSect);
2247
kwiberg5a25d952016-08-17 07:31:12 -07002248 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002249 _engineStatisticsPtr->SetLastError(
2250 VE_STOP_RECORDING_FAILED, kTraceError,
2251 "StopRecording() could not stop recording");
2252 return (-1);
2253 }
kwiberg5a25d952016-08-17 07:31:12 -07002254 output_file_recorder_->RegisterModuleFileCallback(NULL);
2255 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002256 _outputFileRecording = false;
2257
2258 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002259}
2260
kwiberg55b97fe2016-01-28 05:22:45 -08002261void Channel::SetMixWithMicStatus(bool mix) {
2262 rtc::CritScope cs(&_fileCritSect);
2263 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002264}
2265
kwiberg55b97fe2016-01-28 05:22:45 -08002266int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2267 int8_t currentLevel = _outputAudioLevel.Level();
2268 level = static_cast<int32_t>(currentLevel);
2269 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002270}
2271
kwiberg55b97fe2016-01-28 05:22:45 -08002272int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2273 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2274 level = static_cast<int32_t>(currentLevel);
2275 return 0;
2276}
2277
solenberg1c2af8e2016-03-24 10:36:00 -07002278int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002279 rtc::CritScope cs(&volume_settings_critsect_);
2280 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002281 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002282 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002283 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002284}
2285
solenberg1c2af8e2016-03-24 10:36:00 -07002286bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002287 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002288 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002289}
2290
kwiberg55b97fe2016-01-28 05:22:45 -08002291int Channel::SetOutputVolumePan(float left, float right) {
2292 rtc::CritScope cs(&volume_settings_critsect_);
2293 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002294 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002295 _panLeft = left;
2296 _panRight = right;
2297 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002298}
2299
kwiberg55b97fe2016-01-28 05:22:45 -08002300int Channel::GetOutputVolumePan(float& left, float& right) const {
2301 rtc::CritScope cs(&volume_settings_critsect_);
2302 left = _panLeft;
2303 right = _panRight;
2304 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002305}
2306
kwiberg55b97fe2016-01-28 05:22:45 -08002307int Channel::SetChannelOutputVolumeScaling(float scaling) {
2308 rtc::CritScope cs(&volume_settings_critsect_);
2309 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002310 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002311 _outputGain = scaling;
2312 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002313}
2314
kwiberg55b97fe2016-01-28 05:22:45 -08002315int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2316 rtc::CritScope cs(&volume_settings_critsect_);
2317 scaling = _outputGain;
2318 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002319}
2320
solenberg8842c3e2016-03-11 03:06:41 -08002321int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002322 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002323 "Channel::SendTelephoneEventOutband(...)");
2324 RTC_DCHECK_LE(0, event);
2325 RTC_DCHECK_GE(255, event);
2326 RTC_DCHECK_LE(0, duration_ms);
2327 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002328 if (!Sending()) {
2329 return -1;
2330 }
solenberg8842c3e2016-03-11 03:06:41 -08002331 if (_rtpRtcpModule->SendTelephoneEventOutband(
2332 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002333 _engineStatisticsPtr->SetLastError(
2334 VE_SEND_DTMF_FAILED, kTraceWarning,
2335 "SendTelephoneEventOutband() failed to send event");
2336 return -1;
2337 }
2338 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002339}
2340
solenbergffbbcac2016-11-17 05:25:37 -08002341int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2342 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002343 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002344 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002345 RTC_DCHECK_LE(0, payload_type);
2346 RTC_DCHECK_GE(127, payload_type);
2347 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002348 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002349 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002350 memcpy(codec.plname, "telephone-event", 16);
2351 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2352 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2353 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2354 _engineStatisticsPtr->SetLastError(
2355 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2356 "SetSendTelephoneEventPayloadType() failed to register send"
2357 "payload type");
2358 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002359 }
kwiberg55b97fe2016-01-28 05:22:45 -08002360 }
kwiberg55b97fe2016-01-28 05:22:45 -08002361 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002362}
2363
kwiberg55b97fe2016-01-28 05:22:45 -08002364int Channel::VoiceActivityIndicator(int& activity) {
2365 activity = _sendFrameType;
2366 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002367}
2368
kwiberg55b97fe2016-01-28 05:22:45 -08002369int Channel::SetLocalSSRC(unsigned int ssrc) {
2370 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2371 "Channel::SetLocalSSRC()");
2372 if (channel_state_.Get().sending) {
2373 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2374 "SetLocalSSRC() already sending");
2375 return -1;
2376 }
2377 _rtpRtcpModule->SetSSRC(ssrc);
2378 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002379}
2380
kwiberg55b97fe2016-01-28 05:22:45 -08002381int Channel::GetLocalSSRC(unsigned int& ssrc) {
2382 ssrc = _rtpRtcpModule->SSRC();
2383 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002384}
2385
kwiberg55b97fe2016-01-28 05:22:45 -08002386int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2387 ssrc = rtp_receiver_->SSRC();
2388 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002389}
2390
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002391int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002392 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002393 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002394}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002395
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002396int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2397 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002398 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2399 if (enable &&
2400 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2401 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002402 return -1;
2403 }
2404 return 0;
2405}
2406
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002407void Channel::EnableSendTransportSequenceNumber(int id) {
2408 int ret =
2409 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2410 RTC_DCHECK_EQ(0, ret);
2411}
2412
stefan3313ec92016-01-21 06:32:43 -08002413void Channel::EnableReceiveTransportSequenceNumber(int id) {
2414 rtp_header_parser_->DeregisterRtpHeaderExtension(
2415 kRtpExtensionTransportSequenceNumber);
2416 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2417 kRtpExtensionTransportSequenceNumber, id);
2418 RTC_DCHECK(ret);
2419}
2420
stefanbba9dec2016-02-01 04:39:55 -08002421void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002422 RtpPacketSender* rtp_packet_sender,
2423 TransportFeedbackObserver* transport_feedback_observer,
2424 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002425 RTC_DCHECK(rtp_packet_sender);
2426 RTC_DCHECK(transport_feedback_observer);
2427 RTC_DCHECK(packet_router && !packet_router_);
2428 feedback_observer_proxy_->SetTransportFeedbackObserver(
2429 transport_feedback_observer);
2430 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2431 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2432 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002433 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002434 packet_router_ = packet_router;
2435}
2436
stefanbba9dec2016-02-01 04:39:55 -08002437void Channel::RegisterReceiverCongestionControlObjects(
2438 PacketRouter* packet_router) {
2439 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002440 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002441 packet_router_ = packet_router;
2442}
2443
2444void Channel::ResetCongestionControlObjects() {
2445 RTC_DCHECK(packet_router_);
2446 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2447 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2448 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002449 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002450 packet_router_ = nullptr;
2451 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2452}
2453
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002454void Channel::SetRTCPStatus(bool enable) {
2455 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2456 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002457 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002458}
2459
kwiberg55b97fe2016-01-28 05:22:45 -08002460int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002461 RtcpMode method = _rtpRtcpModule->RTCP();
2462 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002463 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002464}
2465
kwiberg55b97fe2016-01-28 05:22:45 -08002466int Channel::SetRTCP_CNAME(const char cName[256]) {
2467 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2468 "Channel::SetRTCP_CNAME()");
2469 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2470 _engineStatisticsPtr->SetLastError(
2471 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2472 "SetRTCP_CNAME() failed to set RTCP CNAME");
2473 return -1;
2474 }
2475 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002476}
2477
kwiberg55b97fe2016-01-28 05:22:45 -08002478int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2479 if (cName == NULL) {
2480 _engineStatisticsPtr->SetLastError(
2481 VE_INVALID_ARGUMENT, kTraceError,
2482 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2483 return -1;
2484 }
2485 char cname[RTCP_CNAME_SIZE];
2486 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2487 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2488 _engineStatisticsPtr->SetLastError(
2489 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2490 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2491 return -1;
2492 }
2493 strcpy(cName, cname);
2494 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002495}
2496
kwiberg55b97fe2016-01-28 05:22:45 -08002497int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2498 unsigned int& NTPLow,
2499 unsigned int& timestamp,
2500 unsigned int& playoutTimestamp,
2501 unsigned int* jitter,
2502 unsigned short* fractionLost) {
2503 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002504
kwiberg55b97fe2016-01-28 05:22:45 -08002505 RTCPSenderInfo senderInfo;
2506 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2507 _engineStatisticsPtr->SetLastError(
2508 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2509 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2510 "side");
2511 return -1;
2512 }
2513
2514 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2515 // and octet count)
2516 NTPHigh = senderInfo.NTPseconds;
2517 NTPLow = senderInfo.NTPfraction;
2518 timestamp = senderInfo.RTPtimeStamp;
2519
2520 // --- Locally derived information
2521
2522 // This value is updated on each incoming RTCP packet (0 when no packet
2523 // has been received)
2524 playoutTimestamp = playout_timestamp_rtcp_;
2525
2526 if (NULL != jitter || NULL != fractionLost) {
2527 // Get all RTCP receiver report blocks that have been received on this
2528 // channel. If we receive RTP packets from a remote source we know the
2529 // remote SSRC and use the report block from him.
2530 // Otherwise use the first report block.
2531 std::vector<RTCPReportBlock> remote_stats;
2532 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2533 remote_stats.empty()) {
2534 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2535 "GetRemoteRTCPData() failed to measure statistics due"
2536 " to lack of received RTP and/or RTCP packets");
2537 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002538 }
2539
kwiberg55b97fe2016-01-28 05:22:45 -08002540 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2541 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2542 for (; it != remote_stats.end(); ++it) {
2543 if (it->remoteSSRC == remoteSSRC)
2544 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002545 }
kwiberg55b97fe2016-01-28 05:22:45 -08002546
2547 if (it == remote_stats.end()) {
2548 // If we have not received any RTCP packets from this SSRC it probably
2549 // means that we have not received any RTP packets.
2550 // Use the first received report block instead.
2551 it = remote_stats.begin();
2552 remoteSSRC = it->remoteSSRC;
2553 }
2554
2555 if (jitter) {
2556 *jitter = it->jitter;
2557 }
2558
2559 if (fractionLost) {
2560 *fractionLost = it->fractionLost;
2561 }
2562 }
2563 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002564}
2565
kwiberg55b97fe2016-01-28 05:22:45 -08002566int Channel::SendApplicationDefinedRTCPPacket(
2567 unsigned char subType,
2568 unsigned int name,
2569 const char* data,
2570 unsigned short dataLengthInBytes) {
2571 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2572 "Channel::SendApplicationDefinedRTCPPacket()");
2573 if (!channel_state_.Get().sending) {
2574 _engineStatisticsPtr->SetLastError(
2575 VE_NOT_SENDING, kTraceError,
2576 "SendApplicationDefinedRTCPPacket() not sending");
2577 return -1;
2578 }
2579 if (NULL == data) {
2580 _engineStatisticsPtr->SetLastError(
2581 VE_INVALID_ARGUMENT, kTraceError,
2582 "SendApplicationDefinedRTCPPacket() invalid data value");
2583 return -1;
2584 }
2585 if (dataLengthInBytes % 4 != 0) {
2586 _engineStatisticsPtr->SetLastError(
2587 VE_INVALID_ARGUMENT, kTraceError,
2588 "SendApplicationDefinedRTCPPacket() invalid length value");
2589 return -1;
2590 }
2591 RtcpMode status = _rtpRtcpModule->RTCP();
2592 if (status == RtcpMode::kOff) {
2593 _engineStatisticsPtr->SetLastError(
2594 VE_RTCP_ERROR, kTraceError,
2595 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2596 return -1;
2597 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002598
kwiberg55b97fe2016-01-28 05:22:45 -08002599 // Create and schedule the RTCP APP packet for transmission
2600 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2601 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2602 _engineStatisticsPtr->SetLastError(
2603 VE_SEND_ERROR, kTraceError,
2604 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2605 return -1;
2606 }
2607 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002608}
2609
kwiberg55b97fe2016-01-28 05:22:45 -08002610int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2611 unsigned int& maxJitterMs,
2612 unsigned int& discardedPackets) {
2613 // The jitter statistics is updated for each received RTP packet and is
2614 // based on received packets.
2615 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2616 // If RTCP is off, there is no timed thread in the RTCP module regularly
2617 // generating new stats, trigger the update manually here instead.
2618 StreamStatistician* statistician =
2619 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2620 if (statistician) {
2621 // Don't use returned statistics, use data from proxy instead so that
2622 // max jitter can be fetched atomically.
2623 RtcpStatistics s;
2624 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002625 }
kwiberg55b97fe2016-01-28 05:22:45 -08002626 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002627
kwiberg55b97fe2016-01-28 05:22:45 -08002628 ChannelStatistics stats = statistics_proxy_->GetStats();
2629 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2630 if (playoutFrequency > 0) {
2631 // Scale RTP statistics given the current playout frequency
2632 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2633 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2634 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002635
kwiberg55b97fe2016-01-28 05:22:45 -08002636 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002637
kwiberg55b97fe2016-01-28 05:22:45 -08002638 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002639}
2640
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002641int Channel::GetRemoteRTCPReportBlocks(
2642 std::vector<ReportBlock>* report_blocks) {
2643 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002644 _engineStatisticsPtr->SetLastError(
2645 VE_INVALID_ARGUMENT, kTraceError,
2646 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002647 return -1;
2648 }
2649
2650 // Get the report blocks from the latest received RTCP Sender or Receiver
2651 // Report. Each element in the vector contains the sender's SSRC and a
2652 // report block according to RFC 3550.
2653 std::vector<RTCPReportBlock> rtcp_report_blocks;
2654 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002655 return -1;
2656 }
2657
2658 if (rtcp_report_blocks.empty())
2659 return 0;
2660
2661 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2662 for (; it != rtcp_report_blocks.end(); ++it) {
2663 ReportBlock report_block;
2664 report_block.sender_SSRC = it->remoteSSRC;
2665 report_block.source_SSRC = it->sourceSSRC;
2666 report_block.fraction_lost = it->fractionLost;
2667 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2668 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2669 report_block.interarrival_jitter = it->jitter;
2670 report_block.last_SR_timestamp = it->lastSR;
2671 report_block.delay_since_last_SR = it->delaySinceLastSR;
2672 report_blocks->push_back(report_block);
2673 }
2674 return 0;
2675}
2676
kwiberg55b97fe2016-01-28 05:22:45 -08002677int Channel::GetRTPStatistics(CallStatistics& stats) {
2678 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002679
kwiberg55b97fe2016-01-28 05:22:45 -08002680 // The jitter statistics is updated for each received RTP packet and is
2681 // based on received packets.
2682 RtcpStatistics statistics;
2683 StreamStatistician* statistician =
2684 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002685 if (statistician) {
2686 statistician->GetStatistics(&statistics,
2687 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002688 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002689
kwiberg55b97fe2016-01-28 05:22:45 -08002690 stats.fractionLost = statistics.fraction_lost;
2691 stats.cumulativeLost = statistics.cumulative_lost;
2692 stats.extendedMax = statistics.extended_max_sequence_number;
2693 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002694
kwiberg55b97fe2016-01-28 05:22:45 -08002695 // --- RTT
2696 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002697
kwiberg55b97fe2016-01-28 05:22:45 -08002698 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002699
kwiberg55b97fe2016-01-28 05:22:45 -08002700 size_t bytesSent(0);
2701 uint32_t packetsSent(0);
2702 size_t bytesReceived(0);
2703 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002704
kwiberg55b97fe2016-01-28 05:22:45 -08002705 if (statistician) {
2706 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2707 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002708
kwiberg55b97fe2016-01-28 05:22:45 -08002709 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2710 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2711 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2712 " output will not be complete");
2713 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002714
kwiberg55b97fe2016-01-28 05:22:45 -08002715 stats.bytesSent = bytesSent;
2716 stats.packetsSent = packetsSent;
2717 stats.bytesReceived = bytesReceived;
2718 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002719
kwiberg55b97fe2016-01-28 05:22:45 -08002720 // --- Timestamps
2721 {
2722 rtc::CritScope lock(&ts_stats_lock_);
2723 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2724 }
2725 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002726}
2727
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002728int Channel::SetCodecFECStatus(bool enable) {
2729 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2730 "Channel::SetCodecFECStatus()");
2731
kwibergc8d071e2016-04-06 12:22:38 -07002732 if (!codec_manager_.SetCodecFEC(enable) ||
2733 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002734 _engineStatisticsPtr->SetLastError(
2735 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2736 "SetCodecFECStatus() failed to set FEC state");
2737 return -1;
2738 }
2739 return 0;
2740}
2741
2742bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002743 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002744}
2745
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002746void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2747 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002748 // If pacing is enabled we always store packets.
2749 if (!pacing_enabled_)
2750 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002751 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002752 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002753 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002754 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002755 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002756}
2757
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002758// Called when we are missing one or more packets.
2759int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002760 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2761}
2762
kwiberg55b97fe2016-01-28 05:22:45 -08002763uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2764 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2765 "Channel::Demultiplex()");
2766 _audioFrame.CopyFrom(audioFrame);
2767 _audioFrame.id_ = _channelId;
2768 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002769}
2770
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002771void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002772 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002773 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002774 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002775 CodecInst codec;
2776 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002777
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002778 // Never upsample or upmix the capture signal here. This should be done at the
2779 // end of the send chain.
2780 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2781 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2782 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2783 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002784}
2785
kwiberg55b97fe2016-01-28 05:22:45 -08002786uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2787 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2788 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002789
kwiberg55b97fe2016-01-28 05:22:45 -08002790 if (_audioFrame.samples_per_channel_ == 0) {
2791 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2792 "Channel::PrepareEncodeAndSend() invalid audio frame");
2793 return 0xFFFFFFFF;
2794 }
2795
2796 if (channel_state_.Get().input_file_playing) {
2797 MixOrReplaceAudioWithFile(mixingFrequency);
2798 }
2799
solenberg1c2af8e2016-03-24 10:36:00 -07002800 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2801 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002802
2803 if (channel_state_.Get().input_external_media) {
2804 rtc::CritScope cs(&_callbackCritSect);
2805 const bool isStereo = (_audioFrame.num_channels_ == 2);
2806 if (_inputExternalMediaCallbackPtr) {
2807 _inputExternalMediaCallbackPtr->Process(
2808 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2809 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2810 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002811 }
kwiberg55b97fe2016-01-28 05:22:45 -08002812 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002813
kwiberg55b97fe2016-01-28 05:22:45 -08002814 if (_includeAudioLevelIndication) {
2815 size_t length =
2816 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002817 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002818 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002819 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002820 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002821 rms_level_.Analyze(
2822 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002823 }
kwiberg55b97fe2016-01-28 05:22:45 -08002824 }
solenberg1c2af8e2016-03-24 10:36:00 -07002825 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002826
kwiberg55b97fe2016-01-28 05:22:45 -08002827 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002828}
2829
kwiberg55b97fe2016-01-28 05:22:45 -08002830uint32_t Channel::EncodeAndSend() {
2831 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2832 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002833
kwiberg55b97fe2016-01-28 05:22:45 -08002834 assert(_audioFrame.num_channels_ <= 2);
2835 if (_audioFrame.samples_per_channel_ == 0) {
2836 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2837 "Channel::EncodeAndSend() invalid audio frame");
2838 return 0xFFFFFFFF;
2839 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002840
kwiberg55b97fe2016-01-28 05:22:45 -08002841 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002842
kwiberg55b97fe2016-01-28 05:22:45 -08002843 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002844
kwiberg55b97fe2016-01-28 05:22:45 -08002845 // The ACM resamples internally.
2846 _audioFrame.timestamp_ = _timeStamp;
2847 // This call will trigger AudioPacketizationCallback::SendData if encoding
2848 // is done and payload is ready for packetization and transmission.
2849 // Otherwise, it will return without invoking the callback.
2850 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2851 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2852 "Channel::EncodeAndSend() ACM encoding failed");
2853 return 0xFFFFFFFF;
2854 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002855
kwiberg55b97fe2016-01-28 05:22:45 -08002856 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2857 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002858}
2859
solenberg7602aab2016-11-14 11:30:07 -08002860void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2861 RTC_DCHECK(!channel.channel() ||
2862 channel.channel()->ChannelId() != _channelId);
2863 rtc::CritScope lock(&assoc_send_channel_lock_);
2864 associate_send_channel_ = channel;
2865}
2866
Minyue2013aec2015-05-13 14:14:42 +02002867void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002868 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002869 Channel* channel = associate_send_channel_.channel();
2870 if (channel && channel->ChannelId() == channel_id) {
2871 // If this channel is associated with a send channel of the specified
2872 // Channel ID, disassociate with it.
2873 ChannelOwner ref(NULL);
2874 associate_send_channel_ = ref;
2875 }
2876}
2877
ivoc14d5dbe2016-07-04 07:06:55 -07002878void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2879 event_log_proxy_->SetEventLog(event_log);
2880}
2881
michaelt9332b7d2016-11-30 07:51:13 -08002882void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2883 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2884}
2885
michaelt79e05882016-11-08 02:50:09 -08002886void Channel::SetTransportOverhead(int transport_overhead_per_packet) {
2887 _rtpRtcpModule->SetTransportOverhead(transport_overhead_per_packet);
2888}
2889
kwiberg55b97fe2016-01-28 05:22:45 -08002890int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
2891 VoEMediaProcess& processObject) {
2892 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2893 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002894
kwiberg55b97fe2016-01-28 05:22:45 -08002895 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002896
kwiberg55b97fe2016-01-28 05:22:45 -08002897 if (kPlaybackPerChannel == type) {
2898 if (_outputExternalMediaCallbackPtr) {
2899 _engineStatisticsPtr->SetLastError(
2900 VE_INVALID_OPERATION, kTraceError,
2901 "Channel::RegisterExternalMediaProcessing() "
2902 "output external media already enabled");
2903 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002904 }
kwiberg55b97fe2016-01-28 05:22:45 -08002905 _outputExternalMediaCallbackPtr = &processObject;
2906 _outputExternalMedia = true;
2907 } else if (kRecordingPerChannel == type) {
2908 if (_inputExternalMediaCallbackPtr) {
2909 _engineStatisticsPtr->SetLastError(
2910 VE_INVALID_OPERATION, kTraceError,
2911 "Channel::RegisterExternalMediaProcessing() "
2912 "output external media already enabled");
2913 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002914 }
kwiberg55b97fe2016-01-28 05:22:45 -08002915 _inputExternalMediaCallbackPtr = &processObject;
2916 channel_state_.SetInputExternalMedia(true);
2917 }
2918 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002919}
2920
kwiberg55b97fe2016-01-28 05:22:45 -08002921int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
2922 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2923 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002924
kwiberg55b97fe2016-01-28 05:22:45 -08002925 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002926
kwiberg55b97fe2016-01-28 05:22:45 -08002927 if (kPlaybackPerChannel == type) {
2928 if (!_outputExternalMediaCallbackPtr) {
2929 _engineStatisticsPtr->SetLastError(
2930 VE_INVALID_OPERATION, kTraceWarning,
2931 "Channel::DeRegisterExternalMediaProcessing() "
2932 "output external media already disabled");
2933 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002934 }
kwiberg55b97fe2016-01-28 05:22:45 -08002935 _outputExternalMedia = false;
2936 _outputExternalMediaCallbackPtr = NULL;
2937 } else if (kRecordingPerChannel == type) {
2938 if (!_inputExternalMediaCallbackPtr) {
2939 _engineStatisticsPtr->SetLastError(
2940 VE_INVALID_OPERATION, kTraceWarning,
2941 "Channel::DeRegisterExternalMediaProcessing() "
2942 "input external media already disabled");
2943 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002944 }
kwiberg55b97fe2016-01-28 05:22:45 -08002945 channel_state_.SetInputExternalMedia(false);
2946 _inputExternalMediaCallbackPtr = NULL;
2947 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002948
kwiberg55b97fe2016-01-28 05:22:45 -08002949 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002950}
2951
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002952int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08002953 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2954 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002955
kwiberg55b97fe2016-01-28 05:22:45 -08002956 if (channel_state_.Get().playing) {
2957 _engineStatisticsPtr->SetLastError(
2958 VE_INVALID_OPERATION, kTraceError,
2959 "Channel::SetExternalMixing() "
2960 "external mixing cannot be changed while playing.");
2961 return -1;
2962 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002963
kwiberg55b97fe2016-01-28 05:22:45 -08002964 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002965
kwiberg55b97fe2016-01-28 05:22:45 -08002966 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002967}
2968
kwiberg55b97fe2016-01-28 05:22:45 -08002969int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2970 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002971}
2972
wu@webrtc.org24301a62013-12-13 19:17:43 +00002973void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2974 audio_coding_->GetDecodingCallStatistics(stats);
2975}
2976
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002977bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
2978 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08002979 rtc::CritScope lock(&video_sync_lock_);
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07002980 *jitter_buffer_delay_ms = audio_coding_->FilteredCurrentDelayMs();
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002981 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002982 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00002983}
2984
solenberg358057b2015-11-27 10:46:42 -08002985uint32_t Channel::GetDelayEstimate() const {
2986 int jitter_buffer_delay_ms = 0;
2987 int playout_buffer_delay_ms = 0;
2988 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
2989 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
2990}
2991
deadbeef74375882015-08-13 12:09:10 -07002992int Channel::LeastRequiredDelayMs() const {
2993 return audio_coding_->LeastRequiredDelayMs();
2994}
2995
kwiberg55b97fe2016-01-28 05:22:45 -08002996int Channel::SetMinimumPlayoutDelay(int delayMs) {
2997 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2998 "Channel::SetMinimumPlayoutDelay()");
2999 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3000 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3001 _engineStatisticsPtr->SetLastError(
3002 VE_INVALID_ARGUMENT, kTraceError,
3003 "SetMinimumPlayoutDelay() invalid min delay");
3004 return -1;
3005 }
3006 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3007 _engineStatisticsPtr->SetLastError(
3008 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3009 "SetMinimumPlayoutDelay() failed to set min playout delay");
3010 return -1;
3011 }
3012 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003013}
3014
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003015int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003016 uint32_t playout_timestamp_rtp = 0;
3017 {
tommi31fc21f2016-01-21 10:37:37 -08003018 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003019 playout_timestamp_rtp = playout_timestamp_rtp_;
3020 }
kwiberg55b97fe2016-01-28 05:22:45 -08003021 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003022 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07003023 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003024 "GetPlayoutTimestamp() failed to retrieve timestamp");
3025 return -1;
3026 }
deadbeef74375882015-08-13 12:09:10 -07003027 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003028 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003029}
3030
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003031int Channel::SetInitTimestamp(unsigned int timestamp) {
3032 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003033 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003034 if (channel_state_.Get().sending) {
3035 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3036 "SetInitTimestamp() already sending");
3037 return -1;
3038 }
3039 _rtpRtcpModule->SetStartTimestamp(timestamp);
3040 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003041}
3042
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003043int Channel::SetInitSequenceNumber(short sequenceNumber) {
3044 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3045 "Channel::SetInitSequenceNumber()");
3046 if (channel_state_.Get().sending) {
3047 _engineStatisticsPtr->SetLastError(
3048 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3049 return -1;
3050 }
3051 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3052 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003053}
3054
kwiberg55b97fe2016-01-28 05:22:45 -08003055int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3056 RtpReceiver** rtp_receiver) const {
3057 *rtpRtcpModule = _rtpRtcpModule.get();
3058 *rtp_receiver = rtp_receiver_.get();
3059 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003060}
3061
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003062// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3063// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003064int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003065 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003066 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003067
kwiberg55b97fe2016-01-28 05:22:45 -08003068 {
3069 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003070
kwiberg5a25d952016-08-17 07:31:12 -07003071 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003072 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3073 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3074 " doesnt exist");
3075 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003076 }
3077
kwiberg4ec01d92016-08-22 08:43:54 -07003078 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07003079 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003080 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3081 "Channel::MixOrReplaceAudioWithFile() file mixing "
3082 "failed");
3083 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003084 }
kwiberg55b97fe2016-01-28 05:22:45 -08003085 if (fileSamples == 0) {
3086 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3087 "Channel::MixOrReplaceAudioWithFile() file is ended");
3088 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003089 }
kwiberg55b97fe2016-01-28 05:22:45 -08003090 }
3091
3092 assert(_audioFrame.samples_per_channel_ == fileSamples);
3093
3094 if (_mixFileWithMicrophone) {
3095 // Currently file stream is always mono.
3096 // TODO(xians): Change the code when FilePlayer supports real stereo.
3097 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3098 1, fileSamples);
3099 } else {
3100 // Replace ACM audio with file.
3101 // Currently file stream is always mono.
3102 // TODO(xians): Change the code when FilePlayer supports real stereo.
3103 _audioFrame.UpdateFrame(
3104 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3105 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3106 }
3107 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003108}
3109
kwiberg55b97fe2016-01-28 05:22:45 -08003110int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3111 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003112
kwibergb7f89d62016-02-17 10:04:18 -08003113 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003114 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003115
kwiberg55b97fe2016-01-28 05:22:45 -08003116 {
3117 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003118
kwiberg5a25d952016-08-17 07:31:12 -07003119 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003120 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3121 "Channel::MixAudioWithFile() file mixing failed");
3122 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003123 }
3124
kwiberg55b97fe2016-01-28 05:22:45 -08003125 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07003126 if (output_file_player_->Get10msAudioFromFile(
3127 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003128 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3129 "Channel::MixAudioWithFile() file mixing failed");
3130 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003131 }
kwiberg55b97fe2016-01-28 05:22:45 -08003132 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003133
kwiberg55b97fe2016-01-28 05:22:45 -08003134 if (audioFrame.samples_per_channel_ == fileSamples) {
3135 // Currently file stream is always mono.
3136 // TODO(xians): Change the code when FilePlayer supports real stereo.
3137 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3138 fileSamples);
3139 } else {
3140 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3141 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3142 ") != "
3143 "fileSamples(%" PRIuS ")",
3144 audioFrame.samples_per_channel_, fileSamples);
3145 return -1;
3146 }
3147
3148 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003149}
3150
deadbeef74375882015-08-13 12:09:10 -07003151void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003152 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003153
henrik.lundin96bd5022016-04-06 04:13:56 -07003154 if (!jitter_buffer_playout_timestamp_) {
3155 // This can happen if this channel has not received any RTP packets. In
3156 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003157 return;
3158 }
3159
3160 uint16_t delay_ms = 0;
3161 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003162 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003163 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3164 " delay from the ADM");
3165 _engineStatisticsPtr->SetLastError(
3166 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3167 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3168 return;
3169 }
3170
henrik.lundin96bd5022016-04-06 04:13:56 -07003171 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3172 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003173
3174 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003175 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003176
kwiberg55b97fe2016-01-28 05:22:45 -08003177 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003178 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003179 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003180
3181 {
tommi31fc21f2016-01-21 10:37:37 -08003182 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003183 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003184 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003185 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003186 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003187 }
3188 playout_delay_ms_ = delay_ms;
3189 }
3190}
3191
kwiberg55b97fe2016-01-28 05:22:45 -08003192void Channel::RegisterReceiveCodecsToRTPModule() {
3193 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3194 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003195
kwiberg55b97fe2016-01-28 05:22:45 -08003196 CodecInst codec;
3197 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003198
kwiberg55b97fe2016-01-28 05:22:45 -08003199 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3200 // Open up the RTP/RTCP receiver for all supported codecs
3201 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003202 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003203 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3204 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3205 " to register %s (%d/%d/%" PRIuS
3206 "/%d) to RTP/RTCP "
3207 "receiver",
3208 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3209 codec.rate);
3210 } else {
3211 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3212 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3213 "(%d/%d/%" PRIuS
3214 "/%d) has been added to the RTP/RTCP "
3215 "receiver",
3216 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3217 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003218 }
kwiberg55b97fe2016-01-28 05:22:45 -08003219 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003220}
3221
kwiberg55b97fe2016-01-28 05:22:45 -08003222int Channel::SetSendRtpHeaderExtension(bool enable,
3223 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003224 unsigned char id) {
3225 int error = 0;
3226 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3227 if (enable) {
3228 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3229 }
3230 return error;
3231}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003232
ossue280cde2016-10-12 11:04:10 -07003233int Channel::GetRtpTimestampRateHz() const {
3234 const auto format = audio_coding_->ReceiveFormat();
3235 // Default to the playout frequency if we've not gotten any packets yet.
3236 // TODO(ossu): Zero clockrate can only happen if we've added an external
3237 // decoder for a format we don't support internally. Remove once that way of
3238 // adding decoders is gone!
3239 return (format && format->clockrate_hz != 0)
3240 ? format->clockrate_hz
3241 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003242}
3243
Minyue2013aec2015-05-13 14:14:42 +02003244int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003245 RtcpMode method = _rtpRtcpModule->RTCP();
3246 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003247 return 0;
3248 }
3249 std::vector<RTCPReportBlock> report_blocks;
3250 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003251
3252 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003253 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003254 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003255 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003256 Channel* channel = associate_send_channel_.channel();
3257 // Tries to get RTT from an associated channel. This is important for
3258 // receive-only channels.
3259 if (channel) {
3260 // To prevent infinite recursion and deadlock, calling GetRTT of
3261 // associate channel should always use "false" for argument:
3262 // |allow_associate_channel|.
3263 rtt = channel->GetRTT(false);
3264 }
3265 }
3266 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003267 }
3268
3269 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3270 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3271 for (; it != report_blocks.end(); ++it) {
3272 if (it->remoteSSRC == remoteSSRC)
3273 break;
3274 }
3275 if (it == report_blocks.end()) {
3276 // We have not received packets with SSRC matching the report blocks.
3277 // To calculate RTT we try with the SSRC of the first report block.
3278 // This is very important for send-only channels where we don't know
3279 // the SSRC of the other end.
3280 remoteSSRC = report_blocks[0].remoteSSRC;
3281 }
Minyue2013aec2015-05-13 14:14:42 +02003282
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003283 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003284 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003285 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003286 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3287 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003288 return 0;
3289 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003290 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003291}
3292
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003293} // namespace voe
3294} // namespace webrtc